Compare commits

..

312 Commits

Author SHA1 Message Date
Joseph T. Lyons
bfea1f2263 v0.107.x stable 2023-10-11 12:40:23 -04:00
Kirill Bulatov
5a2a92c7fe zed 0.107.6 2023-10-11 12:50:56 +03:00
Kirill Bulatov
ac96237806 Omit history files with path that does not exist on disk anymore (#3113) 2023-10-11 12:46:14 +03:00
Kirill Bulatov
596e2f307b Ignore history items' paths when matching search queries (#3107)
Follow-up of https://github.com/zed-industries/zed/pull/3059 

Before: 

![image](https://github.com/zed-industries/zed/assets/2690773/4eb2d2d1-1aa3-40b8-b782-bf2bc5f17b43)

After:

![image](https://github.com/zed-industries/zed/assets/2690773/5587d46b-9198-45fe-9372-114a95d4b7d6)

Release Notes:

- N/A
2023-10-11 12:43:47 +03:00
Antonio Scandurra
933537e912 zed 0.107.5 2023-10-11 08:27:53 +02:00
Antonio Scandurra
c44181d445 Revert outline summarization (#3114)
This pull request essentially reverts #3067: we noticed that only using
the function signatures produces far worse results in codegen, and so
that feels like a regression compared to before. We should re-enable
this once we have a smarter approach to fetching context during codegen,
possibly when #3097 lands.

As a drive-by, we also fixed a longstanding bug that caused codegen to
include the final line of a selection even if the selection ended at the
start of the line.

Ideally, I'd like to hot fix this to preview so that it goes to stable
during the weekly release.

/cc: @KCaverly @nathansobo 

Release Notes:

- N/A
2023-10-11 08:26:55 +02:00
Joseph T. Lyons
ad0e53aa6f Fix Discord text truncation 2023-10-11 01:54:54 -04:00
Max Brunsfeld
0f622417d7 zed 0.107.4 2023-10-10 15:56:19 -07:00
Max Brunsfeld
7ef8bd6377 Always log panics (#2896)
I just panicked and wanted to see the cause, but forgot that panic files
get deleted when Zed uploads them.

Release Notes:

- Panics are now written to `~/Library/Logs/Zed/Zed.log`
2023-10-10 15:55:31 -07:00
Max Brunsfeld
aed317840f Fix inclusion of spurious views from other projects in FollowResponse (#3116)
A logic error in https://github.com/zed-industries/zed/pull/2993 caused
follow responses to sometimes contain extra views for other unshared
projects 😱 . These views would generally fail to deserialize on the
other end. This would create a broken intermediate state, where the
following relationship was registered on the server (and on the leader's
client), but the follower didn't have the state necessary for following
into certain views.

Release Notes:

- Fixed a bug where following would sometimes fail if the leader had
another unshared project open.
2023-10-10 15:54:19 -07:00
Joseph T. Lyons
a15b9a55d2 Truncate Discord release note text (#3112)
Hopefully this works the first time 😅

Release Notes:

- N/A
2023-10-10 00:09:08 -04:00
Max Brunsfeld
91ee6b509f zed 0.107.3 2023-10-09 15:28:46 -07:00
Max Brunsfeld
78fe18acbc More small following-related fixes (#3110) 2023-10-09 15:27:25 -07:00
Kirill Bulatov
9d76ba445f Detect file paths that end with : (#3109)
New rustc messages look like

```
thread 'tests::test_history_items_vs_very_good_external_match' panicked at crates/file_finder/src/file_finder.rs:1902:13:
assertion `left == right` failed: Only one history item contains collab_ui, it should be present and others should be filtered out
  left: 0
 right: 1
```

now and we fail to parse that `13:` bit properly, fix that.

One caveat is that we highlight the entire word including the trailing
`:`:
<img width="914" alt="image"
src="https://github.com/zed-industries/zed/assets/2690773/d653a8ff-3e6e-4e3d-b6ea-dad0c8db0f06">

this is unfortunate, but better than nothing (as now).
This is due to the fact, that we detect words with regex inside the
`terminal.rs` and send events to other place that's able to check paths
for existence (and whether that's a path at all), currently there's no
way to detect a path and sanitize it in `terminal.rs`

Release Notes:

- N/A
2023-10-09 15:27:16 -07:00
Max Brunsfeld
b865efe3a3 Fix bug that allowed following multiple people in one pane (#3108)
I've also simplified the representation of a workspace's leaders, so
that it encodes in the type that there can only be one leader per pane.

Release Notes:

- Fixed a bug where you could accidentally follow multiple collaborators
in one pane at the same time.
2023-10-09 15:27:05 -07:00
Joseph T. Lyons
f92d44ed70 Use display name for release channel in panic events (#3101)
This was a mistake from long ago - something I've been meaning to fix
for a long time. All other events use `display_name()`, but panic
events, which leads to mistakes when filtering out `Zed Dev`, which
isn't the format that `dev_name()` returns. I'm adding a fix to zed.dev
as well:

- https://github.com/zed-industries/zed.dev/pull/393

so that the values are adjusted for all clients, not just ones with this
fix. I will correct the data in clickhouse, and adjust the queries in
metabase.

Release Notes:

- N/A
2023-10-06 14:20:29 -04:00
Joseph T. Lyons
62358b9bce Add session id to panic events (#3098)
Release Notes:

- N/A
2023-10-06 13:33:17 -04:00
Max Brunsfeld
df63290a32 Fix panic when immediately closing a window while opening paths (#3092)
Fixes this panic that I've been seeing in Slack:


[example](https://zed-industries.slack.com/archives/C04S6T1T7TQ/p1696530575535779)


```
thread 'main' panicked at 'assertion failed: opened_items.len() == project_paths_to_open.len()'
crates/workspace/src/workspace.rs:3628
<backtrace::capture::Backtrace>::create
<backtrace::capture::Backtrace>::new
Zed::init_panic_hook::{closure#0}
std::panicking::rust_panic_with_hook
std::panicking::begin_panic_handler::{{closure}}
std::sys_common::backtrace::__rust_end_short_backtrace
_rust_begin_unwind
core::panicking::panic_fmt
core::panicking::panic
<workspace::Workspace>::new_local::{closure#0}::{closure#0}
```

I believe it was caused by a window being closed immediately, while it
was still loading some paths. There was a mismatch in expectation
between the `workspace::open_items` function (which contains this
assertion), and the `Workspace::load_workspace` method. That later
method can return an empty vector if the workspace handle is dropped
while it is executing.

Release Notes:

- Fixed a crash when closing a Zed window immediately after opening it
2023-10-05 16:43:58 -07:00
Max Brunsfeld
6098f94dc1 zed 0.107.2 2023-10-05 16:03:07 -07:00
Mikayla Maki
6f4dee5b1d Add markdown parsing to channel chat (#3088)
TODO:
- [x] Add markdown rendering to channel chat
- [x] Unify (?) rendering logic between hover popover and chat
- [x] ~~Determine how to deal with document-oriented markdown like `#`~~
Unimportant until we want to do something special with `#channel`
- [x] Tidy up spacing and styles in chat panel

Release Notes:

- Added markdown rendering to channel chat
- Improved channel chat message style
- Fixed a bug where long chat messages would not soft wrap
2023-10-05 16:01:28 -07:00
Max Brunsfeld
4ca2645a54 Fix bugs in handling mutual following (#3091)
This fixes some bugs in our following logic, due to our attempts to
prevent infinite loops when two people follow each other.

* Propagate all of leader's views to a new follower, even if those views
were originally created by that follower.
* Propagate active view changes to followers, even if the active view is
following that follower.
* Avoid redundant active view updates on the client.

Release Notes:

- Fixed bugs where it was impossible to follow someone into a view that
they previously following you into.
2023-10-05 15:18:31 -07:00
Joseph T. Lyons
c41a3ec01b Add session id (#3090)
Release Notes:

- N/A
2023-10-05 15:51:18 -04:00
Mikayla
4edd0365a1 collab 0.22.2 2023-10-04 15:45:55 -07:00
Mikayla
cc4fb1c1b5 zed 0.107.1 2023-10-04 15:44:17 -07:00
Mikayla Maki
fc3d754aea Remove old code from notes icon click handler (#3085)
Release Notes:

- Fix clicking the notes icon when people are in the channel (preview
only)
2023-10-04 15:43:24 -07:00
Mikayla Maki
643f3db2b2 107 channel touch ups (#3087)
Release Notes:

- Add user avatars to channel chat messages
- Group messages by sender
- Fix visual bugs in new chat and note buttons
2023-10-04 15:43:16 -07:00
Max Brunsfeld
b90c04009f Ensure chat messages are retrieved in order of id (#3086)
Also, remove logic for implicitly marking chat messages as observed when
they are fetched. I think this is unnecessary, because the client always
explicitly acknowledges messages when they are shown.

Release Notes:

- Fixed a bug where chat messages were shown out of order (preview only)
2023-10-04 15:43:08 -07:00
Conrad Irwin
11f7a2cb0e Fix panic in increment (#3084)
Release Notes:

- Fixes a panic in vim when incrementing a non-number.
2023-10-04 15:40:30 -06:00
Joseph T. Lyons
8bdc59703a v0.107.x preview 2023-10-04 15:00:34 -04:00
Mikayla Maki
01b45f4f23 Show when a channel resource changes (#3074)
This PR adds a mechanism for notifying the client when a channel note
has been edited or a message has been changed.

TODO: 
- [x] Fix infinite loop when opening the chat panel
- [x] Switch to client-side ack model of observation detection
- [x] Add client-side-only change detection (e.g. for when a channel
note is open locally but not focused)
- [x] Review implementation / query performance.
- [x] Fix lack of ACK on restart for channel buffers
- [x] remove channel note opening on click
- [x] Fix channel messages sent while chat channel is in the background
not showing the channel as changed.

Release Notes:

- N/A
2023-10-04 11:57:33 -07:00
Mikayla
4d61d01943 Add an RPC handler for channel buffer acks
co-authored-by: max <max@zed.dev>
2023-10-04 11:47:13 -07:00
Mikayla
dd0edcd203 Changed the on-click behavior of joining a channel to not open the chat, and only open 1 project instead of all projects
Co-authored-by: conrad <conrad.irwin@gmail.com>
Co-authored-by: max <max@zed.dev>
2023-10-04 11:46:08 -07:00
Mikayla
e548572f12 Fix channel messages test 2023-10-04 10:13:02 -07:00
Mikayla
db8096ccdc Fix most tests for new chat changes 2023-10-03 20:50:17 -07:00
Mikayla
3bc7024f8b Fix unit test
co-authored-by: Conrad <conrad.irwin@gmail.com>
2023-10-03 20:03:57 -07:00
Mikayla
4ff80a7074 Fix a few mouse event id bugs and move facepile to the left
co-authored-by: conrad <conrad.irwin@gmail.com>
2023-10-03 19:45:33 -07:00
Mikayla
23ee8211c7 Lower frequency of popup warning when leaving a call
co-authored-by: conrad <conrad.irwin@gmail.com>
2023-10-03 19:30:05 -07:00
Max Brunsfeld
95342c8c33 Merge branch 'main' into channel-changes 2023-10-03 17:52:28 -07:00
Max Brunsfeld
61e0289014 Acknowledge channel notes and chat changes when views are active
Co-authored-by: Mikayla <mikayla@zed.dev>
2023-10-03 17:40:10 -07:00
Max Brunsfeld
af09861f5c Specify uuid crate in the root Cargo.toml
Co-authored-by: Mikayla <mikayla@zed.dev>
2023-10-03 17:39:24 -07:00
Conrad Irwin
55d2b9b3c9 join channels (#3082)
Release Notes:

- Clicking on a channel in the sidebar will now join the channel and
open the notes
- If you join a channel that already shared projects, you will join the
projects automatically and follow the host.
- Clicking on the current channel in the sidebar will re-open the notes.
- Chat can now be accessed from the right click menu of channels.


- (probably not worth mentioning) Various improvements to hover states
and tooltips in the collab ui; and if you click on a channel while in
another call, confirm before switching.
2023-10-03 13:54:11 -06:00
Conrad Irwin
044fb9e2f5 Confirm on switching channels 2023-10-03 13:45:48 -06:00
Mikayla
6007c8705c Upgrade SeaORM to latest version, also upgrade sqlite bindings, rustqlite, and remove SeaQuery
co-authored-by: Max <max@zed.dev>
2023-10-03 12:16:53 -07:00
Conrad Irwin
d696b394c4 Tooltips for contacts 2023-10-03 12:54:39 -06:00
Mikayla
32c4138758 Added db message and edit operation observation
Co-authored-by: Max <max@zed.dev>
2023-10-03 11:39:59 -07:00
Conrad Irwin
d8bfe77a3b Scroll so that collab panel is in good state for calls 2023-10-03 12:00:02 -06:00
Joseph T. Lyons
8b0969b698 Update cpu and memory event code (#3081)
Release Notes:

- N/A
2023-10-03 13:36:35 -04:00
Conrad Irwin
66dfa47c66 Update collab ui to join channels again 2023-10-03 11:36:01 -06:00
Joseph T. Lyons
b10255a6dd Update cpu and memory event code
Co-Authored-By: Julia <30666851+ForLoveOfCats@users.noreply.github.com>
2023-10-03 13:29:08 -04:00
Kyle Caverly
cf5d89d13c Leverage embeddings query to collapse syntax nodes if not selected (#3067)
Reverts zed-industries/zed#3049
2023-10-03 12:02:47 +03:00
KCaverly
9f160537ef move collapsed only matches outside item parent in embedding.scm 2023-10-03 11:56:45 +03:00
Conrad Irwin
18e7305b6d Change channel join behavior
- Clicking on a channel name now joins the channel if you are not in it
- (or opens the notes if you are already there).
- When joining a channel, previously shared projects are opened
  automatically.
- If there are no previously shared projects, the notes are opened.
2023-10-02 23:20:06 -06:00
Conrad Irwin
d9813a5bec show host in titlebar (#3072)
Release Notes:

- show host in the titlebar of shared projects
- clicking on faces in the titlebar will now always follow the person
(it used to toggle)
- clicking on someone in the channel panel will follow that person
- highlight the currently open project in the channel panel

- fixes a bug where sometimes following between workspaces would not
work
2023-10-02 21:02:02 -06:00
Conrad Irwin
d7867cd1e2 Add/fix mouse interactions in current call sidebar 2023-10-02 19:38:45 -06:00
Mikayla
32b4b4d24d Add message and operation ACK messages to protos 2023-10-02 17:10:03 -07:00
Joseph T. Lyons
7d32a717af Add memory and cpu events (#3080)
Release Notes:

- N/A
2023-10-02 19:42:49 -04:00
Joseph T. Lyons
892350fa2d Add memory and cpu events
Co-Authored-By: Julia <30666851+ForLoveOfCats@users.noreply.github.com>
2023-10-02 19:35:31 -04:00
Max Brunsfeld
0db4b29452 Avoid N+1 query for channels with new messages
Co-authored-by: Mikayla <mikayla@zed.dev>
2023-10-02 16:22:28 -07:00
Max Brunsfeld
d9d997b218 Avoid N+1 query for channels with notes changes
Also, start work on new timing for recording observed notes edits.

Co-authored-by: Mikayla <mikayla@zed.dev>
2023-10-02 15:58:34 -07:00
Max Brunsfeld
84c4db13fb Avoid spurious notifies in chat channel select
Co-authored-by: Mikayla <mikayla@zed.dev>
2023-10-02 15:57:59 -07:00
Conrad Irwin
528fa5c57b Refactor to remove toggle_follow 2023-10-02 16:51:02 -06:00
Conrad Irwin
27d784b23e Fix bug in following
Prior to this change you could only follow across workspaces when you
were heading to the first window.
2023-10-02 16:29:42 -06:00
Marshall Bowers
9e1f7c4c18 Mainline GPUI2 UI work (#3079)
This PR mainlines the current state of new GPUI2-based UI from the
`gpui2-ui` branch.

Release Notes:

- N/A

---------

Co-authored-by: Nate Butler <iamnbutler@gmail.com>
Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com>
Co-authored-by: Nate <nate@zed.dev>
2023-10-02 18:20:47 -04:00
Julia
08361eb84e Detach completion confirmation task when selecting with mouse (#3078)
Otherwise the spawn to resolve the additional edits never runs causing
autocomplete to never add imports automatically when clicking with the
mouse

Release Notes:

- Fixed auto-complete additional edits, such as auto-import, not
applying when selecting a completion with a mouse click.
2023-10-02 13:32:06 -04:00
Julia
3d68fcad0b Detach completion confirmation task when selecting with mouse
Otherwise the spawn to resolve the additional edits never runs causing
autocomplete to never add imports automatically when clicking with the
mouse
2023-10-02 13:18:49 -04:00
Conrad Irwin
7f44083a96 Remove unused function 2023-10-02 11:03:55 -06:00
Conrad Irwin
39af2bb0a4 Ensure notifications are dismissed
Before this change if you joined a project without clicking on the
notification it would never disappear.

Fix a related bug where if you have more than one monitor, the
notification was only dismissed from one of them.
2023-10-02 11:01:21 -06:00
Conrad Irwin
9dc292772a Add a screen for gpui tests
Allows me to test notifications
2023-10-02 09:53:30 -06:00
Antonio Scandurra
bf5d9e3224 Sort matches before processing them 2023-10-02 17:50:52 +02:00
Antonio Scandurra
d70014cfd0 Summarize file in the background 2023-10-02 15:36:10 +02:00
Piotr Osiewicz
a785eb9141 auto-update: Link to the current release's changelog, not the latest one (#3076)
An user complained in zed-industries/community#2093 that we always link
to the latest release changelog, not the one that they've just updated
to.


Release Notes:
- Fixed changelog link in update notification always leading to the
latest release changelog, not the one that was updated to. Fixes
zed-industries/community#2093.
2023-10-02 15:24:09 +02:00
Antonio Scandurra
f52200a340 Prevent deploying the inline assistant when selection spans multiple excerpts 2023-10-02 15:21:58 +02:00
Antonio Scandurra
df7ac9b815 💄 2023-10-02 14:36:16 +02:00
Antonio Scandurra
64a55681e6 Summarize the contents of a file using the embedding query 2023-10-02 14:32:13 +02:00
Mikayla
1d5b665f13 Implement channel changes for messages 2023-10-01 22:32:11 -07:00
Mikayla
51cf6a5ff3 Add database implementation of channel message change tracking 2023-10-01 22:32:11 -07:00
Mikayla
e0ff7ba180 Add channel note indicator and clear changed status 2023-10-01 22:32:10 -07:00
Mikayla
9ba975d6ad Channel notifications from the server works 2023-10-01 22:30:21 -07:00
Mikayla
1469c02998 Add observed_channel_notes table and implement note diffing 2023-10-01 22:26:27 -07:00
Joseph T. Lyons
95e09dd2e9 Add Nushell support to venv activation (#3073)
This PR adds an option to run `activate.nu` in the automatic venv
activation code (relevant comment
[here](https://github.com/zed-industries/community/issues/2103#issuecomment-1742355651))

Release Notes:

- Added a `nushell` option to the
`terminal.detect_venv.on.activate_script` setting
([2103](https://github.com/zed-industries/community/issues/2103)).
2023-10-01 23:55:57 -04:00
Joseph T. Lyons
e5e63ed201 Add Nushell support to venv activation 2023-10-01 23:38:30 -04:00
Conrad Irwin
92bb9a5fdc Make following more good
Co-Authored-By: Max Brunsfeld <max@zed.dev>
2023-09-29 17:59:19 -06:00
Conrad Irwin
1cfc2f0c07 Show host in titlebar
Co-Authored-By: Max Brunsfeld <max@zed.dev>
2023-09-29 16:37:00 -06:00
Conrad Irwin
219715449d More logging on collab by default 2023-09-29 16:37:00 -06:00
Max Brunsfeld
f011a3df52 Allow following participants who aren't in the same project (#2993)
The goal of this PR is to make Following more intuitive.

### Old Behavior

Previously, following was scoped to a project. In order to follow
someone in a given window, the window needed to contain a shared
project, and the leader needed to be present in the project. Otherwise,
following failed.

### New Behavior

* You can always follow **any** participant in the current call, in any
pane of any window.
* When following someone in a project that you're both collaborating in,
it works the same as before.
* When following someone in an unshared project, or a project that they
don't have open, you'll only get updates about the leader's views that
don't belong to a project, such as channel notes views. When the leader
focuses a file in a different project, you'll get the "follow $LEADER to
their active project" indicator

### Todo

* [x] Change db schema and RPC protocol so a project id isn't required
for following
* [x] Change client to allow following into non-project items regardless
of the leader's project
* [x] Assign colors to users in a way that doesn't require users to be
in a shared project.
2023-09-29 15:18:05 -07:00
Max Brunsfeld
7adaa2046d Show current user as follower when following in unshared projects 2023-09-29 15:08:25 -07:00
Max Brunsfeld
948871969f Fix active view update when center pane is not focused 2023-09-29 14:37:28 -07:00
Mikayla Maki
57707a80e6 Refactor elixir LSP settings (#3071)
This PR is a bit of a last minute change, but I realized there was
actually a third player in the Elixir LSP space who wants support as
well,
[lexical](https://github.com/zed-industries/community/issues/1567). I
realized that the settings arrangement I shipped in this preview
precludes adding a third kind of LSP. I don't have the time to learn how
to fully support this LSP, but I thought I'd at least refactor how the
settings are represented before this hits stable.

Release Notes:

- Changed the new `"elixir": { "next": "on" }` setting to `"elixir": {
"lsp": "next_ls" }`. The `elixir.lsp` setting requires a full restart to
take effect. (Preview only)
2023-09-29 14:25:05 -07:00
Max Brunsfeld
55da5bc25d Switch .leader_replica_id -> .leader_peer_id 2023-09-29 14:16:38 -07:00
Max Brunsfeld
c718b810f6 Merge branch 'main' into allow-following-outside-of-projects 2023-09-29 14:15:33 -07:00
Max Brunsfeld
afd293ee87 Update active view when activating a window 2023-09-29 14:12:51 -07:00
Mikayla
752bc5dcdd Refactor elixir LSP settings 2023-09-29 14:12:50 -07:00
Max Brunsfeld
973f03e73e Fix bug in follower updates for non-project items 2023-09-29 14:09:14 -07:00
Max Brunsfeld
555c9847d4 Add ZED_ALWAYS_ACTIVE env var, use it in local collaboration script
This makes zed always behave as if the app is active, even if no window is focused.
It prevents the 'viewing a window outside of zed' state during collaboration.
2023-09-29 13:43:43 -07:00
Conrad Irwin
d9c1cf9874 vim: Fix accidental visual selection when following (#3068)
Release Notes:

- vim: Fix a bug where following could put you in visual mode
2023-09-29 13:59:59 -06:00
Mikayla Maki
1155f1b0e1 Add support for the TextDocumentSyncKind LSP option (#3070)
fixes https://github.com/zed-industries/community/issues/2098

Release Notes:

- Fixed a bug in Zed's LSP implementation when using Next LS.
2023-09-29 12:25:37 -07:00
Mikayla
31ff5bffd6 Fix tests relying on off-spec behavior 2023-09-29 12:19:58 -07:00
Mikayla
4887ea3563 Add support for the TextDocumentSyncKind LSP options 2023-09-29 12:05:21 -07:00
Kyle Caverly
dbaaf4216d add scheme for full parseable files in semantic index (#3069)
add scheme as a parseable file type in semantic index.
Each file will operate as a single embedding, in which no real scheme
syntax or tree-sitter level data is stored.

Release Notes:

- Added scheme to Semantic Index
2023-09-29 14:42:15 -04:00
Antonio Scandurra
53c25690f9 WIP: Use a different approach to codegen outline 2023-09-29 20:37:07 +02:00
KCaverly
3c12e711a4 add scheme for full parseable files in semantic index 2023-09-29 14:35:02 -04:00
Conrad Irwin
9b7bd4e9ae vim: Fix accidental visual selection when following 2023-09-29 12:08:25 -06:00
Max Brunsfeld
026b3a1d0f Remove uneeded Workspace::project_remote_id_changed method 2023-09-29 08:54:23 -07:00
Antonio Scandurra
d9c08de58a Revert "Revert "leverage file outline and selection as opposed to entire file"" 2023-09-29 17:15:26 +02:00
Marshall Bowers
c379a6f2fb ui: Fix glyph used for option key in Keybinding (#3066)
This PR fixes the glyph used for the option key in the new `Keybinding`
component.

Same fix as in #3065, but applied to the new `Keybinding` component so
that we don't regress when switching to GPUI2.

<img width="750" alt="Screenshot 2023-09-29 at 10 50 15 AM"
src="https://github.com/zed-industries/zed/assets/1486634/8c6147e9-fa05-4804-954c-b8e3b98cbdf0">

Release Notes:

- N/A
2023-09-29 11:02:35 -04:00
Piotr Osiewicz
488a3eeace ui: Mirror option key in keybindings (#3065)
![image](https://github.com/zed-industries/zed/assets/24362066/94731737-a21a-4cef-a445-eb855f1a4d3e)

![image](https://github.com/zed-industries/zed/assets/24362066/e879ec9a-70aa-4989-923f-4cca18d01587)

Release Notes:

- Fixed option key's appearance in keybindings
2023-09-29 16:45:49 +02:00
Antonio Scandurra
4dd9c9e2b9 Introduce the ability to include or exclude warnings from project diagnostics (#3056)
![CleanShot 2023-09-27 at 18 09
37](https://github.com/zed-industries/zed/assets/482957/317d31e4-81f8-44d8-b94f-8ca7150d3fd2)

Release Notes:

- Added the ability to exclude warnings from project diagnostics. By
default, they will be on but they can be disabled temporarily by
clicking on the warnings icon. The default behavior can be changed by
changing the new `diagnostics.include_warnings` setting.
2023-09-29 13:13:04 +01:00
Max Brunsfeld
ca0a4bdf8e Introduce a WorkspaceStore for handling following 2023-09-28 18:58:52 -07:00
Marshall Bowers
247c7eff14 storybook: Fix kitchen sink story (#3064)
This PR fixes the kitchen sink story in the storybook.

Included are some additional changes that make it so the kitchen sink is
automatically populated by all of the defined stories.

Release Notes:

- N/A
2023-09-28 21:22:50 -04:00
Max Brunsfeld
837ec5a27c Remove stray file 2023-09-28 17:14:53 -07:00
Max Brunsfeld
5a15692589 🎨 Workspace::leader_updated 2023-09-28 17:13:10 -07:00
Max Brunsfeld
0058702749 Remove unused db query method 2023-09-28 17:13:10 -07:00
Max Brunsfeld
e34ebbc665 Remove unused dependencies on theme 2023-09-28 17:13:10 -07:00
Max Brunsfeld
38a9e6fde1 Fix removal of followers on Unfollow 2023-09-28 16:46:43 -07:00
Marshall Bowers
f26ca0866c Mainline GPUI2 UI work (#3062)
This PR mainlines the current state of new GPUI2-based UI from the
`gpui2-ui` branch.

Release Notes:

- N/A

---------

Co-authored-by: Nate Butler <iamnbutler@gmail.com>
Co-authored-by: Max Brunsfeld <maxbrunsfeld@gmail.com>
Co-authored-by: Marshall Bowers <1486634+maxdeviant@users.noreply.github.com>
Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com>
Co-authored-by: Nate <nate@zed.dev>
Co-authored-by: Mikayla <mikayla@zed.dev>
2023-09-28 19:36:21 -04:00
Conrad Irwin
e7ee8a95f6 vim: Fix some dw edge cases (#3058)
Release Notes:

- vim: Fix `dw` on the last word of a line, and on empty lines.
2023-09-28 15:32:29 -06:00
Conrad Irwin
91adefedfa vim keybinding updates (#3057)
Release Notes:

- vim: Add ctrl-i to go forward
([#1732](https://github.com/zed-industries/community/issues/1732)).
ctrl-o was already supported.
- vim: Add `g <space>` to open the current snippet in its own file.
- vim: Escape will now return to normal mode even if completion menus
are open (use `ctrl-x ctrl-z` to hide menus, as in vim).
- vim: Add key bindings for Zed's various completion mechanisms:
- - `ctrl-x ctrl-o` to open the completion menu,
- -  `ctrl-x ctrl-l` to open the LSP action menu,
- - `ctrl-x ctrl-c` to trigger Copilot (requires configuring copilot),
- - `ctrl-x ctrl-a` to trigger the inline Assistant (requires
configuring openAI),

NOTE: we should add these to the docs before shipping 0.107 to stable.
2023-09-28 15:32:21 -06:00
Conrad Irwin
2f5eaa8475 vim increment (#3054)
- vim: add ctrl-a/ctrl-x for increment/decrement
2023-09-28 15:32:11 -06:00
Joseph T. Lyons
da964fae93 Enable semantic_index by default (#3061)
Release Notes:

- Enabled the `semantic_index` setting by default.
2023-09-28 17:24:00 -04:00
Max Brunsfeld
e9c1ad6acd Undo making project optional on stored follower states
Following works without a project, but following in unshared projects does
not need to be replicated to other participants.
2023-09-28 14:21:44 -07:00
Joseph T. Lyons
f965ee9b1b Enable semantic_index by default 2023-09-28 17:17:26 -04:00
Max Brunsfeld
ce940da8e9 Fix errors from assuming all room_participant rows had a non-null participant_index
Rows representing pending participants have a null participant_index.

Co-authored-by: Conrad <conrad@zed.dev>
2023-09-28 12:03:53 -07:00
Max Brunsfeld
a8b35eb8f5 Merge branch 'main' into allow-following-outside-of-projects 2023-09-28 11:58:28 -07:00
Max Brunsfeld
0c95e5a6ca Fix coloring of local selections when following
Co-authored-by: Conrad <conrad@zed.dev>
2023-09-28 11:37:47 -07:00
Max Brunsfeld
0f39b63801 Rename color_index to participant_index
Co-authored-by: Conrad <conrad@zed.dev>
2023-09-28 11:37:22 -07:00
Max Brunsfeld
545b5e0161 Assign unique color indices to room participants, use those instead of replica_ids
Co-authored-by: Conrad <conrad@zed.dev>
Co-authored-by: Antonio <antonio@zed.dev>
2023-09-28 11:06:09 -07:00
Joseph T. Lyons
3cf7164a54 Fix text transformation commands for multiple line, single selection cases (#3060)
If you highlight the following block of text (with a single selection):

```
The quick brown
fox jumps over
the lazy dog
```

and run `editor: convert to upper camel case`, you'll get:

```
TheQuickBrown
foxJumpsOver
theLazyDog
```

instead of:

```
TheQuickBrown
FoxJumpsOver
TheLazyDog
```

The same thing happens for `editor: convert to title case`. This happens
because [`to_case` crate](https://crates.io/crates/convert_case) doesn't
allow the user to define '\n' as a boundary. I wanted to fix this at the
lib level, so I filled [an
issue](https://github.com/rutrum/convert-case/issues/16) but I never
heard back. What's strange is VS Code and Sublime I think both exhibit
the same output as we do currently, but I don't personally think this
feels right (happy to hear opposing opinions). I'm just doing the naive
thing to hack around this limitation of the `to_case` crate.

I did some testing and it seems I only need to adjust `editor: convert
to title case` and `editor: convert to upper camel case`. The way the
other transformations are implemented in `to_case` don't seem to have
this issue.

Release Notes:

- Fixed a bug where running certain text transfomration commands on a
single selection covering multiple lines would not transform all
selected lines as expected.
2023-09-28 14:04:17 -04:00
Kirill Bulatov
a8188a2f33 Improve file finder ergonomics (#3059)
Deals with https://github.com/zed-industries/community/issues/2086
Part of https://github.com/zed-industries/community/issues/351

Initial:
<img width="585" alt="Screenshot 2023-09-28 at 09 50 05"
src="https://github.com/zed-industries/zed/assets/2690773/e0149312-dfe3-4b7c-948c-0f593d6f540c">
First query letter input (only two history items match that, both are
preserved on top, with their order preserved also)
<img width="603" alt="Screenshot 2023-09-28 at 09 50 08"
src="https://github.com/zed-industries/zed/assets/2690773/85ab2f4c-bb9c-4811-b8b0-b5c14a370ae2">
Second query letter input, no matching history items:
<img width="614" alt="Screenshot 2023-09-28 at 09 50 11"
src="https://github.com/zed-industries/zed/assets/2690773/6d380403-a43c-4f00-a05b-88f43f91fefb">
Remove second query letter, history items match again and pop to the
top:
<img width="574" alt="Screenshot 2023-09-28 at 09 50 15"
src="https://github.com/zed-industries/zed/assets/2690773/5981ca53-6bc8-4305-ae36-27144080e1a2">


* allows `file_finder::Toggle` (cmd-p by default) to cycle through file
finder items (ESC closes the modal still)
* on query typing, preserve history items that match the query and keep
them on top, with their ordering preserved
* show history items' matched letters

Release Notes:

- Improve file finder ergonomics: allow cycle through items with the
toggle action, preserve matching history items on query input
2023-09-28 19:53:09 +03:00
Kirill Bulatov
d30385f07c Show path matches inside history items matching the query 2023-09-28 09:49:25 -07:00
Kirill Bulatov
1b5ff68c43 Show matching search history whenever possible 2023-09-28 09:34:20 -07:00
Kirill Bulatov
97eabe6f81 Add tests 2023-09-28 09:00:25 -07:00
Kirill Bulatov
57a95d1799 Preserve matching history items and their order 2023-09-28 06:55:49 -07:00
Kirill Bulatov
541dd994a9 Cycle file finder entries on cmd-p 2023-09-28 06:55:49 -07:00
Piotr Osiewicz
81a107f503 assets: Add keybinds to replace (#3055)
Release Notes:

- N/A
2023-09-28 13:04:14 +02:00
Conrad Irwin
768c991909 vim: Fix some dw edge cases 2023-09-27 23:09:09 -06:00
Conrad Irwin
51b24bbaf3 Add vim-style completion bindings: 2023-09-27 21:29:18 -06:00
Conrad Irwin
2cb320e246 Escape returns to normal mode even if completion is open
For zed-industries/community#1746
2023-09-27 21:28:30 -06:00
Conrad Irwin
73fc1c1c56 Add g space for option-enter
vimify all the things
2023-09-27 21:05:58 -06:00
Conrad Irwin
d1baff1743 Add ctrl-i to go forward
For zed-industries/community#1732
2023-09-27 21:04:13 -06:00
Conrad Irwin
dd1cf5c3cf vim: add ctrl-a/ctrl-x
For zed-industries/community#1411
For zed-industries/community#619
2023-09-27 19:49:31 -06:00
Conrad Irwin
9246c11c35 Don't prompt to save unchanged files (#3053)
- don't prompt to save a set of unchanged files when closing
(preview-only)
2023-09-27 19:20:08 -06:00
Antonio Scandurra
0e6002dca2 Fix tests 2023-09-27 18:19:35 -06:00
Antonio Scandurra
78908bc5cb Introduce a new include_warnings setting under diagnostics 2023-09-27 18:08:08 -06:00
Antonio Scandurra
f603d682cd Add an include/exclude warnings toggle in project diagnostics 2023-09-27 17:47:19 -06:00
Conrad Irwin
6cebcac805 fix tests 2023-09-27 17:02:47 -06:00
Conrad Irwin
3573896fe0 Don't prompt to save unchanged files 2023-09-27 16:07:35 -06:00
Conrad Irwin
25429f760c ctrl-a/x for vim 2023-09-27 12:32:01 -06:00
Joseph T. Lyons
ece4875973 v0.107.x dev 2023-09-27 12:26:48 -04:00
Kyle Caverly
2c0547079a Revert "leverage file outline and selection as opposed to entire file" (#3049)
Reverts zed-industries/zed#3040
2023-09-27 12:21:11 -04:00
Kyle Caverly
b3b3a56164 Revert "leverage file outline and selection as opposed to entire file" 2023-09-27 12:21:03 -04:00
Kyle Caverly
4242b45646 Revert "removed stale dbg in assistant from main" (#3048)
Reverts zed-industries/zed#3046
2023-09-27 12:19:54 -04:00
Kyle Caverly
cab80cbe9d Revert "removed stale dbg in assistant from main" 2023-09-27 12:19:44 -04:00
Julia
d671a8a21d Bump update notification size back up (#3047)
Regressed:
<img width="422" alt="CleanShot 2023-09-27 at 11 07 37@2x"
src="https://github.com/zed-industries/zed/assets/30666851/636d7bec-4518-45e6-87bd-84b45dda28e1">

Fixed:
<img width="424" alt="CleanShot 2023-09-27 at 11 04 13@2x"
src="https://github.com/zed-industries/zed/assets/30666851/186a1d49-4daf-4211-891a-dacfd1144311">

Release Notes:

- N/A
2023-09-27 11:25:16 -04:00
Julia
6b88ac9c32 Bump update notification size back up 2023-09-27 11:04:25 -04:00
Piotr Osiewicz
6ccaf55e54 search: Reorder items in search bar (#3039)
Release Notes:

- Reordered items in project and buffer search bar
2023-09-27 16:51:20 +02:00
Kyle Caverly
edf29aa67d implement new search strategy (#3029)
Augment current search strategy in semantic search, reducing search
times by ~60%

Release Notes:

- Implemented minimum batch sizes for concurrent database reads.
- Batch embedding matrix multiplication.
- Calculate matmul with ndarray
2023-09-27 10:37:48 -04:00
KCaverly
0e6fd645fd leverage embeddings len returned in construction matrix multiplication 2023-09-27 10:33:04 -04:00
Conrad Irwin
c63cc78ffd vim: Fix ctrl-u/ctrl-d (#3044)
- vim: Fix ctrl-d/ctrl-u to match vim (when :set scrolloff=3)
2023-09-27 07:48:50 -06:00
KCaverly
3682751455 Merge branch 'main' of github.com:zed-industries/zed into faster_semantic_search 2023-09-27 09:43:39 -04:00
KCaverly
abefa2738b removed blas and increase batch size for vector search 2023-09-27 09:43:23 -04:00
Kyle Caverly
4ccd69350b removed stale dbg in assistant from main (#3046)
remove small dbg! statement in main
2023-09-27 09:13:41 -04:00
KCaverly
0d6880adb3 removed stale dbg in assistant from main 2023-09-27 09:13:00 -04:00
Kyle Caverly
2f368de397 leverage file outline and selection as opposed to entire file (#3040)
Transition generate prompt for inline assist to leverage outline as
opposed to full file.
This enables, us to leverage the inline assist for large files.

Release Notes:

- Change inline assist to use tree-sitter based outlines for code
generation instead of full files
2023-09-27 09:10:18 -04:00
KCaverly
650a160f04 update test outline for prompt tests for new cursor span 2023-09-27 09:06:53 -04:00
Piotr Osiewicz
ecb037fc0e language: Add block_comment to CSS (#3045)
Fixes zed-industries/community#2081

Release Notes:
- Fixed "toggle comment" action not working in CSS buffers.
2023-09-27 11:56:26 +02:00
Conrad Irwin
8e1bbf32be vim: Fix ctrl-u/ctrl-d
They should work by exactly half a screen, and also move the cursor.
2023-09-26 22:28:04 -06:00
Conrad Irwin
30bb3a109e Add SwapPaneInDirection (#3043)
- Add cmd-k shift-{left,right,up,down} to swap panes in that direction
- vim: Add ctrl-w shift-{h,j,k,l} to swap panes in that direction
([#278](https://github.com/zed-industries/community/issues/278))
2023-09-26 22:18:02 -06:00
Conrad Irwin
37b6e1cbb7 Add SwapPaneInDirection
Add keybindings for vim (and non-vim)
2023-09-26 22:00:51 -06:00
Kirill Bulatov
cb83b49432 Hide inlay hints toggle if they are not supported by the current editor (#3041)
Release Notes:

- N/A
2023-09-27 01:16:02 +03:00
Marshall Bowers
568fec0f54 Add Sized bound to StyleHelpers (#3042)
This PR adds a `Sized` bound to the `StyleHelpers` trait.

All of the individual methods on this trait already had a `Self: Sized`
bound, so moving it up to the trait level will make it so we don't have
to repeat ourselves so much.

There's an open question of whether we can hoist the `Sized` bound to
`Styleable`, but it's possible there are cases where we'd want to have a
`Styleable` trait object.

Release Notes:

- N/A
2023-09-26 18:15:41 -04:00
Kirill Bulatov
7e2cef98a7 Hide inlay hints toggle if they are not supported by the current editor 2023-09-26 23:52:11 +02:00
KCaverly
90f17d4a28 updated codegen match to leverage unused values 2023-09-26 17:11:20 -04:00
KCaverly
e8dd412ac1 update inline generate prompt to leverage more explicit <|START| and |END|> spans 2023-09-26 17:10:31 -04:00
KCaverly
54c63063e4 changed inline assist generate prompt to leverage outline as opposed to entire prior file
Co-Authored-by: Antonio <antonio@zed.dev>
2023-09-26 16:23:48 -04:00
Joseph T. Lyons
e9e558d8c8 Rework call events api (#3038)
There were times when events with bad data were being emitted. What we
found was that places where certain collaboration-related code could
fail, like sending an invite, would still send events; those events
would be in a bad state, as certain elements, such as a room, weren't
constructed as expected, causing the event to have missing data. The new
API guarantees that we have data in the correct configuration. In the
future, we will add events for certain types of failures within Zed, to
cover things like invites failing.

Release Notes:

- N/A
2023-09-26 14:29:25 -04:00
Joseph T. Lyons
0897ed561f Rework call events api
There were time when events with bad data were being emitted. What we found was that places where certain collaboration-related code could fail, like sending an, would still send events, and those events be in a bad state, as certain elements weren't constructed as expected, thus missing in the event. The new API guarantees that we have data in the correct configuration. In the future, we will add events for certain types of failures within Zed.

Co-Authored-By: Julia <30666851+ForLoveOfCats@users.noreply.github.com>
2023-09-26 14:18:32 -04:00
Piotr Osiewicz
e263805847 workspace: change save prompt for unnamed buffers (#3037)
Release Notes:
- N/A
2023-09-26 19:35:10 +02:00
Piotr Osiewicz
8c47f117db editor: Start transaction in replace impl (#3036)
This fixes the undo with replace in project
/cc @maxbrunsfeld 

Release Notes:

- N/A
2023-09-26 19:21:15 +02:00
Piotr Osiewicz
36f022bb58 project_replace: Fix up key bindings (#3034)
Release Notes:
- N/A
2023-09-26 18:40:41 +02:00
KCaverly
e75f56a0f2 move to system blas 2023-09-26 12:39:22 -04:00
Marshall Bowers
342a00b89e Remove dbg! from styleable_helpers! (#3035)
This PR removes a leftover `dbg!` from `styleable_helpers!`.

We already removed this in the `gpui2-ui` branch, but getting this on
`main` since @KCaverly pointed it out.

Release Notes:

- N/A
2023-09-26 10:49:55 -04:00
KCaverly
330a71d28b fixed bug limiting number of results returned 2023-09-26 10:29:55 -04:00
KCaverly
ea278b5b12 ensure desc sort and cleanup unused imports 2023-09-26 09:53:49 -04:00
Kirill Bulatov
5e7f0c65fe Fix another place where Copilot may panic (#3033) 2023-09-26 11:12:36 +03:00
Kirill Bulatov
b131a2cb98 Fix another place where Copilot may panic 2023-09-26 10:51:13 +03:00
Joseph T. Lyons
b5a39de3e2 Add reset_db script 2023-09-25 21:45:28 -04:00
Conrad Irwin
42df5ef45e vim: Add multicursor shortcuts (#3032)
Adding a few bindings to bring first class feeling multiselect to zed's
vim emulation.

gn and gN are similar to similar vim bindings, ga is similar to gA (and
I doubt we need vim's real ga), g> and g< are just made up.

Release Notes:

- vim: `g n` / `g N` to select next/previous
- vim: `g >` / `g <` to skip current selection and select next/previous
- vim: `g a` to select all
2023-09-25 17:18:12 -05:00
Conrad Irwin
b29e295e1b vim: Add multicursor shortcuts
- g n / g N to select next/previous
- g > / g < to select next/previous replacing current
- g a to select all matches
2023-09-25 15:32:03 -06:00
Mikayla Maki
8c90157990 Fix space and copy/paste when editing a channel (#3030)
This fixes several bugs with how spaces and keyboard commands interact
with channel creating / renaming.

fixes
https://github.com/zed-industries/community/discussions/2076#discussioncomment-7096959

Release Notes:

- N/A
2023-09-25 15:20:00 -05:00
Conrad Irwin
b454f43b6c Add cmd-+ as an alias for cmd-= (#3028)
Release Notes:

- Allow cmd-+ in addition to cmd-= for zoom in
([#1021](https://github.com/zed-industries/community/issues/1021)).

Although I had initially thought this was something more to do with
option key handling, it turns out to be a straightforward and reasonable
feature request.
2023-09-25 14:45:46 -05:00
Conrad Irwin
d17d38fe70 vim: Command (#2951)
Release Notes:

- vim: Add v1 of command mode
([#279](https://github.com/zed-industries/community/issues/279)). The
goal was to cover 90% of what most people actually do, but it is very
incomplete. Known omissions are that ranges cannot be specified (except
that `:%s//` must always specify the % range), commands cannot take
arguments (you can `:w` but not `:w [file]`), and there is no history.
Please file feature requests on
https://github.com/zed-industries/community as you notice things that
could be better.
- `:` triggers zed's command palette. If you type a known vim command it
will run it, otherwise you get zed's normal fuzzy search. For this
release supported commands are limited to:
- - `:w[rite][!]`, `:wq[!]`, `:q[uit][!]`, `:wa[ll][!]`, `:wqa[ll][!]`,
`:qa[ll][!]`, `:[e]x[it][!]`, `:up[date]` to save/close tab(s) and
pane(s).
- - `:cq` to quit completely.
- - `:vs[plit]`, `:sp[lit]` to split vertically/horizontally
- - `:new`, `:vne[w]` to create a new file in a new pane above or to the
left
- - `:tabedit`, `:tabnew` to create a new file in a new tab.
- - `:tabn[ext]`, `:tabp[rev]` to go to previous/next tabs
- - `:tabc[lose]` to close tabs
- - `:cn[ext]`, `:cp[rev]`, `:ln[ext]`, `:lp[rev]` to go to the
next/prev diagnostics.
- - `:cc`, `:ll` to open the errors page
- - `:<number>` to jump to a line number.
- - `:$` to jump to end of file
- - `:%s/foo/bar/` (note that /g is always implied, the range must
always be %, and zed uses different regex syntax to vim)
- - `:/foo` and `:?foo` to jump to next/prev line matching foo
- - `:j[oin]`, to join the current line (no range is yet supported)
- - `:d[elete][l][p]`, to delete the current line (no range is yet
supported)
- - `:s[ort] [i]` to sort the current selection (case-insensitively)
- vim: Add `ctrl-w o` (closes everything except the current item) and
`ctrl-w n` (creates a new file in the pane above).
([#1884](https://github.com/zed-industries/community/issues/1884))
- all: Add a "Discard" option to prompt when saving a file with
conflicts (previously this only appeared on close, not on save).

Internal changes:
- The Picker will now wait for pending queries before confirming (to
handle people typing `: w enter` rapidly.
- workspace::save_item and Pane::save_item are now merged together, and
the behavior controlled by `workspace::SaveIntent`.
- Many actions related to closing/saving items now take an optional
`SaveIntent`.
-
2023-09-25 14:07:22 -05:00
Mikayla
667fc25766 Fix space and copy/paste when editing a channel 2023-09-25 11:31:02 -07:00
Conrad Irwin
359847d047 Revert "Revert "workspace: Improve save prompt. (#3025)""
This reverts commit 5c75450a77.
2023-09-25 12:18:03 -06:00
Mikayla Maki
591ec02cea Add support for the experimental Next LS for Elixir (#3024)
This is a PR I built for a friend of a friend at StrangeLoop, who is
making a much better LSP for elixir that elixir folks want to experiment
with. This PR also improves the our debug log viewer to handle LSP
restarts.

TODO:
- [ ] Make sure NextLS binary loading works.

Release Notes:

- Added support for the experimental Next LS for Elxir, to enable it add
the following field to your settings to enable:

```json
"elixir": {
    "next": "on"
}
```
2023-09-25 12:52:56 -05:00
Mikayla
c2fca054ae Fix compile and test errors 2023-09-25 10:46:09 -07:00
Julia
bf6c2f0dfd Activate correct item when clicking on a code action with the mouse (#3027)
Release Notes:

- Fixed clicking a code action only ever performing the first action in
the list rather than the one clicked on.
2023-09-25 13:45:20 -04:00
KCaverly
86ec0b1d9f implement new search strategy 2023-09-25 13:44:19 -04:00
Conrad Irwin
769c330b3d Merge branch 'vim-command' 2023-09-25 11:41:13 -06:00
Conrad Irwin
5c75450a77 Revert "workspace: Improve save prompt. (#3025)"
This reverts commit 0a491e773b.
2023-09-25 11:41:09 -06:00
Mikayla
ad7c1f3c81 Download next-ls automatically from github 2023-09-25 10:40:20 -07:00
Conrad Irwin
23767f734f Add cmd-+ as an alias for cmd-=
For github.com/zed-industries/community#1021
2023-09-25 11:31:34 -06:00
Julia
80eaabd360 Activate correct item when clicking on a code action with the mouse 2023-09-25 13:31:00 -04:00
Julia
ff5d0f2aeb Trigger scroll_to on code action list when moving selection (#3026)
Release Notes:
- Fixed the code action popup menu not scrolling as selection moves.
2023-09-25 11:21:24 -04:00
Julia
a278428bd5 Trigger scroll_to on code action list when moving selection 2023-09-25 11:13:50 -04:00
Piotr Osiewicz
0a491e773b workspace: Improve save prompt. (#3025)
Add buffer path to the prompt.

Z-2903

Release Notes:
- Added a "Save all/Discard all" prompt when closing a pane with
multiple edited buffers.
2023-09-25 16:15:29 +02:00
Mikayla
8b63e45f0b Implement LSP adapter methods for syntax highlighting 2023-09-24 05:08:05 -07:00
Mikayla
052cb459a6 Improve lsp log viewer's behavior in the presence of LSP restarts
Improve settings interface to local LSP
2023-09-24 04:59:55 -07:00
Marshall Bowers
0697d08e54 Restructure ui into just elements and components (#3023)
This PR restructures the `ui` crate into just `elements` and
`components`.

This was already done on the `gpui2-ui` branch, just getting it onto
`main`.

Release Notes:

- N/A

---------

Co-authored-by: Nate Butler <nate@zed.dev>
2023-09-22 21:27:47 -04:00
Marshall Bowers
895386cfaf Mainline Icon and IconButton changes (#3022)
This PR mainlines the `Icon` and `IconButton` changes from the
`gpui2-ui` branch.

Release Notes:

- N/A

Co-authored-by: Nate Butler <nate@zed.dev>
2023-09-22 19:14:12 -04:00
Marshall Bowers
ad62a966a6 Display available stories in storybook CLI (#3021)
This PR updates the storybook CLI to support displaying all of the
available stories.

The `--help` flag will now show a list of all the available stories:

<img width="1435" alt="Screenshot 2023-09-22 at 6 11 00 PM"
src="https://github.com/zed-industries/zed/assets/1486634/284e1a24-46ec-462e-9709-0f9b6e94931f">

Inputting an invalid story name will also show the list of available
stories:

<img width="1435" alt="Screenshot 2023-09-22 at 6 10 43 PM"
src="https://github.com/zed-industries/zed/assets/1486634/1ce3ae3f-ab03-4976-a06a-5a2b5f61eae3">

Release Notes:

- N/A
2023-09-22 18:16:16 -04:00
Marshall Bowers
fe4248cf34 Scaffold Toolbar and Breadcrumb components (#3020)
This PR scaffolds the `Toolbar` and `Breadcrumb` components.

Right now they both just consist of hardcoded data.

<img width="846" alt="Screenshot 2023-09-22 at 4 54 00 PM"
src="https://github.com/zed-industries/zed/assets/1486634/70578df2-7216-42d2-97ef-d38b83fb4a25">

<img width="799" alt="Screenshot 2023-09-22 at 4 46 04 PM"
src="https://github.com/zed-industries/zed/assets/1486634/73ca3d8a-baf9-4ed4-b4c4-279c674672a3">

Release Notes:

- N/A
2023-09-22 16:57:33 -04:00
Marshall Bowers
27e3e09bb9 Label component states in stories (#3019)
This PR updates the UI component stories to label the various states
that they are in.

Release Notes:

- N/A
2023-09-22 15:48:32 -04:00
Marshall Bowers
d0b15ed940 Report which requested font families are not present on the system (#3006)
This PR improves the error message when `FontCache.load_family` attempts
to load a font that is not present on the system.

I ran into this while trying to run the `storybook` for the first time.
The error message indicated that a font family was not found, but did
not provide any information as to which font family was being loaded.

### Before

```
   Compiling storybook v0.1.0 (/Users/maxdeviant/projects/zed/crates/storybook)
    Finished dev [unoptimized + debuginfo] target(s) in 8.52s
     Running `/Users/maxdeviant/projects/zed/target/debug/storybook`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: could not find a non-empty font family matching one of the given names', crates/theme/src/theme_settings.rs:132:18
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
libc++abi: terminating due to uncaught foreign exception
fish: Job 1, 'cargo run' terminated by signal SIGABRT (Abort)
```

### After

```
   Compiling storybook v0.1.0 (/Users/maxdeviant/projects/zed/crates/storybook)
    Finished dev [unoptimized + debuginfo] target(s) in 7.90s
     Running `/Users/maxdeviant/projects/zed/target/debug/storybook`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: could not find a non-empty font family matching one of the given names: `Zed Mono`', crates/theme/src/theme_settings.rs:132:18
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
libc++abi: terminating due to uncaught foreign exception
fish: Job 1, 'cargo run' terminated by signal SIGABRT (Abort)
```

Release Notes:

- N/A
2023-09-22 15:27:42 -04:00
Marshall Bowers
8b6e982495 Remove manual mapping in FromStr implementation for StorySelector (#3018)
This PR removes the need for writing manual mappings in the `FromStr`
implementation for the `StorySelector` enum used in the storybook CLI.

We are now using the
[`EnumString`](https://docs.rs/strum/0.25.0/strum/derive.EnumString.html)
trait from `strum` to automatically derive snake_cased names for the
enums.

This will cut down on some of the manual work needed to wire up more
stories to the storybook.

Release Notes:

- N/A
2023-09-22 14:06:09 -04:00
Marshall Bowers
71c1e36d1e Put Theme behind an Arc (#3017)
This PR puts the `Theme` returned from the `theme` function behind an
`Arc`.

### Motivation

While working on wiring up window focus events for the `TitleBar`
component we ran into issues where `theme` was holding an immutable
borrow to the `ViewContext` for the entirety of the `render` scope,
which prevented having mutable borrows in the same scope.

### Explanation

To avoid this, we can make `theme` return an `Arc<Theme>` to allow for
cheap clones and avoiding the issues with the borrow checker.

Release Notes:

- N/A

Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com>
2023-09-22 13:35:30 -04:00
Marshall Bowers
d8c6adf338 Factor story boilerplate out into separate components (#3016)
This PR factors out the bulk of the boilerplate required to setup a
story in the storybook out into separate components.

The pattern we're using here is adapted from the "[associated
component](https://maxdeviant.com/posts/2021/react-associated-components/)"
pattern in React.

Release Notes:

- N/A
2023-09-22 11:38:01 -04:00
Kirill Bulatov
afa7045847 Tone down inlay hint update logs 2023-09-22 17:04:11 +03:00
Kyle Caverly
e84339ef4a reorganize AI crates to structure future development (#3015)
Reorganized assistant/semantic_index crates and introduced AI crate to
include shared functionality.

Release Notes:

- Moved most of the Assistant functionality from ai crate to assistant
crate
- Moved interaction with embedding providers from semantic_index to ai
crate
2023-09-22 09:54:46 -04:00
KCaverly
fbd6b5b434 cargo fmt 2023-09-22 09:46:06 -04:00
KCaverly
dc49dec4f0 catchup with main 2023-09-22 09:43:39 -04:00
KCaverly
68c37ca2a4 move embedding provider to ai crate 2023-09-22 09:33:59 -04:00
Kirill Bulatov
1f1c669673 Do not resubscribe for Copilot logs events (#3014)
Last follow-up of https://github.com/zed-industries/zed/pull/3002
Fixes
https://zed-industries.slack.com/archives/C04S6T1T7TQ/p1695281196667609

Copilot sends multiple events about its LSP server readiness, not
necessarily recreating the server from scratch (e.g. due to re-sign in
action). Avoid re-adding same log subscriptions on the same LSP server,
which causes panics.

Release Notes:

- N/A
2023-09-22 13:48:13 +03:00
Kirill Bulatov
d61565d227 Do not resubscribe for Copilot logs events
Copilot sends multiple events about its LSP server readiness, not necessarily recreating the server from scratch (e.g. due to re-sign in action).
Avoid re-adding same log subscriptions on the same LSP server, which
causes panics.
2023-09-22 13:40:20 +03:00
Nate Butler
a5e055f8a5 Bring UI crate up to date (#3013)
Merges various in-progress gpui2 component branches with the new `ui`
crate.
2023-09-21 23:54:11 -04:00
Nate Butler
30b105afd5 Remove leftover state doc 2023-09-21 23:51:03 -04:00
Nate Butler
d14e4d41ea Merge branch 'main' into nate/bring-ui-crate-up-to-date 2023-09-21 23:47:17 -04:00
Nate Butler
f54634aeb2 Bring UI crate up to date 2023-09-21 23:46:06 -04:00
Marshall Bowers
5083ab7694 Add TrafficLights component (#3011)
This PR adds a `TrafficLights` component for GPUI2.

<img width="861" alt="Screenshot 2023-09-21 at 11 32 10 PM"
src="https://github.com/zed-industries/zed/assets/1486634/0fe0e847-49b3-44dc-bd4c-64f12f0051c1">

Release Notes:

- N/A
2023-09-21 23:42:18 -04:00
KCaverly
48e151495f introduce ai crate with completion providers 2023-09-21 22:44:56 -04:00
Marshall Bowers
66358f2900 Update storybook to support stories for individual components (#3010)
This PR updates the `storybook` with support for adding stories for
individual components.

### Motivation

Right now we just have one story in the storybook that renders an entire
`WorkspaceElement`.

While iterating on the various UI components, it will be helpful to be
able to create stories of those components just by themselves.

This is especially true for components that have a number of different
states, as we can render the components in all of the various states in
a single layout.

### Explanation

We achieve this by adding a simple CLI to the storybook.

The `storybook` binary now accepts an optional `[STORY]` parameter that
can be used to indicate which story should be loaded. If this parameter
is not provided, it will load the workspace story as it currently does.

Passing a story name will load the corresponding story, if it exists.

For example:

```
cargo run -- elements/avatar
```

<img width="723" alt="Screenshot 2023-09-21 at 10 29 52 PM"
src="https://github.com/zed-industries/zed/assets/1486634/5df489ed-8607-4024-9c19-c5f4541f97c9">

```
cargo run -- components/facepile
```

<img width="785" alt="Screenshot 2023-09-21 at 10 30 07 PM"
src="https://github.com/zed-industries/zed/assets/1486634/e04a4577-7403-405d-b23c-e765b7a06229">



Release Notes:

- N/A
2023-09-21 22:41:53 -04:00
KCaverly
5f6334696a rename ai crate to assistant crate 2023-09-21 21:54:59 -04:00
Mikayla
02a85b1252 Add local next LSP adapter 2023-09-21 18:09:02 -07:00
Nate Butler
4628639ac6 Update ambiguous theme import (#3009)
Fixes an ambiguous reference to `theme` causing storybook not to build.
2023-09-21 20:32:41 -04:00
Nate Butler
8440ac3a54 Fix fmt complaining about order 2023-09-21 20:25:25 -04:00
Nate Butler
1e6ac8caf2 theme::* -> crate::theme::*; 2023-09-21 20:21:56 -04:00
Max Brunsfeld
7711530704 Simplify titlebar facepile click rendering / mouse handling 2023-09-21 17:12:59 -07:00
Max Brunsfeld
4ffa167256 Allow following into channel notes regardless of project 2023-09-21 17:12:59 -07:00
Marshall Bowers
baa07e935e Extract UI elements from storybook into new ui crate (#3008)
This PR extracts the various UI elements from the `storybook` crate into
a new `ui` library crate.

Release Notes:

- N/A
2023-09-21 19:25:35 -04:00
Marshall Bowers
c252eae32e Reorganize ui module exports (#3007)
This PR reorganizes the exports for the `ui` module in the `storybook`
crate.

### Motivation

Currently we expose each of the various elements/components/modules in
two places:

- Through the module itself (e.g., `ui::element::Avatar`)
- Through the `ui` module's re-exports (e.g., `ui::Avatar`)

This means it's possible to import any given item from two spots, which
can lead to inconsistencies in the consumers. Additionally, it also
means we're shipping the exact module structure underneath `ui` as part
of the public API.

### Explanation

To avoid this, we can avoid exposing each of the individual modules
underneath `ui::{element, component, module}` and instead export just
the module contents themselves.

This makes the `ui` module namespace flat.

Release Notes:

- N/A
2023-09-21 17:46:37 -04:00
Marshall Bowers
92d3115f3d Fix some typos in tools.md 2023-09-21 17:21:40 -04:00
Marshall Bowers
6bbf614a37 Fix some typos in README.md 2023-09-21 16:56:04 -04:00
Max Brunsfeld
ed8b022b51 Add initial failing test for following to channel notes in an unshared project 2023-09-21 13:14:15 -07:00
Max Brunsfeld
f34c6bd1ce Start work on allowing following without a shared project 2023-09-21 13:14:15 -07:00
Max Brunsfeld
c71566e7f5 Make project id optional when following - server only 2023-09-21 13:14:15 -07:00
Max Brunsfeld
83455028b0 Procfile: run zed.dev via 'next dev', not 'vercel dev' 2023-09-21 13:14:15 -07:00
Kyle Caverly
3c2b05be90 add semantic index status, for non authenticated users (#3005)
Update project search semantic ui to accommodate for users who have not
set the OPENAI_API_KEY in their environment variables.

Release Notes:

- Expand Semantic Index status to include status for non authenticated
users
- Update Search UI to illustrate this status.
2023-09-21 14:18:58 -04:00
KCaverly
7b63369df2 move api authentication to embedding provider 2023-09-21 14:00:00 -04:00
KCaverly
997f362cc2 add semantic index status, for non authenticated users 2023-09-21 13:40:01 -04:00
Max Brunsfeld
59e561dcf9 Bump rust from 1.72.0 to 1.72.1 2023-09-21 10:17:55 -07:00
Nate Butler
056353f8a8 Correct icon_margin_scale for fold indicator (#3003)
Fixes a design regression on Preview where the fold icon became small
due to the icon standardization PR.

Release Notes:

- [Preview] Fixed an issue with the size of the fold line icon.
2023-09-21 12:52:54 -04:00
Max Brunsfeld
19a9753663 Fix channel move cancel (#3004)
Release Notes:

- Fixes a bug where channels could no longer be rearranged with drag and
drop.
2023-09-21 09:11:09 -07:00
Mikayla
66dd0e9ec0 Switch drag end event to be fired after mouse up 2023-09-21 08:58:36 -07:00
Nate Butler
d74b8ec4e3 Correct icon_margin_scale 2023-09-21 11:57:35 -04:00
Piotr Osiewicz
dbfa1d7263 [WIP] Replace in project (#2984)
Targeting Preview of 09.27.
This is still pending several touchups/clearups:
- We should watch multibuffer for changes and rescan the excerpts. This
should also update match count.
- Closing editor while multibuffer with 100's of changed files is open
leads to us prompting for save once per each file in the multibuffer.
One could in theory save in multibuffer before closing it (thus avoiding
unnecessary prompts), but it'd be cool to be able to "Save all"/"Discard
All".

Release Notes:

- Added "Replace in project" functionality
2023-09-21 16:27:58 +02:00
Kirill Bulatov
d090fd25e4 Supplementary LSP server log improvements (#3002)
Follow-up of https://github.com/zed-industries/zed/pull/2991 improving
rough edges around supplementary LSP servers:

* Fixes
https://zed-industries.slack.com/archives/C04S6T1T7TQ/p1695281196667609
Copilot init panic
* Makes LSP server list scrollable in the panel
* Shows supplementary servers' RPC logs in the panel

Release Notes:

- N/A
2023-09-21 11:22:56 +03:00
Kirill Bulatov
1c53b0a1c0 Properly re-add Copilot LSP server 2023-09-21 11:02:03 +03:00
Kirill Bulatov
a2ac5ae478 Fix RPC logs not being displayed for supplementary servers 2023-09-21 11:00:05 +03:00
Kirill Bulatov
ead7155b0f Make LSP panel scrollable
co-authored-by: Max <max@zed.dev>
2023-09-21 10:59:19 +03:00
Conrad Irwin
32f8733313 Code review changes 2023-09-20 21:29:45 -06:00
Conrad Irwin
4bf4c780be Revert accidental Cargo change 2023-09-20 20:50:22 -06:00
Conrad Irwin
7a7ff4bb96 Fix save related tests, and refactor saves again 2023-09-20 20:44:42 -06:00
Conrad Irwin
a59da3634b Fix backward search from command 2023-09-20 20:44:42 -06:00
Conrad Irwin
a25fcfdfa7 Iron out some edge-cases 2023-09-20 20:44:42 -06:00
Conrad Irwin
2d9db0fed1 Flesh out v1.0 of vim : 2023-09-20 20:44:41 -06:00
Conrad Irwin
6ad1f19a21 Add NewFileInDirection 2023-09-20 20:44:26 -06:00
Conrad Irwin
88a32ae48d Merge Workspace::save_item into Pane::save_item
These methods were slightly different which caused (for example) there
to be no "Discard" option in the conflict case at the workspace level.

To make this work, a new SaveBehavior (::PromptForNewPath) was added to
support SaveAs.
2023-09-20 20:44:26 -06:00
Conrad Irwin
a4f96e6452 tests: wait deterministically after simulating_keystrokes 2023-09-20 20:44:26 -06:00
Conrad Irwin
e27b7d7812 Ensure the picker waits for pending updates
Particularly in development builds (and in tests), when typing in the
command palette, I tend to hit enter before the suggestions have
settled.
2023-09-20 20:44:26 -06:00
Conrad Irwin
ba5d84f7e8 Fix vim tests on my machine
In a rare case of "it broke on my machine" I haven't been able to run
the vim tests locally for a few days; turns out I ran out of swap file
names...
2023-09-20 20:44:26 -06:00
Conrad Irwin
ea3a1745f5 Add vim-specific interactions to command
This mostly adds the commonly requested set (:wq and friends) and
a few that I use frequently
:<line> to go to a line number
:vsp / :sp to create a split
:cn / :cp to go to diagnostics
2023-09-20 20:44:26 -06:00
Max Brunsfeld
d42093e069 collab 0.22.1 2023-09-20 17:39:21 -07:00
Max Brunsfeld
98482f0150 Fix select all bugs (#3001)
Release Notes:

- Restore `cmd-shift-d` as 'editor::DuplicateLine' and move
`editor::SelectAllMatches` to `cmd-shift-L`, like in VS Code. The
previous action for `cmd-shift-l`, `editor::SplitSelectionIntoLines`,
has been moved to the sublime base keymap.
- Fixes a panic when using 'editor::SelectAllMatches'  on an empty line.
2023-09-20 17:21:10 -07:00
Mikayla
58f4efb579 fix default keybindings for select all matches 2023-09-20 17:14:19 -07:00
Mikayla
fe10875285 Fix panic on select all when query is empty 2023-09-20 17:10:23 -07:00
Mikayla Maki
e0fe97401d Fix bugs from channel moving (#3000)
This PR fixes several bugs related to channel moving and it's
unintuitive behavior when attempting to re-order channels

Release Notes:

- N/A
2023-09-20 17:01:14 -07:00
Mikayla
f2f507e619 Fix bug in channel rendering
Fix drag and drop stale state bug revealed by the channel panel

co-authored-by: Max <max@zed.dev>
2023-09-20 16:40:29 -07:00
Conrad Irwin
f4d4a2f41b vim fixes for find&replace (#2995)
* allow replacing with the empty string to delete
* fix <enter> for ReplaceNext (in vim mode)

Release Notes:

- allow replacement to be empty
2023-09-20 16:42:39 -06:00
Mikayla
4ff44dfa3b Fix bugs in moving channels that could cause channels to be stranded or moved unexpectedly
Made channel linking not query in a loop

co-authored-by: Max <max@zed.dev>
2023-09-20 15:32:06 -07:00
Max Brunsfeld
ee16b2051e Fix opening channel notes from collab panel context menu (#2998)
Release Notes:

- Fixed a bug where the 'Open Notes' action in the collaboration panel
context menu didn't work (preview only).
2023-09-20 13:55:23 -07:00
Max Brunsfeld
3633f091c5 Fix opening channel notes from context menu 2023-09-20 13:45:35 -07:00
Conrad Irwin
841b4d648c Fix vim panic when over-shooting with j (#2997)
Release Notes:

- vim: fix a panic when using `j` to go beyond end of file
2023-09-20 12:17:07 -06:00
Conrad Irwin
01b2db4845 Fix vim test recording 2023-09-20 12:01:04 -06:00
Joseph T. Lyons
e7d73b833b collab 0.22.0 2023-09-20 13:59:36 -04:00
Nate Butler
f7696114bb Add an initial set of GPUI2 components to the storybook (#2990)
This PR adds an initial set of components to `crates/storybook/src/ui`.

All changes still are contained to inside storybook. Merging to keep up
to date with main.
2023-09-20 13:52:47 -04:00
Conrad Irwin
8de67fd9d9 Fix vim panic when over-shooting with j 2023-09-20 11:20:35 -06:00
Nate Butler
be6690bf0b Update tracker.md 2023-09-20 13:08:20 -04:00
Joseph T. Lyons
a86dc942d6 v0.106.x dev 2023-09-20 13:02:13 -04:00
Nate Butler
6dcb0bafb0 WIP Project Tracker 2023-09-20 12:53:08 -04:00
Mikayla
0cceb3fdf1 Get nextLS running 2023-09-20 06:55:24 -07:00
Conrad Irwin
2da664ed17 vim fixes for find&replace
* allow replacing with the empty string to delete
* fix <enter> for ReplaceNext
2023-09-19 20:48:01 -06:00
Nate Butler
2699f170ca Checkpoint - Details 2023-09-19 19:18:23 -04:00
Nate Butler
65aa4d5642 Draw indent guides using indent_level
Co-Authored-By: Julia <30666851+ForLoveOfCats@users.noreply.github.com>
2023-09-19 12:38:46 -04:00
Nate Butler
3a9f5d6ddc use u32 as indent_level
Co-Authored-By: Julia <30666851+ForLoveOfCats@users.noreply.github.com>
2023-09-19 11:59:55 -04:00
Nate Butler
748ad5f05a Make list_item toggleable, improve optional left_icon on list item
Co-Authored-By: Julia <30666851+ForLoveOfCats@users.noreply.github.com>
2023-09-19 11:52:35 -04:00
Nate Butler
7e300079ce WIP 2023-09-19 08:31:22 -04:00
Nate Butler
26f442a675 Merge branch 'main' into nate/gpui2-ui-components 2023-09-19 00:26:41 -04:00
Nate Butler
8aa4fbea83 Add icon, list_item, work on project panel 2023-09-19 00:25:46 -04:00
Nathan Sobo
2701be91e3 Add negative style helpers 2023-09-18 20:47:40 -06:00
Nathan Sobo
f2e87a3429 Add Element::when method 2023-09-18 20:25:12 -06:00
Nathan Sobo
c7a3186d08 Checkpoint 2023-09-18 20:17:27 -06:00
Nathan Sobo
a5e4ceb735 Checkpoint: Add methods for setting arbitrary lengths 2023-09-18 19:48:22 -06:00
Nate Butler
b725cadf48 Checkpoint 2023-09-18 19:59:01 -04:00
Nate Butler
db1dacde5d Add facepile, indicator, follow_group 2023-09-15 22:10:51 -04:00
Nate Butler
9f2a9d43b1 Organize design system under ui 2023-09-15 16:34:56 -04:00
Nate Butler
d6f24feb4a WIP 2023-09-15 14:14:28 -04:00
Nate Butler
40e785fdff Merge branch 'main' into nate/gpui2-ui-components 2023-09-15 13:57:15 -04:00
Nate Butler
70a91c5426 Checkpoint 2023-09-15 11:41:21 -04:00
Nate Butler
fd10b49742 Fix .active() interaction state
Co-Authored-By: Nathan Sobo <1789+nathansobo@users.noreply.github.com>
2023-09-13 13:56:13 -04:00
Nate Butler
a316e25034 Checkpoint 2023-09-13 12:50:01 -04:00
Nate Butler
f54f2c52e9 Checkpoint 2023-09-13 12:40:28 -04:00
Nate Butler
bbc4673f17 Checkpoint 2023-09-12 15:18:13 -04:00
Nate Butler
0d161519e4 Checkpoint 2023-09-12 11:34:27 -04:00
263 changed files with 19382 additions and 5741 deletions

View File

@@ -6,8 +6,8 @@ jobs:
discord_release:
runs-on: ubuntu-latest
steps:
- name: Get appropriate URL
id: get-appropriate-url
- name: Get release URL
id: get-release-url
run: |
if [ "${{ github.event.release.prerelease }}" == "true" ]; then
URL="https://zed.dev/releases/preview/latest"
@@ -15,14 +15,19 @@ jobs:
URL="https://zed.dev/releases/stable/latest"
fi
echo "::set-output name=URL::$URL"
- name: Get content
uses: 2428392/gh-truncate-string-action@v1.2.0
id: get-content
with:
stringToTruncate: |
📣 Zed ${{ github.event.release.tag_name }} was just released!
Restart your Zed or head to ${{ steps.get-release-url.outputs.URL }} to grab it.
${{ github.event.release.body }}
maxLength: 2000
- name: Discord Webhook Action
uses: tsickert/discord-webhook@v5.3.0
with:
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
content: |
📣 Zed ${{ github.event.release.tag_name }} was just released!
Restart your Zed or head to ${{ steps.get-appropriate-url.outputs.URL }} to grab it.
${{ github.event.release.body }}
content: ${{ steps.get-content.outputs.string }}

977
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,6 +2,7 @@
members = [
"crates/activity_indicator",
"crates/ai",
"crates/assistant",
"crates/audio",
"crates/auto_update",
"crates/breadcrumbs",
@@ -63,12 +64,14 @@ members = [
"crates/sqlez",
"crates/sqlez_macros",
"crates/feature_flags",
"crates/rich_text",
"crates/storybook",
"crates/sum_tree",
"crates/terminal",
"crates/text",
"crates/theme",
"crates/theme_selector",
"crates/ui",
"crates/util",
"crates/semantic_index",
"crates/vim",
@@ -103,12 +106,14 @@ rand = { version = "0.8.5" }
refineable = { path = "./crates/refineable" }
regex = { version = "1.5" }
rust-embed = { version = "8.0", features = ["include-exclude"] }
rusqlite = { version = "0.29.0", features = ["blob", "array", "modern_sqlite"] }
schemars = { version = "0.8" }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_derive = { version = "1.0", features = ["deserialize_in_place"] }
serde_json = { version = "1.0", features = ["preserve_order", "raw_value"] }
smallvec = { version = "1.6", features = ["union"] }
smol = { version = "1.2" }
sysinfo = "0.29.10"
tempdir = { version = "0.3.7" }
thiserror = { version = "1.0.29" }
time = { version = "0.3", features = ["serde", "serde-well-known"] }
@@ -117,6 +122,7 @@ tree-sitter = "0.20"
unindent = { version = "0.1.7" }
pretty_assertions = "1.3.0"
git2 = { version = "0.15", default-features = false}
uuid = { version = "1.1.2", features = ["v4"] }
tree-sitter-bash = { git = "https://github.com/tree-sitter/tree-sitter-bash", rev = "1b0321ee85701d5036c334a6f04761cdc672e64c" }
tree-sitter-c = "0.20.1"

View File

@@ -1,4 +1,4 @@
web: cd ../zed.dev && PORT=3000 npx vercel dev
collab: cd crates/collab && cargo run serve
web: cd ../zed.dev && PORT=3000 npm run dev
collab: cd crates/collab && RUST_LOG=${RUST_LOG:-collab=info} cargo run serve
livekit: livekit-server --dev
postgrest: postgrest crates/collab/admin_api.conf

View File

@@ -13,7 +13,7 @@ Welcome to Zed, a lightning-fast, collaborative code editor that makes your drea
sudo xcodebuild -license
```
* Install homebrew, node and rustup-init (rutup, rust, cargo, etc.)
* Install homebrew, node and rustup-init (rustup, rust, cargo, etc.)
```
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install node rustup-init
@@ -36,7 +36,7 @@ Welcome to Zed, a lightning-fast, collaborative code editor that makes your drea
brew install foreman
```
* Ensure the Zed.dev website is checked out in a sibling directory and install it's dependencies:
* Ensure the Zed.dev website is checked out in a sibling directory and install its dependencies:
```
cd ..

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.6 KiB

View File

@@ -30,6 +30,7 @@
"cmd-s": "workspace::Save",
"cmd-shift-s": "workspace::SaveAs",
"cmd-=": "zed::IncreaseBufferFontSize",
"cmd-+": "zed::IncreaseBufferFontSize",
"cmd--": "zed::DecreaseBufferFontSize",
"cmd-0": "zed::ResetBufferFontSize",
"cmd-,": "zed::OpenSettings",
@@ -249,6 +250,7 @@
"bindings": {
"escape": "project_search::ToggleFocus",
"alt-tab": "search::CycleMode",
"cmd-shift-h": "search::ToggleReplace",
"alt-cmd-g": "search::ActivateRegexMode",
"alt-cmd-s": "search::ActivateSemanticMode",
"alt-cmd-x": "search::ActivateTextMode"
@@ -261,11 +263,19 @@
"down": "search::NextHistoryQuery"
}
},
{
"context": "ProjectSearchBar && in_replace",
"bindings": {
"enter": "search::ReplaceNext",
"cmd-enter": "search::ReplaceAll"
}
},
{
"context": "ProjectSearchView",
"bindings": {
"escape": "project_search::ToggleFocus",
"alt-tab": "search::CycleMode",
"cmd-shift-h": "search::ToggleReplace",
"alt-cmd-g": "search::ActivateRegexMode",
"alt-cmd-s": "search::ActivateSemanticMode",
"alt-cmd-x": "search::ActivateTextMode"
@@ -277,6 +287,7 @@
"cmd-f": "project_search::ToggleFocus",
"cmd-g": "search::SelectNextMatch",
"cmd-shift-g": "search::SelectPrevMatch",
"cmd-shift-h": "search::ToggleReplace",
"alt-enter": "search::SelectAllMatches",
"alt-cmd-c": "search::ToggleCaseSensitive",
"alt-cmd-w": "search::ToggleWholeWord",
@@ -498,6 +509,22 @@
"cmd-k cmd-down": [
"workspace::ActivatePaneInDirection",
"Down"
],
"cmd-k shift-left": [
"workspace::SwapPaneInDirection",
"Left"
],
"cmd-k shift-right": [
"workspace::SwapPaneInDirection",
"Right"
],
"cmd-k shift-up": [
"workspace::SwapPaneInDirection",
"Up"
],
"cmd-k shift-down": [
"workspace::SwapPaneInDirection",
"Down"
]
}
},
@@ -562,7 +589,7 @@
}
},
{
"context": "ProjectSearchBar",
"context": "ProjectSearchBar && !in_replace",
"bindings": {
"cmd-enter": "project_search::SearchInNew"
}
@@ -588,14 +615,20 @@
}
},
{
"context": "CollabPanel",
"context": "CollabPanel && not_editing",
"bindings": {
"ctrl-backspace": "collab_panel::Remove",
"space": "menu::Confirm"
}
},
{
"context": "CollabPanel > Editor",
"context": "(CollabPanel && editing) > Editor",
"bindings": {
"space": "collab_panel::InsertSpace"
}
},
{
"context": "(CollabPanel && not_editing) > Editor",
"bindings": {
"cmd-c": "collab_panel::StartLinkChannel",
"cmd-x": "collab_panel::StartMoveChannel",

View File

@@ -18,6 +18,7 @@
}
}
],
":": "command_palette::Toggle",
"h": "vim::Left",
"left": "vim::Left",
"backspace": "vim::Backspace",
@@ -94,6 +95,7 @@
}
],
"ctrl-o": "pane::GoBack",
"ctrl-i": "pane::GoForward",
"ctrl-]": "editor::GoToDefinition",
"escape": [
"vim::SwitchMode",
@@ -125,10 +127,26 @@
"g shift-t": "pane::ActivatePrevItem",
"g d": "editor::GoToDefinition",
"g shift-d": "editor::GoToTypeDefinition",
"g n": "vim::SelectNext",
"g shift-n": "vim::SelectPrevious",
"g >": [
"editor::SelectNext",
{
"replace_newest": true
}
],
"g <": [
"editor::SelectPrevious",
{
"replace_newest": true
}
],
"g a": "editor::SelectAllMatches",
"g s": "outline::Toggle",
"g shift-s": "project_symbols::Toggle",
"g .": "editor::ToggleCodeActions", // zed specific
"g shift-a": "editor::FindAllReferences", // zed specific
"g space": "editor::OpenExcerpts", // zed specific
"g *": [
"vim::MoveToNext",
{
@@ -205,13 +223,13 @@
"shift-z shift-q": [
"pane::CloseActiveItem",
{
"saveBehavior": "dontSave"
"saveIntent": "skip"
}
],
"shift-z shift-z": [
"pane::CloseActiveItem",
{
"saveBehavior": "promptOnConflict"
"saveIntent": "saveAll"
}
],
// Count support
@@ -300,6 +318,38 @@
"workspace::ActivatePaneInDirection",
"Down"
],
"ctrl-w shift-left": [
"workspace::SwapPaneInDirection",
"Left"
],
"ctrl-w shift-right": [
"workspace::SwapPaneInDirection",
"Right"
],
"ctrl-w shift-up": [
"workspace::SwapPaneInDirection",
"Up"
],
"ctrl-w shift-down": [
"workspace::SwapPaneInDirection",
"Down"
],
"ctrl-w shift-h": [
"workspace::SwapPaneInDirection",
"Left"
],
"ctrl-w shift-l": [
"workspace::SwapPaneInDirection",
"Right"
],
"ctrl-w shift-k": [
"workspace::SwapPaneInDirection",
"Up"
],
"ctrl-w shift-j": [
"workspace::SwapPaneInDirection",
"Down"
],
"ctrl-w g t": "pane::ActivateNextItem",
"ctrl-w ctrl-g t": "pane::ActivateNextItem",
"ctrl-w g shift-t": "pane::ActivatePrevItem",
@@ -318,7 +368,17 @@
"ctrl-w c": "pane::CloseAllItems",
"ctrl-w ctrl-c": "pane::CloseAllItems",
"ctrl-w q": "pane::CloseAllItems",
"ctrl-w ctrl-q": "pane::CloseAllItems"
"ctrl-w ctrl-q": "pane::CloseAllItems",
"ctrl-w o": "workspace::CloseInactiveTabsAndPanes",
"ctrl-w ctrl-o": "workspace::CloseInactiveTabsAndPanes",
"ctrl-w n": [
"workspace::NewFileInDirection",
"Up"
],
"ctrl-w ctrl-n": [
"workspace::NewFileInDirection",
"Up"
]
}
},
{
@@ -357,6 +417,8 @@
"o": "vim::InsertLineBelow",
"shift-o": "vim::InsertLineAbove",
"~": "vim::ChangeCase",
"ctrl-a": "vim::Increment",
"ctrl-x": "vim::Decrement",
"p": "vim::Paste",
"shift-p": [
"vim::Paste",
@@ -468,6 +530,20 @@
"shift-r": "vim::SubstituteLine",
"c": "vim::Substitute",
"~": "vim::ChangeCase",
"ctrl-a": "vim::Increment",
"ctrl-x": "vim::Decrement",
"g ctrl-a": [
"vim::Increment",
{
"step": true
}
],
"g ctrl-x": [
"vim::Decrement",
{
"step": true
}
],
"shift-i": "vim::InsertBefore",
"shift-a": "vim::InsertAfter",
"shift-j": "vim::JoinLines",
@@ -508,11 +584,16 @@
}
},
{
"context": "Editor && vim_mode == insert && !menu",
"context": "Editor && vim_mode == insert",
"bindings": {
"escape": "vim::NormalBefore",
"ctrl-c": "vim::NormalBefore",
"ctrl-[": "vim::NormalBefore"
"ctrl-[": "vim::NormalBefore",
"ctrl-x ctrl-o": "editor::ShowCompletions",
"ctrl-x ctrl-a": "assistant::InlineAssist", // zed specific
"ctrl-x ctrl-c": "copilot::Suggest", // zed specific
"ctrl-x ctrl-l": "editor::ToggleCodeActions", // zed specific
"ctrl-x ctrl-z": "editor::Cancel"
}
},
{
@@ -531,7 +612,7 @@
}
},
{
"context": "BufferSearchBar > VimEnabled",
"context": "BufferSearchBar && !in_replace > VimEnabled",
"bindings": {
"enter": "vim::SearchSubmit",
"escape": "buffer_search::Dismiss"

View File

@@ -227,6 +227,11 @@
},
// Automatically update Zed
"auto_update": true,
// Diagnostics configuration.
"diagnostics": {
// Whether to show warnings or not by default.
"include_warnings": true
},
// Git gutter behavior configuration.
"git": {
// Control whether the git gutter is shown. May take 2 values:
@@ -356,7 +361,7 @@
".venv",
"venv"
],
// Can also be 'csh' and 'fish'
// Can also be 'csh', 'fish', and `nushell`
"activate_script": "default"
}
}
@@ -370,7 +375,28 @@
},
// Difference settings for semantic_index
"semantic_index": {
"enabled": false
"enabled": true
},
// Settings specific to our elixir integration
"elixir": {
// Change the LSP zed uses for elixir.
// Note that changing this setting requires a restart of Zed
// to take effect.
//
// May take 3 values:
// 1. Use the standard ElixirLS, this is the default
// "lsp": "elixir_ls"
// 2. Use the experimental NextLs
// "lsp": "next_ls",
// 3. Use a language server installed locally on your machine:
// "lsp": {
// "local": {
// "path": "~/next-ls/bin/start",
// "arguments": ["--stdio"]
// }
// },
//
"lsp": "elixir_ls"
},
// Different settings for specific languages.
"languages": {

View File

@@ -9,39 +9,26 @@ path = "src/ai.rs"
doctest = false
[dependencies]
client = { path = "../client" }
collections = { path = "../collections"}
editor = { path = "../editor" }
fs = { path = "../fs" }
gpui = { path = "../gpui" }
language = { path = "../language" }
menu = { path = "../menu" }
search = { path = "../search" }
settings = { path = "../settings" }
theme = { path = "../theme" }
util = { path = "../util" }
uuid = { version = "1.1.2", features = ["v4"] }
workspace = { path = "../workspace" }
async-trait.workspace = true
anyhow.workspace = true
chrono = { version = "0.4", features = ["serde"] }
futures.workspace = true
indoc.workspace = true
isahc.workspace = true
lazy_static.workspace = true
ordered-float.workspace = true
parking_lot.workspace = true
isahc.workspace = true
regex.workspace = true
schemars.workspace = true
serde.workspace = true
serde_json.workspace = true
smol.workspace = true
tiktoken-rs = "0.4"
postage.workspace = true
rand.workspace = true
log.workspace = true
parse_duration = "2.1.1"
tiktoken-rs = "0.5.0"
matrixmultiply = "0.3.7"
rusqlite = { version = "0.29.0", features = ["blob", "array", "modern_sqlite"] }
bincode = "1.3.3"
[dev-dependencies]
editor = { path = "../editor", features = ["test-support"] }
project = { path = "../project", features = ["test-support"] }
ctor.workspace = true
env_logger.workspace = true
log.workspace = true
rand.workspace = true
gpui = { path = "../gpui", features = ["test-support"] }

View File

@@ -1,294 +1,2 @@
pub mod assistant;
mod assistant_settings;
mod codegen;
mod streaming_diff;
use anyhow::{anyhow, Result};
pub use assistant::AssistantPanel;
use assistant_settings::OpenAIModel;
use chrono::{DateTime, Local};
use collections::HashMap;
use fs::Fs;
use futures::{io::BufReader, AsyncBufReadExt, AsyncReadExt, Stream, StreamExt};
use gpui::{executor::Background, AppContext};
use isahc::{http::StatusCode, Request, RequestExt};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::{
cmp::Reverse,
ffi::OsStr,
fmt::{self, Display},
io,
path::PathBuf,
sync::Arc,
};
use util::paths::CONVERSATIONS_DIR;
const OPENAI_API_URL: &'static str = "https://api.openai.com/v1";
// Data types for chat completion requests
#[derive(Debug, Default, Serialize)]
pub struct OpenAIRequest {
model: String,
messages: Vec<RequestMessage>,
stream: bool,
}
#[derive(
Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
struct MessageId(usize);
#[derive(Clone, Debug, Serialize, Deserialize)]
struct MessageMetadata {
role: Role,
sent_at: DateTime<Local>,
status: MessageStatus,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
enum MessageStatus {
Pending,
Done,
Error(Arc<str>),
}
#[derive(Serialize, Deserialize)]
struct SavedMessage {
id: MessageId,
start: usize,
}
#[derive(Serialize, Deserialize)]
struct SavedConversation {
id: Option<String>,
zed: String,
version: String,
text: String,
messages: Vec<SavedMessage>,
message_metadata: HashMap<MessageId, MessageMetadata>,
summary: String,
model: OpenAIModel,
}
impl SavedConversation {
const VERSION: &'static str = "0.1.0";
}
struct SavedConversationMetadata {
title: String,
path: PathBuf,
mtime: chrono::DateTime<chrono::Local>,
}
impl SavedConversationMetadata {
pub async fn list(fs: Arc<dyn Fs>) -> Result<Vec<Self>> {
fs.create_dir(&CONVERSATIONS_DIR).await?;
let mut paths = fs.read_dir(&CONVERSATIONS_DIR).await?;
let mut conversations = Vec::<SavedConversationMetadata>::new();
while let Some(path) = paths.next().await {
let path = path?;
if path.extension() != Some(OsStr::new("json")) {
continue;
}
let pattern = r" - \d+.zed.json$";
let re = Regex::new(pattern).unwrap();
let metadata = fs.metadata(&path).await?;
if let Some((file_name, metadata)) = path
.file_name()
.and_then(|name| name.to_str())
.zip(metadata)
{
let title = re.replace(file_name, "");
conversations.push(Self {
title: title.into_owned(),
path,
mtime: metadata.mtime.into(),
});
}
}
conversations.sort_unstable_by_key(|conversation| Reverse(conversation.mtime));
Ok(conversations)
}
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct RequestMessage {
role: Role,
content: String,
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct ResponseMessage {
role: Option<Role>,
content: Option<String>,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
enum Role {
User,
Assistant,
System,
}
impl Role {
pub fn cycle(&mut self) {
*self = match self {
Role::User => Role::Assistant,
Role::Assistant => Role::System,
Role::System => Role::User,
}
}
}
impl Display for Role {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Role::User => write!(f, "User"),
Role::Assistant => write!(f, "Assistant"),
Role::System => write!(f, "System"),
}
}
}
#[derive(Deserialize, Debug)]
pub struct OpenAIResponseStreamEvent {
pub id: Option<String>,
pub object: String,
pub created: u32,
pub model: String,
pub choices: Vec<ChatChoiceDelta>,
pub usage: Option<Usage>,
}
#[derive(Deserialize, Debug)]
pub struct Usage {
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub total_tokens: u32,
}
#[derive(Deserialize, Debug)]
pub struct ChatChoiceDelta {
pub index: u32,
pub delta: ResponseMessage,
pub finish_reason: Option<String>,
}
#[derive(Deserialize, Debug)]
struct OpenAIUsage {
prompt_tokens: u64,
completion_tokens: u64,
total_tokens: u64,
}
#[derive(Deserialize, Debug)]
struct OpenAIChoice {
text: String,
index: u32,
logprobs: Option<serde_json::Value>,
finish_reason: Option<String>,
}
pub fn init(cx: &mut AppContext) {
assistant::init(cx);
}
pub async fn stream_completion(
api_key: String,
executor: Arc<Background>,
mut request: OpenAIRequest,
) -> Result<impl Stream<Item = Result<OpenAIResponseStreamEvent>>> {
request.stream = true;
let (tx, rx) = futures::channel::mpsc::unbounded::<Result<OpenAIResponseStreamEvent>>();
let json_data = serde_json::to_string(&request)?;
let mut response = Request::post(format!("{OPENAI_API_URL}/chat/completions"))
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", api_key))
.body(json_data)?
.send_async()
.await?;
let status = response.status();
if status == StatusCode::OK {
executor
.spawn(async move {
let mut lines = BufReader::new(response.body_mut()).lines();
fn parse_line(
line: Result<String, io::Error>,
) -> Result<Option<OpenAIResponseStreamEvent>> {
if let Some(data) = line?.strip_prefix("data: ") {
let event = serde_json::from_str(&data)?;
Ok(Some(event))
} else {
Ok(None)
}
}
while let Some(line) = lines.next().await {
if let Some(event) = parse_line(line).transpose() {
let done = event.as_ref().map_or(false, |event| {
event
.choices
.last()
.map_or(false, |choice| choice.finish_reason.is_some())
});
if tx.unbounded_send(event).is_err() {
break;
}
if done {
break;
}
}
}
anyhow::Ok(())
})
.detach();
Ok(rx)
} else {
let mut body = String::new();
response.body_mut().read_to_string(&mut body).await?;
#[derive(Deserialize)]
struct OpenAIResponse {
error: OpenAIError,
}
#[derive(Deserialize)]
struct OpenAIError {
message: String,
}
match serde_json::from_str::<OpenAIResponse>(&body) {
Ok(response) if !response.error.message.is_empty() => Err(anyhow!(
"Failed to connect to OpenAI API: {}",
response.error.message,
)),
_ => Err(anyhow!(
"Failed to connect to OpenAI API: {} {}",
response.status(),
body,
)),
}
}
}
#[cfg(test)]
#[ctor::ctor]
fn init_logger() {
if std::env::var("RUST_LOG").is_ok() {
env_logger::init();
}
}
pub mod completion;
pub mod embedding;

212
crates/ai/src/completion.rs Normal file
View File

@@ -0,0 +1,212 @@
use anyhow::{anyhow, Result};
use futures::{
future::BoxFuture, io::BufReader, stream::BoxStream, AsyncBufReadExt, AsyncReadExt, FutureExt,
Stream, StreamExt,
};
use gpui::executor::Background;
use isahc::{http::StatusCode, Request, RequestExt};
use serde::{Deserialize, Serialize};
use std::{
fmt::{self, Display},
io,
sync::Arc,
};
pub const OPENAI_API_URL: &'static str = "https://api.openai.com/v1";
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Role {
User,
Assistant,
System,
}
impl Role {
pub fn cycle(&mut self) {
*self = match self {
Role::User => Role::Assistant,
Role::Assistant => Role::System,
Role::System => Role::User,
}
}
}
impl Display for Role {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Role::User => write!(f, "User"),
Role::Assistant => write!(f, "Assistant"),
Role::System => write!(f, "System"),
}
}
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct RequestMessage {
pub role: Role,
pub content: String,
}
#[derive(Debug, Default, Serialize)]
pub struct OpenAIRequest {
pub model: String,
pub messages: Vec<RequestMessage>,
pub stream: bool,
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct ResponseMessage {
pub role: Option<Role>,
pub content: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct OpenAIUsage {
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub total_tokens: u32,
}
#[derive(Deserialize, Debug)]
pub struct ChatChoiceDelta {
pub index: u32,
pub delta: ResponseMessage,
pub finish_reason: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct OpenAIResponseStreamEvent {
pub id: Option<String>,
pub object: String,
pub created: u32,
pub model: String,
pub choices: Vec<ChatChoiceDelta>,
pub usage: Option<OpenAIUsage>,
}
pub async fn stream_completion(
api_key: String,
executor: Arc<Background>,
mut request: OpenAIRequest,
) -> Result<impl Stream<Item = Result<OpenAIResponseStreamEvent>>> {
request.stream = true;
let (tx, rx) = futures::channel::mpsc::unbounded::<Result<OpenAIResponseStreamEvent>>();
let json_data = serde_json::to_string(&request)?;
let mut response = Request::post(format!("{OPENAI_API_URL}/chat/completions"))
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", api_key))
.body(json_data)?
.send_async()
.await?;
let status = response.status();
if status == StatusCode::OK {
executor
.spawn(async move {
let mut lines = BufReader::new(response.body_mut()).lines();
fn parse_line(
line: Result<String, io::Error>,
) -> Result<Option<OpenAIResponseStreamEvent>> {
if let Some(data) = line?.strip_prefix("data: ") {
let event = serde_json::from_str(&data)?;
Ok(Some(event))
} else {
Ok(None)
}
}
while let Some(line) = lines.next().await {
if let Some(event) = parse_line(line).transpose() {
let done = event.as_ref().map_or(false, |event| {
event
.choices
.last()
.map_or(false, |choice| choice.finish_reason.is_some())
});
if tx.unbounded_send(event).is_err() {
break;
}
if done {
break;
}
}
}
anyhow::Ok(())
})
.detach();
Ok(rx)
} else {
let mut body = String::new();
response.body_mut().read_to_string(&mut body).await?;
#[derive(Deserialize)]
struct OpenAIResponse {
error: OpenAIError,
}
#[derive(Deserialize)]
struct OpenAIError {
message: String,
}
match serde_json::from_str::<OpenAIResponse>(&body) {
Ok(response) if !response.error.message.is_empty() => Err(anyhow!(
"Failed to connect to OpenAI API: {}",
response.error.message,
)),
_ => Err(anyhow!(
"Failed to connect to OpenAI API: {} {}",
response.status(),
body,
)),
}
}
}
pub trait CompletionProvider {
fn complete(
&self,
prompt: OpenAIRequest,
) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>>;
}
pub struct OpenAICompletionProvider {
api_key: String,
executor: Arc<Background>,
}
impl OpenAICompletionProvider {
pub fn new(api_key: String, executor: Arc<Background>) -> Self {
Self { api_key, executor }
}
}
impl CompletionProvider for OpenAICompletionProvider {
fn complete(
&self,
prompt: OpenAIRequest,
) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
let request = stream_completion(self.api_key.clone(), self.executor.clone(), prompt);
async move {
let response = request.await?;
let stream = response
.filter_map(|response| async move {
match response {
Ok(mut response) => Some(Ok(response.choices.pop()?.delta.content?)),
Err(error) => Some(Err(error)),
}
})
.boxed();
Ok(stream)
}
.boxed()
}
}

View File

@@ -27,8 +27,30 @@ lazy_static! {
}
#[derive(Debug, PartialEq, Clone)]
pub struct Embedding(Vec<f32>);
pub struct Embedding(pub Vec<f32>);
// This is needed for semantic index functionality
// Unfortunately it has to live wherever the "Embedding" struct is created.
// Keeping this in here though, introduces a 'rusqlite' dependency into AI
// which is less than ideal
impl FromSql for Embedding {
fn column_result(value: ValueRef) -> FromSqlResult<Self> {
let bytes = value.as_blob()?;
let embedding: Result<Vec<f32>, Box<bincode::ErrorKind>> = bincode::deserialize(bytes);
if embedding.is_err() {
return Err(rusqlite::types::FromSqlError::Other(embedding.unwrap_err()));
}
Ok(Embedding(embedding.unwrap()))
}
}
impl ToSql for Embedding {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
let bytes = bincode::serialize(&self.0)
.map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?;
Ok(ToSqlOutput::Owned(rusqlite::types::Value::Blob(bytes)))
}
}
impl From<Vec<f32>> for Embedding {
fn from(value: Vec<f32>) -> Self {
Embedding(value)
@@ -63,24 +85,24 @@ impl Embedding {
}
}
impl FromSql for Embedding {
fn column_result(value: ValueRef) -> FromSqlResult<Self> {
let bytes = value.as_blob()?;
let embedding: Result<Vec<f32>, Box<bincode::ErrorKind>> = bincode::deserialize(bytes);
if embedding.is_err() {
return Err(rusqlite::types::FromSqlError::Other(embedding.unwrap_err()));
}
Ok(Embedding(embedding.unwrap()))
}
}
// impl FromSql for Embedding {
// fn column_result(value: ValueRef) -> FromSqlResult<Self> {
// let bytes = value.as_blob()?;
// let embedding: Result<Vec<f32>, Box<bincode::ErrorKind>> = bincode::deserialize(bytes);
// if embedding.is_err() {
// return Err(rusqlite::types::FromSqlError::Other(embedding.unwrap_err()));
// }
// Ok(Embedding(embedding.unwrap()))
// }
// }
impl ToSql for Embedding {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
let bytes = bincode::serialize(&self.0)
.map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?;
Ok(ToSqlOutput::Owned(rusqlite::types::Value::Blob(bytes)))
}
}
// impl ToSql for Embedding {
// fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
// let bytes = bincode::serialize(&self.0)
// .map_err(|err| rusqlite::Error::ToSqlConversionFailure(Box::new(err)))?;
// Ok(ToSqlOutput::Owned(rusqlite::types::Value::Blob(bytes)))
// }
// }
#[derive(Clone)]
pub struct OpenAIEmbeddings {

View File

@@ -0,0 +1,48 @@
[package]
name = "assistant"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
path = "src/assistant.rs"
doctest = false
[dependencies]
ai = { path = "../ai" }
client = { path = "../client" }
collections = { path = "../collections"}
editor = { path = "../editor" }
fs = { path = "../fs" }
gpui = { path = "../gpui" }
language = { path = "../language" }
menu = { path = "../menu" }
search = { path = "../search" }
settings = { path = "../settings" }
theme = { path = "../theme" }
util = { path = "../util" }
workspace = { path = "../workspace" }
uuid.workspace = true
anyhow.workspace = true
chrono = { version = "0.4", features = ["serde"] }
futures.workspace = true
indoc.workspace = true
isahc.workspace = true
ordered-float.workspace = true
parking_lot.workspace = true
regex.workspace = true
schemars.workspace = true
serde.workspace = true
serde_json.workspace = true
smol.workspace = true
tiktoken-rs = "0.4"
[dev-dependencies]
editor = { path = "../editor", features = ["test-support"] }
project = { path = "../project", features = ["test-support"] }
ctor.workspace = true
env_logger.workspace = true
log.workspace = true
rand.workspace = true

View File

@@ -0,0 +1,113 @@
pub mod assistant_panel;
mod assistant_settings;
mod codegen;
mod prompts;
mod streaming_diff;
use ai::completion::Role;
use anyhow::Result;
pub use assistant_panel::AssistantPanel;
use assistant_settings::OpenAIModel;
use chrono::{DateTime, Local};
use collections::HashMap;
use fs::Fs;
use futures::StreamExt;
use gpui::AppContext;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::{cmp::Reverse, ffi::OsStr, path::PathBuf, sync::Arc};
use util::paths::CONVERSATIONS_DIR;
#[derive(
Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
struct MessageId(usize);
#[derive(Clone, Debug, Serialize, Deserialize)]
struct MessageMetadata {
role: Role,
sent_at: DateTime<Local>,
status: MessageStatus,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
enum MessageStatus {
Pending,
Done,
Error(Arc<str>),
}
#[derive(Serialize, Deserialize)]
struct SavedMessage {
id: MessageId,
start: usize,
}
#[derive(Serialize, Deserialize)]
struct SavedConversation {
id: Option<String>,
zed: String,
version: String,
text: String,
messages: Vec<SavedMessage>,
message_metadata: HashMap<MessageId, MessageMetadata>,
summary: String,
model: OpenAIModel,
}
impl SavedConversation {
const VERSION: &'static str = "0.1.0";
}
struct SavedConversationMetadata {
title: String,
path: PathBuf,
mtime: chrono::DateTime<chrono::Local>,
}
impl SavedConversationMetadata {
pub async fn list(fs: Arc<dyn Fs>) -> Result<Vec<Self>> {
fs.create_dir(&CONVERSATIONS_DIR).await?;
let mut paths = fs.read_dir(&CONVERSATIONS_DIR).await?;
let mut conversations = Vec::<SavedConversationMetadata>::new();
while let Some(path) = paths.next().await {
let path = path?;
if path.extension() != Some(OsStr::new("json")) {
continue;
}
let pattern = r" - \d+.zed.json$";
let re = Regex::new(pattern).unwrap();
let metadata = fs.metadata(&path).await?;
if let Some((file_name, metadata)) = path
.file_name()
.and_then(|name| name.to_str())
.zip(metadata)
{
let title = re.replace(file_name, "");
conversations.push(Self {
title: title.into_owned(),
path,
mtime: metadata.mtime.into(),
});
}
}
conversations.sort_unstable_by_key(|conversation| Reverse(conversation.mtime));
Ok(conversations)
}
}
pub fn init(cx: &mut AppContext) {
assistant_panel::init(cx);
}
#[cfg(test)]
#[ctor::ctor]
fn init_logger() {
if std::env::var("RUST_LOG").is_ok() {
env_logger::init();
}
}

View File

@@ -1,8 +1,12 @@
use crate::{
assistant_settings::{AssistantDockPosition, AssistantSettings, OpenAIModel},
codegen::{self, Codegen, CodegenKind, OpenAICompletionProvider},
stream_completion, MessageId, MessageMetadata, MessageStatus, OpenAIRequest, RequestMessage,
Role, SavedConversation, SavedConversationMetadata, SavedMessage, OPENAI_API_URL,
codegen::{self, Codegen, CodegenKind},
prompts::generate_content_prompt,
MessageId, MessageMetadata, MessageStatus, Role, SavedConversation, SavedConversationMetadata,
SavedMessage,
};
use ai::completion::{
stream_completion, OpenAICompletionProvider, OpenAIRequest, RequestMessage, OPENAI_API_URL,
};
use anyhow::{anyhow, Result};
use chrono::{DateTime, Local};
@@ -13,7 +17,7 @@ use editor::{
BlockContext, BlockDisposition, BlockId, BlockProperties, BlockStyle, ToDisplayPoint,
},
scroll::autoscroll::{Autoscroll, AutoscrollStrategy},
Anchor, Editor, MoveDown, MoveUp, MultiBufferSnapshot, ToOffset,
Anchor, Editor, MoveDown, MoveUp, MultiBufferSnapshot, ToOffset, ToPoint,
};
use fs::Fs;
use futures::StreamExt;
@@ -270,22 +274,40 @@ impl AssistantPanel {
return;
};
let inline_assist_id = post_inc(&mut self.next_inline_assist_id);
let selection = editor.read(cx).selections.newest_anchor().clone();
if selection.start.excerpt_id() != selection.end.excerpt_id() {
return;
}
let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
// Extend the selection to the start and the end of the line.
let mut point_selection = selection.map(|selection| selection.to_point(&snapshot));
if point_selection.end > point_selection.start {
point_selection.start.column = 0;
// If the selection ends at the start of the line, we don't want to include it.
if point_selection.end.column == 0 {
point_selection.end.row -= 1;
}
point_selection.end.column = snapshot.line_len(point_selection.end.row);
}
let codegen_kind = if point_selection.start == point_selection.end {
CodegenKind::Generate {
position: snapshot.anchor_after(point_selection.start),
}
} else {
CodegenKind::Transform {
range: snapshot.anchor_before(point_selection.start)
..snapshot.anchor_after(point_selection.end),
}
};
let inline_assist_id = post_inc(&mut self.next_inline_assist_id);
let provider = Arc::new(OpenAICompletionProvider::new(
api_key,
cx.background().clone(),
));
let selection = editor.read(cx).selections.newest_anchor().clone();
let codegen_kind = if editor.read(cx).selections.newest::<usize>(cx).is_empty() {
CodegenKind::Generate {
position: selection.start,
}
} else {
CodegenKind::Transform {
range: selection.start..selection.end,
}
};
let codegen = cx.add_model(|cx| {
Codegen::new(editor.read(cx).buffer().clone(), codegen_kind, provider, cx)
});
@@ -311,7 +333,7 @@ impl AssistantPanel {
editor.insert_blocks(
[BlockProperties {
style: BlockStyle::Flex,
position: selection.head().bias_left(&snapshot),
position: snapshot.anchor_before(point_selection.head()),
height: 2,
render: Arc::new({
let inline_assistant = inline_assistant.clone();
@@ -538,11 +560,26 @@ impl AssistantPanel {
self.inline_prompt_history.pop_front();
}
let codegen = pending_assist.codegen.clone();
let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
let range = pending_assist.codegen.read(cx).range();
let selected_text = snapshot.text_for_range(range.clone()).collect::<String>();
let range = codegen.read(cx).range();
let start = snapshot.point_to_buffer_offset(range.start);
let end = snapshot.point_to_buffer_offset(range.end);
let (buffer, range) = if let Some((start, end)) = start.zip(end) {
let (start_buffer, start_buffer_offset) = start;
let (end_buffer, end_buffer_offset) = end;
if start_buffer.remote_id() == end_buffer.remote_id() {
(start_buffer.clone(), start_buffer_offset..end_buffer_offset)
} else {
self.finish_inline_assist(inline_assist_id, false, cx);
return;
}
} else {
self.finish_inline_assist(inline_assist_id, false, cx);
return;
};
let language = snapshot.language_at(range.start);
let language = buffer.language_at(range.start);
let language_name = if let Some(language) = language.as_ref() {
if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
None
@@ -552,95 +589,9 @@ impl AssistantPanel {
} else {
None
};
let language_name = language_name.as_deref();
let mut prompt = String::new();
if let Some(language_name) = language_name {
writeln!(prompt, "You're an expert {language_name} engineer.").unwrap();
}
match pending_assist.codegen.read(cx).kind() {
CodegenKind::Transform { .. } => {
writeln!(
prompt,
"You're currently working inside an editor on this file:"
)
.unwrap();
if let Some(language_name) = language_name {
writeln!(prompt, "```{language_name}").unwrap();
} else {
writeln!(prompt, "```").unwrap();
}
for chunk in snapshot.text_for_range(Anchor::min()..Anchor::max()) {
write!(prompt, "{chunk}").unwrap();
}
writeln!(prompt, "```").unwrap();
writeln!(
prompt,
"In particular, the user has selected the following text:"
)
.unwrap();
if let Some(language_name) = language_name {
writeln!(prompt, "```{language_name}").unwrap();
} else {
writeln!(prompt, "```").unwrap();
}
writeln!(prompt, "{selected_text}").unwrap();
writeln!(prompt, "```").unwrap();
writeln!(prompt).unwrap();
writeln!(
prompt,
"Modify the selected text given the user prompt: {user_prompt}"
)
.unwrap();
writeln!(
prompt,
"You MUST reply only with the edited selected text, not the entire file."
)
.unwrap();
}
CodegenKind::Generate { .. } => {
writeln!(
prompt,
"You're currently working inside an editor on this file:"
)
.unwrap();
if let Some(language_name) = language_name {
writeln!(prompt, "```{language_name}").unwrap();
} else {
writeln!(prompt, "```").unwrap();
}
for chunk in snapshot.text_for_range(Anchor::min()..range.start) {
write!(prompt, "{chunk}").unwrap();
}
write!(prompt, "<|>").unwrap();
for chunk in snapshot.text_for_range(range.start..Anchor::max()) {
write!(prompt, "{chunk}").unwrap();
}
writeln!(prompt).unwrap();
writeln!(prompt, "```").unwrap();
writeln!(
prompt,
"Assume the cursor is located where the `<|>` marker is."
)
.unwrap();
writeln!(
prompt,
"Text can't be replaced, so assume your answer will be inserted at the cursor."
)
.unwrap();
writeln!(
prompt,
"Complete the text given the user prompt: {user_prompt}"
)
.unwrap();
}
}
if let Some(language_name) = language_name {
writeln!(prompt, "Your answer MUST always be valid {language_name}.").unwrap();
}
writeln!(prompt, "Always wrap your response in a Markdown codeblock.").unwrap();
writeln!(prompt, "Never make remarks about the output.").unwrap();
let codegen_kind = codegen.read(cx).kind().clone();
let user_prompt = user_prompt.to_string();
let mut messages = Vec::new();
let mut model = settings::get::<AssistantSettings>(cx)
@@ -657,18 +608,26 @@ impl AssistantPanel {
model = conversation.model.clone();
}
messages.push(RequestMessage {
role: Role::User,
content: prompt,
let prompt = cx.background().spawn(async move {
let language_name = language_name.as_deref();
generate_content_prompt(user_prompt, language_name, &buffer, range, codegen_kind)
});
let request = OpenAIRequest {
model: model.full_name().into(),
messages,
stream: true,
};
pending_assist
.codegen
.update(cx, |codegen, cx| codegen.start(request, cx));
cx.spawn(|_, mut cx| async move {
let prompt = prompt.await;
messages.push(RequestMessage {
role: Role::User,
content: prompt,
});
let request = OpenAIRequest {
model: model.full_name().into(),
messages,
stream: true,
};
codegen.update(&mut cx, |codegen, cx| codegen.start(request, cx));
})
.detach();
}
fn update_highlights_for_editor(

View File

@@ -1,59 +1,12 @@
use crate::{
stream_completion,
streaming_diff::{Hunk, StreamingDiff},
OpenAIRequest,
};
use crate::streaming_diff::{Hunk, StreamingDiff};
use ai::completion::{CompletionProvider, OpenAIRequest};
use anyhow::Result;
use editor::{
multi_buffer, Anchor, AnchorRangeExt, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint,
};
use futures::{
channel::mpsc, future::BoxFuture, stream::BoxStream, FutureExt, SinkExt, Stream, StreamExt,
};
use gpui::{executor::Background, Entity, ModelContext, ModelHandle, Task};
use editor::{multi_buffer, Anchor, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint};
use futures::{channel::mpsc, SinkExt, Stream, StreamExt};
use gpui::{Entity, ModelContext, ModelHandle, Task};
use language::{Rope, TransactionId};
use std::{cmp, future, ops::Range, sync::Arc};
pub trait CompletionProvider {
fn complete(
&self,
prompt: OpenAIRequest,
) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>>;
}
pub struct OpenAICompletionProvider {
api_key: String,
executor: Arc<Background>,
}
impl OpenAICompletionProvider {
pub fn new(api_key: String, executor: Arc<Background>) -> Self {
Self { api_key, executor }
}
}
impl CompletionProvider for OpenAICompletionProvider {
fn complete(
&self,
prompt: OpenAIRequest,
) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
let request = stream_completion(self.api_key.clone(), self.executor.clone(), prompt);
async move {
let response = request.await?;
let stream = response
.filter_map(|response| async move {
match response {
Ok(mut response) => Some(Ok(response.choices.pop()?.delta.content?)),
Err(error) => Some(Err(error)),
}
})
.boxed();
Ok(stream)
}
.boxed()
}
}
pub enum Event {
Finished,
Undone,
@@ -85,26 +38,11 @@ impl Entity for Codegen {
impl Codegen {
pub fn new(
buffer: ModelHandle<MultiBuffer>,
mut kind: CodegenKind,
kind: CodegenKind,
provider: Arc<dyn CompletionProvider>,
cx: &mut ModelContext<Self>,
) -> Self {
let snapshot = buffer.read(cx).snapshot(cx);
match &mut kind {
CodegenKind::Transform { range } => {
let mut point_range = range.to_point(&snapshot);
point_range.start.column = 0;
if point_range.end.column > 0 || point_range.start.row == point_range.end.row {
point_range.end.column = snapshot.line_len(point_range.end.row);
}
range.start = snapshot.anchor_before(point_range.start);
range.end = snapshot.anchor_after(point_range.end);
}
CodegenKind::Generate { position } => {
*position = position.bias_right(&snapshot);
}
}
Self {
provider,
buffer: buffer.clone(),
@@ -397,13 +335,17 @@ fn strip_markdown_codeblock(
#[cfg(test)]
mod tests {
use super::*;
use futures::stream;
use futures::{
future::BoxFuture,
stream::{self, BoxStream},
};
use gpui::{executor::Deterministic, TestAppContext};
use indoc::indoc;
use language::{language_settings, tree_sitter_rust, Buffer, Language, LanguageConfig, Point};
use parking_lot::Mutex;
use rand::prelude::*;
use settings::SettingsStore;
use smol::future::FutureExt;
#[gpui::test(iterations = 10)]
async fn test_transform_autoindent(
@@ -427,7 +369,7 @@ mod tests {
let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
let range = buffer.read_with(cx, |buffer, cx| {
let snapshot = buffer.snapshot(cx);
snapshot.anchor_before(Point::new(1, 4))..snapshot.anchor_after(Point::new(4, 4))
snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
});
let provider = Arc::new(TestCompletionProvider::new());
let codegen = cx.add_model(|cx| {

View File

@@ -0,0 +1,418 @@
use crate::codegen::CodegenKind;
use language::{BufferSnapshot, OffsetRangeExt, ToOffset};
use std::cmp::{self, Reverse};
use std::fmt::Write;
use std::ops::Range;
#[allow(dead_code)]
fn summarize(buffer: &BufferSnapshot, selected_range: Range<impl ToOffset>) -> String {
#[derive(Debug)]
struct Match {
collapse: Range<usize>,
keep: Vec<Range<usize>>,
}
let selected_range = selected_range.to_offset(buffer);
let mut ts_matches = buffer.matches(0..buffer.len(), |grammar| {
Some(&grammar.embedding_config.as_ref()?.query)
});
let configs = ts_matches
.grammars()
.iter()
.map(|g| g.embedding_config.as_ref().unwrap())
.collect::<Vec<_>>();
let mut matches = Vec::new();
while let Some(mat) = ts_matches.peek() {
let config = &configs[mat.grammar_index];
if let Some(collapse) = mat.captures.iter().find_map(|cap| {
if Some(cap.index) == config.collapse_capture_ix {
Some(cap.node.byte_range())
} else {
None
}
}) {
let mut keep = Vec::new();
for capture in mat.captures.iter() {
if Some(capture.index) == config.keep_capture_ix {
keep.push(capture.node.byte_range());
} else {
continue;
}
}
ts_matches.advance();
matches.push(Match { collapse, keep });
} else {
ts_matches.advance();
}
}
matches.sort_unstable_by_key(|mat| (mat.collapse.start, Reverse(mat.collapse.end)));
let mut matches = matches.into_iter().peekable();
let mut summary = String::new();
let mut offset = 0;
let mut flushed_selection = false;
while let Some(mat) = matches.next() {
// Keep extending the collapsed range if the next match surrounds
// the current one.
while let Some(next_mat) = matches.peek() {
if mat.collapse.start <= next_mat.collapse.start
&& mat.collapse.end >= next_mat.collapse.end
{
matches.next().unwrap();
} else {
break;
}
}
if offset > mat.collapse.start {
// Skip collapsed nodes that have already been summarized.
offset = cmp::max(offset, mat.collapse.end);
continue;
}
if offset <= selected_range.start && selected_range.start <= mat.collapse.end {
if !flushed_selection {
// The collapsed node ends after the selection starts, so we'll flush the selection first.
summary.extend(buffer.text_for_range(offset..selected_range.start));
summary.push_str("<|START|");
if selected_range.end == selected_range.start {
summary.push_str(">");
} else {
summary.extend(buffer.text_for_range(selected_range.clone()));
summary.push_str("|END|>");
}
offset = selected_range.end;
flushed_selection = true;
}
// If the selection intersects the collapsed node, we won't collapse it.
if selected_range.end >= mat.collapse.start {
continue;
}
}
summary.extend(buffer.text_for_range(offset..mat.collapse.start));
for keep in mat.keep {
summary.extend(buffer.text_for_range(keep));
}
offset = mat.collapse.end;
}
// Flush selection if we haven't already done so.
if !flushed_selection && offset <= selected_range.start {
summary.extend(buffer.text_for_range(offset..selected_range.start));
summary.push_str("<|START|");
if selected_range.end == selected_range.start {
summary.push_str(">");
} else {
summary.extend(buffer.text_for_range(selected_range.clone()));
summary.push_str("|END|>");
}
offset = selected_range.end;
}
summary.extend(buffer.text_for_range(offset..buffer.len()));
summary
}
pub fn generate_content_prompt(
user_prompt: String,
language_name: Option<&str>,
buffer: &BufferSnapshot,
range: Range<impl ToOffset>,
kind: CodegenKind,
) -> String {
let range = range.to_offset(buffer);
let mut prompt = String::new();
// General Preamble
if let Some(language_name) = language_name {
writeln!(prompt, "You're an expert {language_name} engineer.\n").unwrap();
} else {
writeln!(prompt, "You're an expert engineer.\n").unwrap();
}
let mut content = String::new();
content.extend(buffer.text_for_range(0..range.start));
if range.start == range.end {
content.push_str("<|START|>");
} else {
content.push_str("<|START|");
}
content.extend(buffer.text_for_range(range.clone()));
if range.start != range.end {
content.push_str("|END|>");
}
content.extend(buffer.text_for_range(range.end..buffer.len()));
writeln!(
prompt,
"The file you are currently working on has the following content:"
)
.unwrap();
if let Some(language_name) = language_name {
let language_name = language_name.to_lowercase();
writeln!(prompt, "```{language_name}\n{content}\n```").unwrap();
} else {
writeln!(prompt, "```\n{content}\n```").unwrap();
}
match kind {
CodegenKind::Generate { position: _ } => {
writeln!(prompt, "In particular, the user's cursor is current on the '<|START|>' span in the above outline, with no text selected.").unwrap();
writeln!(
prompt,
"Assume the cursor is located where the `<|START|` marker is."
)
.unwrap();
writeln!(
prompt,
"Text can't be replaced, so assume your answer will be inserted at the cursor."
)
.unwrap();
writeln!(
prompt,
"Generate text based on the users prompt: {user_prompt}"
)
.unwrap();
}
CodegenKind::Transform { range: _ } => {
writeln!(prompt, "In particular, the user has selected a section of the text between the '<|START|' and '|END|>' spans.").unwrap();
writeln!(
prompt,
"Modify the users code selected text based upon the users prompt: {user_prompt}"
)
.unwrap();
writeln!(
prompt,
"You MUST reply with only the adjusted code (within the '<|START|' and '|END|>' spans), not the entire file."
)
.unwrap();
}
}
if let Some(language_name) = language_name {
writeln!(prompt, "Your answer MUST always be valid {language_name}").unwrap();
}
writeln!(prompt, "Always wrap your response in a Markdown codeblock").unwrap();
writeln!(prompt, "Never make remarks about the output.").unwrap();
prompt
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use std::sync::Arc;
use gpui::AppContext;
use indoc::indoc;
use language::{language_settings, tree_sitter_rust, Buffer, Language, LanguageConfig, Point};
use settings::SettingsStore;
pub(crate) fn rust_lang() -> Language {
Language::new(
LanguageConfig {
name: "Rust".into(),
path_suffixes: vec!["rs".to_string()],
..Default::default()
},
Some(tree_sitter_rust::language()),
)
.with_embedding_query(
r#"
(
[(line_comment) (attribute_item)]* @context
.
[
(struct_item
name: (_) @name)
(enum_item
name: (_) @name)
(impl_item
trait: (_)? @name
"for"? @name
type: (_) @name)
(trait_item
name: (_) @name)
(function_item
name: (_) @name
body: (block
"{" @keep
"}" @keep) @collapse)
(macro_definition
name: (_) @name)
] @item
)
"#,
)
.unwrap()
}
#[gpui::test]
fn test_outline_for_prompt(cx: &mut AppContext) {
cx.set_global(SettingsStore::test(cx));
language_settings::init(cx);
let text = indoc! {"
struct X {
a: usize,
b: usize,
}
impl X {
fn new() -> Self {
let a = 1;
let b = 2;
Self { a, b }
}
pub fn a(&self, param: bool) -> usize {
self.a
}
pub fn b(&self) -> usize {
self.b
}
}
"};
let buffer =
cx.add_model(|cx| Buffer::new(0, 0, text).with_language(Arc::new(rust_lang()), cx));
let snapshot = buffer.read(cx).snapshot();
assert_eq!(
summarize(&snapshot, Point::new(1, 4)..Point::new(1, 4)),
indoc! {"
struct X {
<|START|>a: usize,
b: usize,
}
impl X {
fn new() -> Self {}
pub fn a(&self, param: bool) -> usize {}
pub fn b(&self) -> usize {}
}
"}
);
assert_eq!(
summarize(&snapshot, Point::new(8, 12)..Point::new(8, 14)),
indoc! {"
struct X {
a: usize,
b: usize,
}
impl X {
fn new() -> Self {
let <|START|a |END|>= 1;
let b = 2;
Self { a, b }
}
pub fn a(&self, param: bool) -> usize {}
pub fn b(&self) -> usize {}
}
"}
);
assert_eq!(
summarize(&snapshot, Point::new(6, 0)..Point::new(6, 0)),
indoc! {"
struct X {
a: usize,
b: usize,
}
impl X {
<|START|>
fn new() -> Self {}
pub fn a(&self, param: bool) -> usize {}
pub fn b(&self) -> usize {}
}
"}
);
assert_eq!(
summarize(&snapshot, Point::new(21, 0)..Point::new(21, 0)),
indoc! {"
struct X {
a: usize,
b: usize,
}
impl X {
fn new() -> Self {}
pub fn a(&self, param: bool) -> usize {}
pub fn b(&self) -> usize {}
}
<|START|>"}
);
// Ensure nested functions get collapsed properly.
let text = indoc! {"
struct X {
a: usize,
b: usize,
}
impl X {
fn new() -> Self {
let a = 1;
let b = 2;
Self { a, b }
}
pub fn a(&self, param: bool) -> usize {
let a = 30;
fn nested() -> usize {
3
}
self.a + nested()
}
pub fn b(&self) -> usize {
self.b
}
}
"};
buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
let snapshot = buffer.read(cx).snapshot();
assert_eq!(
summarize(&snapshot, Point::new(0, 0)..Point::new(0, 0)),
indoc! {"
<|START|>struct X {
a: usize,
b: usize,
}
impl X {
fn new() -> Self {}
pub fn a(&self, param: bool) -> usize {}
pub fn b(&self) -> usize {}
}
"}
);
}
}

View File

@@ -115,13 +115,15 @@ pub fn check(_: &Check, cx: &mut AppContext) {
fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) {
if let Some(auto_updater) = AutoUpdater::get(cx) {
let server_url = &auto_updater.read(cx).server_url;
let auto_updater = auto_updater.read(cx);
let server_url = &auto_updater.server_url;
let current_version = auto_updater.current_version;
let latest_release_url = if cx.has_global::<ReleaseChannel>()
&& *cx.global::<ReleaseChannel>() == ReleaseChannel::Preview
{
format!("{server_url}/releases/preview/latest")
format!("{server_url}/releases/preview/{current_version}")
} else {
format!("{server_url}/releases/stable/latest")
format!("{server_url}/releases/stable/{current_version}")
};
cx.platform().open_url(&latest_release_url);
}

View File

@@ -2,22 +2,23 @@ pub mod call_settings;
pub mod participant;
pub mod room;
use std::sync::Arc;
use anyhow::{anyhow, Result};
use audio::Audio;
use call_settings::CallSettings;
use channel::ChannelId;
use client::{proto, ClickhouseEvent, Client, TelemetrySettings, TypedEnvelope, User, UserStore};
use client::{
proto, ClickhouseEvent, Client, TelemetrySettings, TypedEnvelope, User, UserStore,
ZED_ALWAYS_ACTIVE,
};
use collections::HashSet;
use futures::{future::Shared, FutureExt};
use postage::watch;
use gpui::{
AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, Subscription, Task,
WeakModelHandle,
};
use postage::watch;
use project::Project;
use std::sync::Arc;
pub use participant::ParticipantLocation;
pub use room::Room;
@@ -68,6 +69,7 @@ impl ActiveCall {
location: None,
pending_invites: Default::default(),
incoming_call: watch::channel(),
_subscriptions: vec![
client.add_request_handler(cx.handle(), Self::handle_incoming_call),
client.add_message_handler(cx.handle(), Self::handle_call_canceled),
@@ -206,9 +208,14 @@ impl ActiveCall {
cx.spawn(|this, mut cx| async move {
let result = invite.await;
if result.is_ok() {
this.update(&mut cx, |this, cx| this.report_call_event("invite", cx));
} else {
// TODO: Resport collaboration error
}
this.update(&mut cx, |this, cx| {
this.pending_invites.remove(&called_user_id);
this.report_call_event("invite", cx);
cx.notify();
});
result
@@ -273,13 +280,7 @@ impl ActiveCall {
.borrow_mut()
.take()
.ok_or_else(|| anyhow!("no incoming call"))?;
Self::report_call_event_for_room(
"decline incoming",
Some(call.room_id),
None,
&self.client,
cx,
);
report_call_event_for_room("decline incoming", call.room_id, None, &self.client, cx);
self.client.send(proto::DeclineCall {
room_id: call.room_id,
})?;
@@ -290,10 +291,10 @@ impl ActiveCall {
&mut self,
channel_id: u64,
cx: &mut ModelContext<Self>,
) -> Task<Result<()>> {
) -> Task<Result<ModelHandle<Room>>> {
if let Some(room) = self.room().cloned() {
if room.read(cx).channel_id() == Some(channel_id) {
return Task::ready(Ok(()));
return Task::ready(Ok(room));
} else {
room.update(cx, |room, cx| room.clear_state(cx));
}
@@ -308,7 +309,7 @@ impl ActiveCall {
this.update(&mut cx, |this, cx| {
this.report_call_event("join channel", cx)
});
Ok(())
Ok(room)
})
}
@@ -349,17 +350,22 @@ impl ActiveCall {
}
}
pub fn location(&self) -> Option<&WeakModelHandle<Project>> {
self.location.as_ref()
}
pub fn set_location(
&mut self,
project: Option<&ModelHandle<Project>>,
cx: &mut ModelContext<Self>,
) -> Task<Result<()>> {
self.location = project.map(|project| project.downgrade());
if let Some((room, _)) = self.room.as_ref() {
room.update(cx, |room, cx| room.set_location(project, cx))
} else {
Task::ready(Ok(()))
if project.is_some() || !*ZED_ALWAYS_ACTIVE {
self.location = project.map(|project| project.downgrade());
if let Some((room, _)) = self.room.as_ref() {
return room.update(cx, |room, cx| room.set_location(project, cx));
}
}
Task::ready(Ok(()))
}
fn set_room(
@@ -409,31 +415,46 @@ impl ActiveCall {
&self.pending_invites
}
fn report_call_event(&self, operation: &'static str, cx: &AppContext) {
let (room_id, channel_id) = match self.room() {
Some(room) => {
let room = room.read(cx);
(Some(room.id()), room.channel_id())
}
None => (None, None),
};
Self::report_call_event_for_room(operation, room_id, channel_id, &self.client, cx)
}
pub fn report_call_event_for_room(
operation: &'static str,
room_id: Option<u64>,
channel_id: Option<u64>,
client: &Arc<Client>,
cx: &AppContext,
) {
let telemetry = client.telemetry();
let telemetry_settings = *settings::get::<TelemetrySettings>(cx);
let event = ClickhouseEvent::Call {
operation,
room_id,
channel_id,
};
telemetry.report_clickhouse_event(event, telemetry_settings);
pub fn report_call_event(&self, operation: &'static str, cx: &AppContext) {
if let Some(room) = self.room() {
let room = room.read(cx);
report_call_event_for_room(operation, room.id(), room.channel_id(), &self.client, cx);
}
}
}
pub fn report_call_event_for_room(
operation: &'static str,
room_id: u64,
channel_id: Option<u64>,
client: &Arc<Client>,
cx: &AppContext,
) {
let telemetry = client.telemetry();
let telemetry_settings = *settings::get::<TelemetrySettings>(cx);
let event = ClickhouseEvent::Call {
operation,
room_id: Some(room_id),
channel_id,
};
telemetry.report_clickhouse_event(event, telemetry_settings);
}
pub fn report_call_event_for_channel(
operation: &'static str,
channel_id: u64,
client: &Arc<Client>,
cx: &AppContext,
) {
let room = ActiveCall::global(cx).read(cx).room();
let telemetry = client.telemetry();
let telemetry_settings = *settings::get::<TelemetrySettings>(cx);
let event = ClickhouseEvent::Call {
operation,
room_id: room.map(|r| r.read(cx).id()),
channel_id: Some(channel_id),
};
telemetry.report_clickhouse_event(event, telemetry_settings);
}

View File

@@ -1,4 +1,5 @@
use anyhow::{anyhow, Result};
use client::ParticipantIndex;
use client::{proto, User};
use collections::HashMap;
use gpui::WeakModelHandle;
@@ -43,6 +44,7 @@ pub struct RemoteParticipant {
pub peer_id: proto::PeerId,
pub projects: Vec<proto::ParticipantProject>,
pub location: ParticipantLocation,
pub participant_index: ParticipantIndex,
pub muted: bool,
pub speaking: bool,
pub video_tracks: HashMap<live_kit_client::Sid, Arc<RemoteVideoTrack>>,

View File

@@ -7,7 +7,7 @@ use anyhow::{anyhow, Result};
use audio::{Audio, Sound};
use client::{
proto::{self, PeerId},
Client, TypedEnvelope, User, UserStore,
Client, ParticipantIndex, TypedEnvelope, User, UserStore,
};
use collections::{BTreeMap, HashMap, HashSet};
use fs::Fs;
@@ -44,6 +44,12 @@ pub enum Event {
RemoteProjectUnshared {
project_id: u64,
},
RemoteProjectJoined {
project_id: u64,
},
RemoteProjectInvitationDiscarded {
project_id: u64,
},
Left,
}
@@ -98,6 +104,10 @@ impl Room {
self.channel_id
}
pub fn is_sharing_project(&self) -> bool {
!self.shared_projects.is_empty()
}
#[cfg(any(test, feature = "test-support"))]
pub fn is_connected(&self) -> bool {
if let Some(live_kit) = self.live_kit.as_ref() {
@@ -588,6 +598,34 @@ impl Room {
.map_or(&[], |v| v.as_slice())
}
/// Returns the most 'active' projects, defined as most people in the project
pub fn most_active_project(&self) -> Option<(u64, u64)> {
let mut project_hosts_and_guest_counts = HashMap::<u64, (Option<u64>, u32)>::default();
for participant in self.remote_participants.values() {
match participant.location {
ParticipantLocation::SharedProject { project_id } => {
project_hosts_and_guest_counts
.entry(project_id)
.or_default()
.1 += 1;
}
ParticipantLocation::External | ParticipantLocation::UnsharedProject => {}
}
for project in &participant.projects {
project_hosts_and_guest_counts
.entry(project.id)
.or_default()
.0 = Some(participant.user.id);
}
}
project_hosts_and_guest_counts
.into_iter()
.filter_map(|(id, (host, guest_count))| Some((id, host?, guest_count)))
.max_by_key(|(_, _, guest_count)| *guest_count)
.map(|(id, host, _)| (id, host))
}
async fn handle_room_updated(
this: ModelHandle<Self>,
envelope: TypedEnvelope<proto::RoomUpdated>,
@@ -651,6 +689,7 @@ impl Room {
let Some(peer_id) = participant.peer_id else {
continue;
};
let participant_index = ParticipantIndex(participant.participant_index);
this.participant_user_ids.insert(participant.user_id);
let old_projects = this
@@ -701,8 +740,9 @@ impl Room {
if let Some(remote_participant) =
this.remote_participants.get_mut(&participant.user_id)
{
remote_participant.projects = participant.projects;
remote_participant.peer_id = peer_id;
remote_participant.projects = participant.projects;
remote_participant.participant_index = participant_index;
if location != remote_participant.location {
remote_participant.location = location;
cx.emit(Event::ParticipantLocationChanged {
@@ -714,6 +754,7 @@ impl Room {
participant.user_id,
RemoteParticipant {
user: user.clone(),
participant_index,
peer_id,
projects: participant.projects,
location,
@@ -807,6 +848,15 @@ impl Room {
let _ = this.leave(cx);
}
this.user_store.update(cx, |user_store, cx| {
let participant_indices_by_user_id = this
.remote_participants
.iter()
.map(|(user_id, participant)| (*user_id, participant.participant_index))
.collect();
user_store.set_participant_indices(participant_indices_by_user_id, cx);
});
this.check_invariants();
cx.notify();
});
@@ -1003,6 +1053,7 @@ impl Room {
) -> Task<Result<ModelHandle<Project>>> {
let client = self.client.clone();
let user_store = self.user_store.clone();
cx.emit(Event::RemoteProjectJoined { project_id: id });
cx.spawn(|this, mut cx| async move {
let project =
Project::remote(id, client, user_store, language_registry, fs, cx.clone()).await?;

View File

@@ -23,6 +23,7 @@ language = { path = "../language" }
settings = { path = "../settings" }
feature_flags = { path = "../feature_flags" }
sum_tree = { path = "../sum_tree" }
clock = { path = "../clock" }
anyhow.workspace = true
futures.workspace = true
@@ -38,7 +39,7 @@ smol.workspace = true
thiserror.workspace = true
time.workspace = true
tiny_http = "0.8"
uuid = { version = "1.1.2", features = ["v4"] }
uuid.workspace = true
url = "2.2"
serde.workspace = true
serde_derive.workspace = true

View File

@@ -2,7 +2,7 @@ mod channel_buffer;
mod channel_chat;
mod channel_store;
pub use channel_buffer::{ChannelBuffer, ChannelBufferEvent};
pub use channel_buffer::{ChannelBuffer, ChannelBufferEvent, ACKNOWLEDGE_DEBOUNCE_INTERVAL};
pub use channel_chat::{ChannelChat, ChannelChatEvent, ChannelMessage, ChannelMessageId};
pub use channel_store::{
Channel, ChannelData, ChannelEvent, ChannelId, ChannelMembership, ChannelPath, ChannelStore,

View File

@@ -1,31 +1,39 @@
use crate::Channel;
use anyhow::Result;
use client::Client;
use gpui::{AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle};
use rpc::{proto, TypedEnvelope};
use std::sync::Arc;
use client::{Client, Collaborator, UserStore};
use collections::HashMap;
use gpui::{AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, Task};
use language::proto::serialize_version;
use rpc::{
proto::{self, PeerId},
TypedEnvelope,
};
use std::{sync::Arc, time::Duration};
use util::ResultExt;
pub const ACKNOWLEDGE_DEBOUNCE_INTERVAL: Duration = Duration::from_millis(250);
pub(crate) fn init(client: &Arc<Client>) {
client.add_model_message_handler(ChannelBuffer::handle_update_channel_buffer);
client.add_model_message_handler(ChannelBuffer::handle_add_channel_buffer_collaborator);
client.add_model_message_handler(ChannelBuffer::handle_remove_channel_buffer_collaborator);
client.add_model_message_handler(ChannelBuffer::handle_update_channel_buffer_collaborator);
client.add_model_message_handler(ChannelBuffer::handle_update_channel_buffer_collaborators);
}
pub struct ChannelBuffer {
pub(crate) channel: Arc<Channel>,
connected: bool,
collaborators: Vec<proto::Collaborator>,
collaborators: HashMap<PeerId, Collaborator>,
user_store: ModelHandle<UserStore>,
buffer: ModelHandle<language::Buffer>,
buffer_epoch: u64,
client: Arc<Client>,
subscription: Option<client::Subscription>,
acknowledge_task: Option<Task<Result<()>>>,
}
pub enum ChannelBufferEvent {
CollaboratorsChanged,
Disconnected,
BufferEdited,
}
impl Entity for ChannelBuffer {
@@ -33,6 +41,9 @@ impl Entity for ChannelBuffer {
fn release(&mut self, _: &mut AppContext) {
if self.connected {
if let Some(task) = self.acknowledge_task.take() {
task.detach();
}
self.client
.send(proto::LeaveChannelBuffer {
channel_id: self.channel.id,
@@ -46,6 +57,7 @@ impl ChannelBuffer {
pub(crate) async fn new(
channel: Arc<Channel>,
client: Arc<Client>,
user_store: ModelHandle<UserStore>,
mut cx: AsyncAppContext,
) -> Result<ModelHandle<Self>> {
let response = client
@@ -61,8 +73,6 @@ impl ChannelBuffer {
.map(language::proto::deserialize_operation)
.collect::<Result<Vec<_>, _>>()?;
let collaborators = response.collaborators;
let buffer = cx.add_model(|_| {
language::Buffer::remote(response.buffer_id, response.replica_id as u16, base_text)
});
@@ -73,34 +83,46 @@ impl ChannelBuffer {
anyhow::Ok(cx.add_model(|cx| {
cx.subscribe(&buffer, Self::on_buffer_update).detach();
Self {
let mut this = Self {
buffer,
buffer_epoch: response.epoch,
client,
connected: true,
collaborators,
collaborators: Default::default(),
acknowledge_task: None,
channel,
subscription: Some(subscription.set_model(&cx.handle(), &mut cx.to_async())),
}
user_store,
};
this.replace_collaborators(response.collaborators, cx);
this
}))
}
pub fn user_store(&self) -> &ModelHandle<UserStore> {
&self.user_store
}
pub(crate) fn replace_collaborators(
&mut self,
collaborators: Vec<proto::Collaborator>,
cx: &mut ModelContext<Self>,
) {
for old_collaborator in &self.collaborators {
if collaborators
.iter()
.any(|c| c.replica_id == old_collaborator.replica_id)
{
let mut new_collaborators = HashMap::default();
for collaborator in collaborators {
if let Ok(collaborator) = Collaborator::from_proto(collaborator) {
new_collaborators.insert(collaborator.peer_id, collaborator);
}
}
for (_, old_collaborator) in &self.collaborators {
if !new_collaborators.contains_key(&old_collaborator.peer_id) {
self.buffer.update(cx, |buffer, cx| {
buffer.remove_peer(old_collaborator.replica_id as u16, cx)
});
}
}
self.collaborators = collaborators;
self.collaborators = new_collaborators;
cx.emit(ChannelBufferEvent::CollaboratorsChanged);
cx.notify();
}
@@ -127,64 +149,14 @@ impl ChannelBuffer {
Ok(())
}
async fn handle_add_channel_buffer_collaborator(
async fn handle_update_channel_buffer_collaborators(
this: ModelHandle<Self>,
envelope: TypedEnvelope<proto::AddChannelBufferCollaborator>,
_: Arc<Client>,
mut cx: AsyncAppContext,
) -> Result<()> {
let collaborator = envelope.payload.collaborator.ok_or_else(|| {
anyhow::anyhow!(
"Should have gotten a collaborator in the AddChannelBufferCollaborator message"
)
})?;
this.update(&mut cx, |this, cx| {
this.collaborators.push(collaborator);
cx.emit(ChannelBufferEvent::CollaboratorsChanged);
cx.notify();
});
Ok(())
}
async fn handle_remove_channel_buffer_collaborator(
this: ModelHandle<Self>,
message: TypedEnvelope<proto::RemoveChannelBufferCollaborator>,
message: TypedEnvelope<proto::UpdateChannelBufferCollaborators>,
_: Arc<Client>,
mut cx: AsyncAppContext,
) -> Result<()> {
this.update(&mut cx, |this, cx| {
this.collaborators.retain(|collaborator| {
if collaborator.peer_id == message.payload.peer_id {
this.buffer.update(cx, |buffer, cx| {
buffer.remove_peer(collaborator.replica_id as u16, cx)
});
false
} else {
true
}
});
cx.emit(ChannelBufferEvent::CollaboratorsChanged);
cx.notify();
});
Ok(())
}
async fn handle_update_channel_buffer_collaborator(
this: ModelHandle<Self>,
message: TypedEnvelope<proto::UpdateChannelBufferCollaborator>,
_: Arc<Client>,
mut cx: AsyncAppContext,
) -> Result<()> {
this.update(&mut cx, |this, cx| {
for collaborator in &mut this.collaborators {
if collaborator.peer_id == message.payload.old_peer_id {
collaborator.peer_id = message.payload.new_peer_id;
break;
}
}
this.replace_collaborators(message.payload.collaborators, cx);
cx.emit(ChannelBufferEvent::CollaboratorsChanged);
cx.notify();
});
@@ -196,19 +168,45 @@ impl ChannelBuffer {
&mut self,
_: ModelHandle<language::Buffer>,
event: &language::Event,
_: &mut ModelContext<Self>,
cx: &mut ModelContext<Self>,
) {
if let language::Event::Operation(operation) = event {
let operation = language::proto::serialize_operation(operation);
self.client
.send(proto::UpdateChannelBuffer {
channel_id: self.channel.id,
operations: vec![operation],
})
.log_err();
match event {
language::Event::Operation(operation) => {
let operation = language::proto::serialize_operation(operation);
self.client
.send(proto::UpdateChannelBuffer {
channel_id: self.channel.id,
operations: vec![operation],
})
.log_err();
}
language::Event::Edited => {
cx.emit(ChannelBufferEvent::BufferEdited);
}
_ => {}
}
}
pub fn acknowledge_buffer_version(&mut self, cx: &mut ModelContext<'_, ChannelBuffer>) {
let buffer = self.buffer.read(cx);
let version = buffer.version();
let buffer_id = buffer.remote_id();
let client = self.client.clone();
let epoch = self.epoch();
self.acknowledge_task = Some(cx.spawn_weak(|_, cx| async move {
cx.background().timer(ACKNOWLEDGE_DEBOUNCE_INTERVAL).await;
client
.send(proto::AckBufferOperation {
buffer_id,
epoch,
version: serialize_version(&version),
})
.ok();
Ok(())
}));
}
pub fn epoch(&self) -> u64 {
self.buffer_epoch
}
@@ -217,7 +215,7 @@ impl ChannelBuffer {
self.buffer.clone()
}
pub fn collaborators(&self) -> &[proto::Collaborator] {
pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
&self.collaborators
}

View File

@@ -1,4 +1,4 @@
use crate::Channel;
use crate::{Channel, ChannelId, ChannelStore};
use anyhow::{anyhow, Result};
use client::{
proto,
@@ -16,7 +16,9 @@ use util::{post_inc, ResultExt as _, TryFutureExt};
pub struct ChannelChat {
channel: Arc<Channel>,
messages: SumTree<ChannelMessage>,
channel_store: ModelHandle<ChannelStore>,
loaded_all_messages: bool,
last_acknowledged_id: Option<u64>,
next_pending_message_id: usize,
user_store: ModelHandle<UserStore>,
rpc: Arc<Client>,
@@ -34,7 +36,7 @@ pub struct ChannelMessage {
pub nonce: u128,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ChannelMessageId {
Saved(u64),
Pending(usize),
@@ -55,6 +57,10 @@ pub enum ChannelChatEvent {
old_range: Range<usize>,
new_count: usize,
},
NewMessage {
channel_id: ChannelId,
message_id: u64,
},
}
pub fn init(client: &Arc<Client>) {
@@ -77,6 +83,7 @@ impl Entity for ChannelChat {
impl ChannelChat {
pub async fn new(
channel: Arc<Channel>,
channel_store: ModelHandle<ChannelStore>,
user_store: ModelHandle<UserStore>,
client: Arc<Client>,
mut cx: AsyncAppContext,
@@ -94,11 +101,13 @@ impl ChannelChat {
let mut this = Self {
channel,
user_store,
channel_store,
rpc: client,
outgoing_messages_lock: Default::default(),
messages: Default::default(),
loaded_all_messages,
next_pending_message_id: 0,
last_acknowledged_id: None,
rng: StdRng::from_entropy(),
_subscription: subscription.set_model(&cx.handle(), &mut cx.to_async()),
};
@@ -219,6 +228,26 @@ impl ChannelChat {
false
}
pub fn acknowledge_last_message(&mut self, cx: &mut ModelContext<Self>) {
if let ChannelMessageId::Saved(latest_message_id) = self.messages.summary().max_id {
if self
.last_acknowledged_id
.map_or(true, |acknowledged_id| acknowledged_id < latest_message_id)
{
self.rpc
.send(proto::AckChannelMessage {
channel_id: self.channel.id,
message_id: latest_message_id,
})
.ok();
self.last_acknowledged_id = Some(latest_message_id);
self.channel_store.update(cx, |store, cx| {
store.acknowledge_message_id(self.channel.id, latest_message_id, cx);
});
}
}
}
pub fn rejoin(&mut self, cx: &mut ModelContext<Self>) {
let user_store = self.user_store.clone();
let rpc = self.rpc.clone();
@@ -313,10 +342,15 @@ impl ChannelChat {
.payload
.message
.ok_or_else(|| anyhow!("empty message"))?;
let message_id = message.id;
let message = ChannelMessage::from_proto(message, &user_store, &mut cx).await?;
this.update(&mut cx, |this, cx| {
this.insert_messages(SumTree::from_item(message, &()), cx)
this.insert_messages(SumTree::from_item(message, &()), cx);
cx.emit(ChannelChatEvent::NewMessage {
channel_id: this.channel.id,
message_id,
})
});
Ok(())
@@ -388,6 +422,7 @@ impl ChannelChat {
old_range: start_ix..end_ix,
new_count,
});
cx.notify();
}
}

View File

@@ -43,6 +43,8 @@ pub type ChannelData = (Channel, ChannelPath);
pub struct Channel {
pub id: ChannelId,
pub name: String,
pub unseen_note_version: Option<(u64, clock::Global)>,
pub unseen_message_id: Option<u64>,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
@@ -198,14 +200,73 @@ impl ChannelStore {
cx: &mut ModelContext<Self>,
) -> Task<Result<ModelHandle<ChannelBuffer>>> {
let client = self.client.clone();
let user_store = self.user_store.clone();
self.open_channel_resource(
channel_id,
|this| &mut this.opened_buffers,
|channel, cx| ChannelBuffer::new(channel, client, cx),
|channel, cx| ChannelBuffer::new(channel, client, user_store, cx),
cx,
)
}
pub fn has_channel_buffer_changed(&self, channel_id: ChannelId) -> Option<bool> {
self.channel_index
.by_id()
.get(&channel_id)
.map(|channel| channel.unseen_note_version.is_some())
}
pub fn has_new_messages(&self, channel_id: ChannelId) -> Option<bool> {
self.channel_index
.by_id()
.get(&channel_id)
.map(|channel| channel.unseen_message_id.is_some())
}
pub fn notes_changed(
&mut self,
channel_id: ChannelId,
epoch: u64,
version: &clock::Global,
cx: &mut ModelContext<Self>,
) {
self.channel_index.note_changed(channel_id, epoch, version);
cx.notify();
}
pub fn new_message(
&mut self,
channel_id: ChannelId,
message_id: u64,
cx: &mut ModelContext<Self>,
) {
self.channel_index.new_message(channel_id, message_id);
cx.notify();
}
pub fn acknowledge_message_id(
&mut self,
channel_id: ChannelId,
message_id: u64,
cx: &mut ModelContext<Self>,
) {
self.channel_index
.acknowledge_message_id(channel_id, message_id);
cx.notify();
}
pub fn acknowledge_notes_version(
&mut self,
channel_id: ChannelId,
epoch: u64,
version: &clock::Global,
cx: &mut ModelContext<Self>,
) {
self.channel_index
.acknowledge_note_version(channel_id, epoch, version);
cx.notify();
}
pub fn open_channel_chat(
&mut self,
channel_id: ChannelId,
@@ -213,10 +274,11 @@ impl ChannelStore {
) -> Task<Result<ModelHandle<ChannelChat>>> {
let client = self.client.clone();
let user_store = self.user_store.clone();
let this = cx.handle();
self.open_channel_resource(
channel_id,
|this| &mut this.opened_chats,
|channel, cx| ChannelChat::new(channel, user_store, client, cx),
|channel, cx| ChannelChat::new(channel, this, user_store, client, cx),
cx,
)
}
@@ -778,6 +840,8 @@ impl ChannelStore {
Arc::new(Channel {
id: channel.id,
name: channel.name,
unseen_note_version: None,
unseen_message_id: None,
}),
),
}
@@ -786,7 +850,9 @@ impl ChannelStore {
let channels_changed = !payload.channels.is_empty()
|| !payload.delete_channels.is_empty()
|| !payload.insert_edge.is_empty()
|| !payload.delete_edge.is_empty();
|| !payload.delete_edge.is_empty()
|| !payload.unseen_channel_messages.is_empty()
|| !payload.unseen_channel_buffer_changes.is_empty();
if channels_changed {
if !payload.delete_channels.is_empty() {
@@ -813,6 +879,22 @@ impl ChannelStore {
index.insert(channel)
}
for unseen_buffer_change in payload.unseen_channel_buffer_changes {
let version = language::proto::deserialize_version(&unseen_buffer_change.version);
index.note_changed(
unseen_buffer_change.channel_id,
unseen_buffer_change.epoch,
&version,
);
}
for unseen_channel_message in payload.unseen_channel_messages {
index.new_messages(
unseen_channel_message.channel_id,
unseen_channel_message.message_id,
);
}
for edge in payload.insert_edge {
index.insert_edge(edge.channel_id, edge.parent_id);
}

View File

@@ -38,6 +38,43 @@ impl ChannelIndex {
channels_by_id: &mut self.channels_by_id,
}
}
pub fn acknowledge_note_version(
&mut self,
channel_id: ChannelId,
epoch: u64,
version: &clock::Global,
) {
if let Some(channel) = self.channels_by_id.get_mut(&channel_id) {
let channel = Arc::make_mut(channel);
if let Some((unseen_epoch, unseen_version)) = &channel.unseen_note_version {
if epoch > *unseen_epoch
|| epoch == *unseen_epoch && version.observed_all(unseen_version)
{
channel.unseen_note_version = None;
}
}
}
}
pub fn acknowledge_message_id(&mut self, channel_id: ChannelId, message_id: u64) {
if let Some(channel) = self.channels_by_id.get_mut(&channel_id) {
let channel = Arc::make_mut(channel);
if let Some(unseen_message_id) = channel.unseen_message_id {
if message_id >= unseen_message_id {
channel.unseen_message_id = None;
}
}
}
}
pub fn note_changed(&mut self, channel_id: ChannelId, epoch: u64, version: &clock::Global) {
insert_note_changed(&mut self.channels_by_id, channel_id, epoch, version);
}
pub fn new_message(&mut self, channel_id: ChannelId, message_id: u64) {
insert_new_message(&mut self.channels_by_id, channel_id, message_id)
}
}
impl Deref for ChannelIndex {
@@ -76,6 +113,14 @@ impl<'a> ChannelPathsInsertGuard<'a> {
}
}
pub fn note_changed(&mut self, channel_id: ChannelId, epoch: u64, version: &clock::Global) {
insert_note_changed(&mut self.channels_by_id, channel_id, epoch, &version);
}
pub fn new_messages(&mut self, channel_id: ChannelId, message_id: u64) {
insert_new_message(&mut self.channels_by_id, channel_id, message_id)
}
pub fn insert(&mut self, channel_proto: proto::Channel) {
if let Some(existing_channel) = self.channels_by_id.get_mut(&channel_proto.id) {
Arc::make_mut(existing_channel).name = channel_proto.name;
@@ -85,6 +130,8 @@ impl<'a> ChannelPathsInsertGuard<'a> {
Arc::new(Channel {
id: channel_proto.id,
name: channel_proto.name,
unseen_note_version: None,
unseen_message_id: None,
}),
);
self.insert_root(channel_proto.id);
@@ -160,3 +207,32 @@ fn channel_path_sorting_key<'a>(
path.iter()
.map(|id| Some(channels_by_id.get(id)?.name.as_str()))
}
fn insert_note_changed(
channels_by_id: &mut BTreeMap<ChannelId, Arc<Channel>>,
channel_id: u64,
epoch: u64,
version: &clock::Global,
) {
if let Some(channel) = channels_by_id.get_mut(&channel_id) {
let unseen_version = Arc::make_mut(channel)
.unseen_note_version
.get_or_insert((0, clock::Global::new()));
if epoch > unseen_version.0 {
*unseen_version = (epoch, version.clone());
} else {
unseen_version.1.join(&version);
}
}
}
fn insert_new_message(
channels_by_id: &mut BTreeMap<ChannelId, Arc<Channel>>,
channel_id: u64,
message_id: u64,
) {
if let Some(channel) = channels_by_id.get_mut(&channel_id) {
let unseen_message_id = Arc::make_mut(channel).unseen_message_id.get_or_insert(0);
*unseen_message_id = message_id.max(*unseen_message_id);
}
}

View File

@@ -33,15 +33,16 @@ parking_lot.workspace = true
postage.workspace = true
rand.workspace = true
schemars.workspace = true
serde.workspace = true
serde_derive.workspace = true
smol.workspace = true
sysinfo.workspace = true
tempfile = "3"
thiserror.workspace = true
time.workspace = true
tiny_http = "0.8"
uuid = { version = "1.1.2", features = ["v4"] }
uuid.workspace = true
url = "2.2"
serde.workspace = true
serde_derive.workspace = true
tempfile = "3"
[dev-dependencies]
collections = { path = "../collections", features = ["test-support"] }

View File

@@ -34,7 +34,7 @@ use std::{
future::Future,
marker::PhantomData,
path::PathBuf,
sync::{Arc, Weak},
sync::{atomic::AtomicU64, Arc, Weak},
time::{Duration, Instant},
};
use telemetry::Telemetry;
@@ -62,13 +62,15 @@ lazy_static! {
.and_then(|v| v.parse().ok());
pub static ref ZED_APP_PATH: Option<PathBuf> =
std::env::var("ZED_APP_PATH").ok().map(PathBuf::from);
pub static ref ZED_ALWAYS_ACTIVE: bool =
std::env::var("ZED_ALWAYS_ACTIVE").map_or(false, |e| e.len() > 0);
}
pub const ZED_SECRET_CLIENT_TOKEN: &str = "618033988749894";
pub const INITIAL_RECONNECTION_DELAY: Duration = Duration::from_millis(100);
pub const CONNECTION_TIMEOUT: Duration = Duration::from_secs(5);
actions!(client, [SignIn, SignOut]);
actions!(client, [SignIn, SignOut, Reconnect]);
pub fn init_settings(cx: &mut AppContext) {
settings::register::<TelemetrySettings>(cx);
@@ -100,10 +102,21 @@ pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
}
}
});
cx.add_global_action({
let client = client.clone();
move |_: &Reconnect, cx| {
if let Some(client) = client.upgrade() {
cx.spawn(|cx| async move {
client.reconnect(&cx);
})
.detach();
}
}
});
}
pub struct Client {
id: usize,
id: AtomicU64,
peer: Arc<Peer>,
http: Arc<dyn HttpClient>,
telemetry: Arc<Telemetry>,
@@ -372,7 +385,7 @@ impl settings::Setting for TelemetrySettings {
impl Client {
pub fn new(http: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
Arc::new(Self {
id: 0,
id: AtomicU64::new(0),
peer: Peer::new(0),
telemetry: Telemetry::new(http.clone(), cx),
http,
@@ -385,17 +398,16 @@ impl Client {
})
}
pub fn id(&self) -> usize {
self.id
pub fn id(&self) -> u64 {
self.id.load(std::sync::atomic::Ordering::SeqCst)
}
pub fn http_client(&self) -> Arc<dyn HttpClient> {
self.http.clone()
}
#[cfg(any(test, feature = "test-support"))]
pub fn set_id(&mut self, id: usize) -> &Self {
self.id = id;
pub fn set_id(&self, id: u64) -> &Self {
self.id.store(id, std::sync::atomic::Ordering::SeqCst);
self
}
@@ -452,7 +464,7 @@ impl Client {
}
fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncAppContext) {
log::info!("set status on client {}: {:?}", self.id, status);
log::info!("set status on client {}: {:?}", self.id(), status);
let mut state = self.state.write();
*state.status.0.borrow_mut() = status;
@@ -803,6 +815,7 @@ impl Client {
}
}
let credentials = credentials.unwrap();
self.set_id(credentials.user_id);
if was_disconnected {
self.set_status(Status::Connecting, cx);
@@ -1210,6 +1223,11 @@ impl Client {
self.set_status(Status::SignedOut, cx);
}
pub fn reconnect(self: &Arc<Self>, cx: &AsyncAppContext) {
self.peer.teardown();
self.set_status(Status::ConnectionLost, cx);
}
fn connection_id(&self) -> Result<ConnectionId> {
if let Status::Connected { connection_id, .. } = *self.status().borrow() {
Ok(connection_id)
@@ -1219,7 +1237,7 @@ impl Client {
}
pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
log::debug!("rpc send. client_id:{}, name:{}", self.id, T::NAME);
log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
self.peer.send(self.connection_id()?, message)
}
@@ -1235,7 +1253,7 @@ impl Client {
&self,
request: T,
) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
let client_id = self.id;
let client_id = self.id();
log::debug!(
"rpc request start. client_id:{}. name:{}",
client_id,
@@ -1256,7 +1274,7 @@ impl Client {
}
fn respond<T: RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) -> Result<()> {
log::debug!("rpc respond. client_id:{}. name:{}", self.id, T::NAME);
log::debug!("rpc respond. client_id:{}. name:{}", self.id(), T::NAME);
self.peer.respond(receipt, response)
}
@@ -1265,7 +1283,7 @@ impl Client {
receipt: Receipt<T>,
error: proto::Error,
) -> Result<()> {
log::debug!("rpc respond. client_id:{}. name:{}", self.id, T::NAME);
log::debug!("rpc respond. client_id:{}. name:{}", self.id(), T::NAME);
self.peer.respond_with_error(receipt, error)
}
@@ -1334,7 +1352,7 @@ impl Client {
if let Some(handler) = handler {
let future = handler(subscriber, message, &self, cx.clone());
let client_id = self.id;
let client_id = self.id();
log::debug!(
"rpc message received. client_id:{}, sender_id:{:?}, type:{}",
client_id,

View File

@@ -4,6 +4,7 @@ use lazy_static::lazy_static;
use parking_lot::Mutex;
use serde::Serialize;
use std::{env, io::Write, mem, path::PathBuf, sync::Arc, time::Duration};
use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt};
use tempfile::NamedTempFile;
use util::http::HttpClient;
use util::{channel::ReleaseChannel, TryFutureExt};
@@ -17,7 +18,8 @@ pub struct Telemetry {
#[derive(Default)]
struct TelemetryState {
metrics_id: Option<Arc<str>>, // Per logged-in user
installation_id: Option<Arc<str>>, // Per app installation
installation_id: Option<Arc<str>>, // Per app installation (different for dev, preview, and stable)
session_id: Option<Arc<str>>, // Per app launch
app_version: Option<Arc<str>>,
release_channel: Option<&'static str>,
os_name: &'static str,
@@ -40,6 +42,7 @@ lazy_static! {
struct ClickhouseEventRequestBody {
token: &'static str,
installation_id: Option<Arc<str>>,
session_id: Option<Arc<str>>,
is_staff: Option<bool>,
app_version: Option<Arc<str>>,
os_name: &'static str,
@@ -88,6 +91,14 @@ pub enum ClickhouseEvent {
kind: AssistantKind,
model: &'static str,
},
Cpu {
usage_as_percentage: f32,
core_count: u32,
},
Memory {
memory_in_bytes: u64,
virtual_memory_in_bytes: u64,
},
}
#[cfg(debug_assertions)]
@@ -122,6 +133,7 @@ impl Telemetry {
release_channel,
installation_id: None,
metrics_id: None,
session_id: None,
clickhouse_events_queue: Default::default(),
flush_clickhouse_events_task: Default::default(),
log_file: None,
@@ -136,15 +148,61 @@ impl Telemetry {
Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
}
pub fn start(self: &Arc<Self>, installation_id: Option<String>) {
pub fn start(
self: &Arc<Self>,
installation_id: Option<String>,
session_id: String,
cx: &mut AppContext,
) {
let mut state = self.state.lock();
state.installation_id = installation_id.map(|id| id.into());
state.session_id = Some(session_id.into());
let has_clickhouse_events = !state.clickhouse_events_queue.is_empty();
drop(state);
if has_clickhouse_events {
self.flush_clickhouse_events();
}
let this = self.clone();
cx.spawn(|mut cx| async move {
let mut system = System::new_all();
system.refresh_all();
loop {
// Waiting some amount of time before the first query is important to get a reasonable value
// https://docs.rs/sysinfo/0.29.10/sysinfo/trait.ProcessExt.html#tymethod.cpu_usage
const DURATION_BETWEEN_SYSTEM_EVENTS: Duration = Duration::from_secs(60);
smol::Timer::after(DURATION_BETWEEN_SYSTEM_EVENTS).await;
system.refresh_memory();
system.refresh_processes();
let current_process = Pid::from_u32(std::process::id());
let Some(process) = system.processes().get(&current_process) else {
let process = current_process;
log::error!("Failed to find own process {process:?} in system process table");
// TODO: Fire an error telemetry event
return;
};
let memory_event = ClickhouseEvent::Memory {
memory_in_bytes: process.memory(),
virtual_memory_in_bytes: process.virtual_memory(),
};
let cpu_event = ClickhouseEvent::Cpu {
usage_as_percentage: process.cpu_usage(),
core_count: system.cpus().len() as u32,
};
let telemetry_settings = cx.update(|cx| *settings::get::<TelemetrySettings>(cx));
this.report_clickhouse_event(memory_event, telemetry_settings);
this.report_clickhouse_event(cpu_event, telemetry_settings);
}
})
.detach();
}
pub fn set_authenticated_user_info(
@@ -230,22 +288,21 @@ impl Telemetry {
{
let state = this.state.lock();
json_bytes.clear();
serde_json::to_writer(
&mut json_bytes,
&ClickhouseEventRequestBody {
token: ZED_SECRET_CLIENT_TOKEN,
installation_id: state.installation_id.clone(),
is_staff: state.is_staff.clone(),
app_version: state.app_version.clone(),
os_name: state.os_name,
os_version: state.os_version.clone(),
architecture: state.architecture,
let request_body = ClickhouseEventRequestBody {
token: ZED_SECRET_CLIENT_TOKEN,
installation_id: state.installation_id.clone(),
session_id: state.session_id.clone(),
is_staff: state.is_staff.clone(),
app_version: state.app_version.clone(),
os_name: state.os_name,
os_version: state.os_version.clone(),
architecture: state.architecture,
release_channel: state.release_channel,
events,
},
)?;
release_channel: state.release_channel,
events,
};
json_bytes.clear();
serde_json::to_writer(&mut json_bytes, &request_body)?;
}
this.http_client

View File

@@ -7,11 +7,15 @@ use gpui::{AsyncAppContext, Entity, ImageData, ModelContext, ModelHandle, Task};
use postage::{sink::Sink, watch};
use rpc::proto::{RequestMessage, UsersResponse};
use std::sync::{Arc, Weak};
use text::ReplicaId;
use util::http::HttpClient;
use util::TryFutureExt as _;
pub type UserId = u64;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParticipantIndex(pub u32);
#[derive(Default, Debug)]
pub struct User {
pub id: UserId,
@@ -19,6 +23,13 @@ pub struct User {
pub avatar: Option<Arc<ImageData>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Collaborator {
pub peer_id: proto::PeerId,
pub replica_id: ReplicaId,
pub user_id: UserId,
}
impl PartialOrd for User {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
@@ -56,6 +67,7 @@ pub enum ContactRequestStatus {
pub struct UserStore {
users: HashMap<u64, Arc<User>>,
participant_indices: HashMap<u64, ParticipantIndex>,
update_contacts_tx: mpsc::UnboundedSender<UpdateContacts>,
current_user: watch::Receiver<Option<Arc<User>>>,
contacts: Vec<Arc<Contact>>,
@@ -81,6 +93,7 @@ pub enum Event {
kind: ContactEventKind,
},
ShowContacts,
ParticipantIndicesChanged,
}
#[derive(Clone, Copy)]
@@ -118,6 +131,7 @@ impl UserStore {
current_user: current_user_rx,
contacts: Default::default(),
incoming_contact_requests: Default::default(),
participant_indices: Default::default(),
outgoing_contact_requests: Default::default(),
invite_info: None,
client: Arc::downgrade(&client),
@@ -581,6 +595,10 @@ impl UserStore {
self.load_users(proto::FuzzySearchUsers { query }, cx)
}
pub fn get_cached_user(&self, user_id: u64) -> Option<Arc<User>> {
self.users.get(&user_id).cloned()
}
pub fn get_user(
&mut self,
user_id: u64,
@@ -641,6 +659,21 @@ impl UserStore {
}
})
}
pub fn set_participant_indices(
&mut self,
participant_indices: HashMap<u64, ParticipantIndex>,
cx: &mut ModelContext<Self>,
) {
if participant_indices != self.participant_indices {
self.participant_indices = participant_indices;
cx.emit(Event::ParticipantIndicesChanged);
}
}
pub fn participant_indices(&self) -> &HashMap<u64, ParticipantIndex> {
&self.participant_indices
}
}
impl User {
@@ -672,6 +705,16 @@ impl Contact {
}
}
impl Collaborator {
pub fn from_proto(message: proto::Collaborator) -> Result<Self> {
Ok(Self {
peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
replica_id: message.replica_id as ReplicaId,
user_id: message.user_id as UserId,
})
}
}
async fn fetch_avatar(http: &dyn HttpClient, url: &str) -> Result<Arc<ImageData>> {
let mut response = http
.get(url, Default::default(), true)

View File

@@ -3,7 +3,7 @@ authors = ["Nathan Sobo <nathan@zed.dev>"]
default-run = "collab"
edition = "2021"
name = "collab"
version = "0.21.0"
version = "0.22.2"
publish = false
[[bin]]
@@ -42,14 +42,12 @@ rand.workspace = true
reqwest = { version = "0.11", features = ["json"], optional = true }
scrypt = "0.7"
smallvec.workspace = true
# Remove fork dependency when a version with https://github.com/SeaQL/sea-orm/pull/1283 is released.
sea-orm = { git = "https://github.com/zed-industries/sea-orm", rev = "18f4c691085712ad014a51792af75a9044bacee6", features = ["sqlx-postgres", "postgres-array", "runtime-tokio-rustls"] }
sea-query = "0.27"
sea-orm = { version = "0.12.x", features = ["sqlx-postgres", "postgres-array", "runtime-tokio-rustls", "with-uuid"] }
serde.workspace = true
serde_derive.workspace = true
serde_json.workspace = true
sha-1 = "0.9"
sqlx = { version = "0.6", features = ["runtime-tokio-rustls", "postgres", "json", "time", "uuid", "any"] }
sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "json", "time", "uuid", "any"] }
time.workspace = true
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = "0.17"
@@ -59,6 +57,7 @@ toml.workspace = true
tracing = "0.1.34"
tracing-log = "0.1.3"
tracing-subscriber = { version = "0.3.11", features = ["env-filter", "json"] }
uuid.workspace = true
[dev-dependencies]
audio = { path = "../audio" }
@@ -87,9 +86,9 @@ env_logger.workspace = true
indoc.workspace = true
util = { path = "../util" }
lazy_static.workspace = true
sea-orm = { git = "https://github.com/zed-industries/sea-orm", rev = "18f4c691085712ad014a51792af75a9044bacee6", features = ["sqlx-sqlite"] }
sea-orm = { version = "0.12.x", features = ["sqlx-sqlite"] }
serde_json.workspace = true
sqlx = { version = "0.6", features = ["sqlite"] }
sqlx = { version = "0.7", features = ["sqlite"] }
unindent.workspace = true
[features]

View File

@@ -158,7 +158,8 @@ CREATE TABLE "room_participants" (
"initial_project_id" INTEGER,
"calling_user_id" INTEGER NOT NULL REFERENCES users (id),
"calling_connection_id" INTEGER NOT NULL,
"calling_connection_server_id" INTEGER REFERENCES servers (id) ON DELETE SET NULL
"calling_connection_server_id" INTEGER REFERENCES servers (id) ON DELETE SET NULL,
"participant_index" INTEGER
);
CREATE UNIQUE INDEX "index_room_participants_on_user_id" ON "room_participants" ("user_id");
CREATE INDEX "index_room_participants_on_room_id" ON "room_participants" ("room_id");
@@ -288,3 +289,24 @@ CREATE TABLE "user_features" (
CREATE UNIQUE INDEX "index_user_features_user_id_and_feature_id" ON "user_features" ("user_id", "feature_id");
CREATE INDEX "index_user_features_on_user_id" ON "user_features" ("user_id");
CREATE INDEX "index_user_features_on_feature_id" ON "user_features" ("feature_id");
CREATE TABLE "observed_buffer_edits" (
"user_id" INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
"buffer_id" INTEGER NOT NULL REFERENCES buffers (id) ON DELETE CASCADE,
"epoch" INTEGER NOT NULL,
"lamport_timestamp" INTEGER NOT NULL,
"replica_id" INTEGER NOT NULL,
PRIMARY KEY (user_id, buffer_id)
);
CREATE UNIQUE INDEX "index_observed_buffers_user_and_buffer_id" ON "observed_buffer_edits" ("user_id", "buffer_id");
CREATE TABLE IF NOT EXISTS "observed_channel_messages" (
"user_id" INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
"channel_id" INTEGER NOT NULL REFERENCES channels (id) ON DELETE CASCADE,
"channel_message_id" INTEGER NOT NULL,
PRIMARY KEY (user_id, channel_id)
);
CREATE UNIQUE INDEX "index_observed_channel_messages_user_and_channel_id" ON "observed_channel_messages" ("user_id", "channel_id");

View File

@@ -0,0 +1,19 @@
CREATE TABLE IF NOT EXISTS "observed_buffer_edits" (
"user_id" INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
"buffer_id" INTEGER NOT NULL REFERENCES buffers (id) ON DELETE CASCADE,
"epoch" INTEGER NOT NULL,
"lamport_timestamp" INTEGER NOT NULL,
"replica_id" INTEGER NOT NULL,
PRIMARY KEY (user_id, buffer_id)
);
CREATE UNIQUE INDEX "index_observed_buffer_user_and_buffer_id" ON "observed_buffer_edits" ("user_id", "buffer_id");
CREATE TABLE IF NOT EXISTS "observed_channel_messages" (
"user_id" INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
"channel_id" INTEGER NOT NULL REFERENCES channels (id) ON DELETE CASCADE,
"channel_message_id" INTEGER NOT NULL,
PRIMARY KEY (user_id, channel_id)
);
CREATE UNIQUE INDEX "index_observed_channel_messages_user_and_channel_id" ON "observed_channel_messages" ("user_id", "channel_id");

View File

@@ -0,0 +1 @@
ALTER TABLE room_participants ADD COLUMN participant_index INTEGER;

View File

@@ -19,11 +19,12 @@ use rpc::{
ConnectionId,
};
use sea_orm::{
entity::prelude::*, ActiveValue, Condition, ConnectionTrait, DatabaseConnection,
DatabaseTransaction, DbErr, FromQueryResult, IntoActiveModel, IsolationLevel, JoinType,
QueryOrder, QuerySelect, Statement, TransactionTrait,
entity::prelude::*,
sea_query::{Alias, Expr, OnConflict, Query},
ActiveValue, Condition, ConnectionTrait, DatabaseConnection, DatabaseTransaction, DbErr,
FromQueryResult, IntoActiveModel, IsolationLevel, JoinType, QueryOrder, QuerySelect, Statement,
TransactionTrait,
};
use sea_query::{Alias, Expr, OnConflict, Query};
use serde::{Deserialize, Serialize};
use sqlx::{
migrate::{Migrate, Migration, MigrationSource},
@@ -62,6 +63,7 @@ pub struct Database {
// separate files in the `queries` folder.
impl Database {
pub async fn new(options: ConnectOptions, executor: Executor) -> Result<Self> {
sqlx::any::install_default_drivers();
Ok(Self {
options: options.clone(),
pool: sea_orm::Database::connect(options).await?,
@@ -119,7 +121,7 @@ impl Database {
Ok(new_migrations)
}
async fn transaction<F, Fut, T>(&self, f: F) -> Result<T>
pub async fn transaction<F, Fut, T>(&self, f: F) -> Result<T>
where
F: Send + Fn(TransactionHandle) -> Fut,
Fut: Send + Future<Output = Result<T>>,
@@ -321,7 +323,7 @@ fn is_serialization_error(error: &Error) -> bool {
}
}
struct TransactionHandle(Arc<Option<DatabaseTransaction>>);
pub struct TransactionHandle(Arc<Option<DatabaseTransaction>>);
impl Deref for TransactionHandle {
type Target = DatabaseTransaction;
@@ -437,6 +439,8 @@ pub struct ChannelsForUser {
pub channels: ChannelGraph,
pub channel_participants: HashMap<ChannelId, Vec<UserId>>,
pub channels_with_admin_privileges: HashSet<ChannelId>,
pub unseen_buffer_changes: Vec<proto::UnseenChannelBufferChange>,
pub channel_messages: Vec<proto::UnseenChannelMessage>,
}
#[derive(Debug)]
@@ -510,7 +514,7 @@ pub struct RefreshedRoom {
pub struct RefreshedChannelBuffer {
pub connection_ids: Vec<ConnectionId>,
pub removed_collaborators: Vec<proto::RemoveChannelBufferCollaborator>,
pub collaborators: Vec<proto::Collaborator>,
}
pub struct Project {

View File

@@ -1,6 +1,5 @@
use crate::Result;
use sea_orm::DbErr;
use sea_query::{Value, ValueTypeErr};
use sea_orm::{entity::prelude::*, DbErr};
use serde::{Deserialize, Serialize};
macro_rules! id_type {
@@ -17,6 +16,7 @@ macro_rules! id_type {
Hash,
Serialize,
Deserialize,
DeriveValueType,
)]
#[serde(transparent)]
pub struct $name(pub i32);
@@ -42,40 +42,6 @@ macro_rules! id_type {
}
}
impl From<$name> for sea_query::Value {
fn from(value: $name) -> Self {
sea_query::Value::Int(Some(value.0))
}
}
impl sea_orm::TryGetable for $name {
fn try_get(
res: &sea_orm::QueryResult,
pre: &str,
col: &str,
) -> Result<Self, sea_orm::TryGetError> {
Ok(Self(i32::try_get(res, pre, col)?))
}
}
impl sea_query::ValueType for $name {
fn try_from(v: Value) -> Result<Self, sea_query::ValueTypeErr> {
Ok(Self(value_to_integer(v)?))
}
fn type_name() -> String {
stringify!($name).into()
}
fn array_type() -> sea_query::ArrayType {
sea_query::ArrayType::Int
}
fn column_type() -> sea_query::ColumnType {
sea_query::ColumnType::Integer(None)
}
}
impl sea_orm::TryFromU64 for $name {
fn try_from_u64(n: u64) -> Result<Self, DbErr> {
Ok(Self(n.try_into().map_err(|_| {
@@ -88,7 +54,7 @@ macro_rules! id_type {
}
}
impl sea_query::Nullable for $name {
impl sea_orm::sea_query::Nullable for $name {
fn null() -> Value {
Value::Int(None)
}
@@ -96,20 +62,6 @@ macro_rules! id_type {
};
}
fn value_to_integer(v: Value) -> Result<i32, ValueTypeErr> {
match v {
Value::TinyInt(Some(int)) => int.try_into().map_err(|_| ValueTypeErr),
Value::SmallInt(Some(int)) => int.try_into().map_err(|_| ValueTypeErr),
Value::Int(Some(int)) => int.try_into().map_err(|_| ValueTypeErr),
Value::BigInt(Some(int)) => int.try_into().map_err(|_| ValueTypeErr),
Value::TinyUnsigned(Some(int)) => int.try_into().map_err(|_| ValueTypeErr),
Value::SmallUnsigned(Some(int)) => int.try_into().map_err(|_| ValueTypeErr),
Value::Unsigned(Some(int)) => int.try_into().map_err(|_| ValueTypeErr),
Value::BigUnsigned(Some(int)) => int.try_into().map_err(|_| ValueTypeErr),
_ => Err(ValueTypeErr),
}
}
id_type!(BufferId);
id_type!(AccessTokenId);
id_type!(ChannelChatParticipantId);

View File

@@ -2,6 +2,12 @@ use super::*;
use prost::Message;
use text::{EditOperation, UndoOperation};
pub struct LeftChannelBuffer {
pub channel_id: ChannelId,
pub collaborators: Vec<proto::Collaborator>,
pub connections: Vec<ConnectionId>,
}
impl Database {
pub async fn join_channel_buffer(
&self,
@@ -68,7 +74,32 @@ impl Database {
.await?;
collaborators.push(collaborator);
let (base_text, operations) = self.get_buffer_state(&buffer, &tx).await?;
let (base_text, operations, max_operation) =
self.get_buffer_state(&buffer, &tx).await?;
// Save the last observed operation
if let Some(op) = max_operation {
observed_buffer_edits::Entity::insert(observed_buffer_edits::ActiveModel {
user_id: ActiveValue::Set(user_id),
buffer_id: ActiveValue::Set(buffer.id),
epoch: ActiveValue::Set(op.epoch),
lamport_timestamp: ActiveValue::Set(op.lamport_timestamp),
replica_id: ActiveValue::Set(op.replica_id),
})
.on_conflict(
OnConflict::columns([
observed_buffer_edits::Column::UserId,
observed_buffer_edits::Column::BufferId,
])
.update_columns([
observed_buffer_edits::Column::Epoch,
observed_buffer_edits::Column::LamportTimestamp,
])
.to_owned(),
)
.exec(&*tx)
.await?;
}
Ok(proto::JoinChannelBufferResponse {
buffer_id: buffer.id.to_proto(),
@@ -204,23 +235,26 @@ impl Database {
server_id: ServerId,
) -> Result<RefreshedChannelBuffer> {
self.transaction(|tx| async move {
let collaborators = channel_buffer_collaborator::Entity::find()
let db_collaborators = channel_buffer_collaborator::Entity::find()
.filter(channel_buffer_collaborator::Column::ChannelId.eq(channel_id))
.all(&*tx)
.await?;
let mut connection_ids = Vec::new();
let mut removed_collaborators = Vec::new();
let mut collaborators = Vec::new();
let mut collaborator_ids_to_remove = Vec::new();
for collaborator in &collaborators {
if !collaborator.connection_lost && collaborator.connection_server_id == server_id {
connection_ids.push(collaborator.connection());
for db_collaborator in &db_collaborators {
if !db_collaborator.connection_lost
&& db_collaborator.connection_server_id == server_id
{
connection_ids.push(db_collaborator.connection());
collaborators.push(proto::Collaborator {
peer_id: Some(db_collaborator.connection().into()),
replica_id: db_collaborator.replica_id.0 as u32,
user_id: db_collaborator.user_id.to_proto(),
})
} else {
removed_collaborators.push(proto::RemoveChannelBufferCollaborator {
channel_id: channel_id.to_proto(),
peer_id: Some(collaborator.connection().into()),
});
collaborator_ids_to_remove.push(collaborator.id);
collaborator_ids_to_remove.push(db_collaborator.id);
}
}
@@ -231,7 +265,7 @@ impl Database {
Ok(RefreshedChannelBuffer {
connection_ids,
removed_collaborators,
collaborators,
})
})
.await
@@ -241,7 +275,7 @@ impl Database {
&self,
channel_id: ChannelId,
connection: ConnectionId,
) -> Result<Vec<ConnectionId>> {
) -> Result<LeftChannelBuffer> {
self.transaction(|tx| async move {
self.leave_channel_buffer_internal(channel_id, connection, &*tx)
.await
@@ -275,7 +309,7 @@ impl Database {
pub async fn leave_channel_buffers(
&self,
connection: ConnectionId,
) -> Result<Vec<(ChannelId, Vec<ConnectionId>)>> {
) -> Result<Vec<LeftChannelBuffer>> {
self.transaction(|tx| async move {
#[derive(Debug, Clone, Copy, EnumIter, DeriveColumn)]
enum QueryChannelIds {
@@ -294,10 +328,10 @@ impl Database {
let mut result = Vec::new();
for channel_id in channel_ids {
let collaborators = self
let left_channel_buffer = self
.leave_channel_buffer_internal(channel_id, connection, &*tx)
.await?;
result.push((channel_id, collaborators));
result.push(left_channel_buffer);
}
Ok(result)
@@ -310,7 +344,7 @@ impl Database {
channel_id: ChannelId,
connection: ConnectionId,
tx: &DatabaseTransaction,
) -> Result<Vec<ConnectionId>> {
) -> Result<LeftChannelBuffer> {
let result = channel_buffer_collaborator::Entity::delete_many()
.filter(
Condition::all()
@@ -327,6 +361,7 @@ impl Database {
Err(anyhow!("not a collaborator on this project"))?;
}
let mut collaborators = Vec::new();
let mut connections = Vec::new();
let mut rows = channel_buffer_collaborator::Entity::find()
.filter(
@@ -336,19 +371,26 @@ impl Database {
.await?;
while let Some(row) = rows.next().await {
let row = row?;
connections.push(ConnectionId {
id: row.connection_id as u32,
owner_id: row.connection_server_id.0 as u32,
let connection = row.connection();
connections.push(connection);
collaborators.push(proto::Collaborator {
peer_id: Some(connection.into()),
replica_id: row.replica_id.0 as u32,
user_id: row.user_id.to_proto(),
});
}
drop(rows);
if connections.is_empty() {
if collaborators.is_empty() {
self.snapshot_channel_buffer(channel_id, &tx).await?;
}
Ok(connections)
Ok(LeftChannelBuffer {
channel_id,
collaborators,
connections,
})
}
pub async fn get_channel_buffer_collaborators(
@@ -356,33 +398,46 @@ impl Database {
channel_id: ChannelId,
) -> Result<Vec<UserId>> {
self.transaction(|tx| async move {
#[derive(Debug, Clone, Copy, EnumIter, DeriveColumn)]
enum QueryUserIds {
UserId,
}
let users: Vec<UserId> = channel_buffer_collaborator::Entity::find()
.select_only()
.column(channel_buffer_collaborator::Column::UserId)
.filter(
Condition::all()
.add(channel_buffer_collaborator::Column::ChannelId.eq(channel_id)),
)
.into_values::<_, QueryUserIds>()
.all(&*tx)
.await?;
Ok(users)
self.get_channel_buffer_collaborators_internal(channel_id, &*tx)
.await
})
.await
}
async fn get_channel_buffer_collaborators_internal(
&self,
channel_id: ChannelId,
tx: &DatabaseTransaction,
) -> Result<Vec<UserId>> {
#[derive(Debug, Clone, Copy, EnumIter, DeriveColumn)]
enum QueryUserIds {
UserId,
}
let users: Vec<UserId> = channel_buffer_collaborator::Entity::find()
.select_only()
.column(channel_buffer_collaborator::Column::UserId)
.filter(
Condition::all().add(channel_buffer_collaborator::Column::ChannelId.eq(channel_id)),
)
.into_values::<_, QueryUserIds>()
.all(&*tx)
.await?;
Ok(users)
}
pub async fn update_channel_buffer(
&self,
channel_id: ChannelId,
user: UserId,
operations: &[proto::Operation],
) -> Result<Vec<ConnectionId>> {
) -> Result<(
Vec<ConnectionId>,
Vec<UserId>,
i32,
Vec<proto::VectorClockEntry>,
)> {
self.transaction(move |tx| async move {
self.check_user_is_channel_member(channel_id, user, &*tx)
.await?;
@@ -401,7 +456,38 @@ impl Database {
.iter()
.filter_map(|op| operation_to_storage(op, &buffer, serialization_version))
.collect::<Vec<_>>();
let mut channel_members;
let max_version;
if !operations.is_empty() {
let max_operation = operations
.iter()
.max_by_key(|op| (op.lamport_timestamp.as_ref(), op.replica_id.as_ref()))
.unwrap();
max_version = vec![proto::VectorClockEntry {
replica_id: *max_operation.replica_id.as_ref() as u32,
timestamp: *max_operation.lamport_timestamp.as_ref() as u32,
}];
// get current channel participants and save the max operation above
self.save_max_operation(
user,
buffer.id,
buffer.epoch,
*max_operation.replica_id.as_ref(),
*max_operation.lamport_timestamp.as_ref(),
&*tx,
)
.await?;
channel_members = self.get_channel_members_internal(channel_id, &*tx).await?;
let collaborators = self
.get_channel_buffer_collaborators_internal(channel_id, &*tx)
.await?;
channel_members.retain(|member| !collaborators.contains(member));
buffer_operation::Entity::insert_many(operations)
.on_conflict(
OnConflict::columns([
@@ -415,6 +501,9 @@ impl Database {
)
.exec(&*tx)
.await?;
} else {
channel_members = Vec::new();
max_version = Vec::new();
}
let mut connections = Vec::new();
@@ -433,11 +522,53 @@ impl Database {
});
}
Ok(connections)
Ok((connections, channel_members, buffer.epoch, max_version))
})
.await
}
async fn save_max_operation(
&self,
user_id: UserId,
buffer_id: BufferId,
epoch: i32,
replica_id: i32,
lamport_timestamp: i32,
tx: &DatabaseTransaction,
) -> Result<()> {
use observed_buffer_edits::Column;
observed_buffer_edits::Entity::insert(observed_buffer_edits::ActiveModel {
user_id: ActiveValue::Set(user_id),
buffer_id: ActiveValue::Set(buffer_id),
epoch: ActiveValue::Set(epoch),
replica_id: ActiveValue::Set(replica_id),
lamport_timestamp: ActiveValue::Set(lamport_timestamp),
})
.on_conflict(
OnConflict::columns([Column::UserId, Column::BufferId])
.update_columns([Column::Epoch, Column::LamportTimestamp, Column::ReplicaId])
.action_cond_where(
Condition::any().add(Column::Epoch.lt(epoch)).add(
Condition::all().add(Column::Epoch.eq(epoch)).add(
Condition::any()
.add(Column::LamportTimestamp.lt(lamport_timestamp))
.add(
Column::LamportTimestamp
.eq(lamport_timestamp)
.and(Column::ReplicaId.lt(replica_id)),
),
),
),
)
.to_owned(),
)
.exec_without_returning(tx)
.await?;
Ok(())
}
async fn get_buffer_operation_serialization_version(
&self,
buffer_id: BufferId,
@@ -455,7 +586,7 @@ impl Database {
.ok_or_else(|| anyhow!("missing buffer snapshot"))?)
}
async fn get_channel_buffer(
pub async fn get_channel_buffer(
&self,
channel_id: ChannelId,
tx: &DatabaseTransaction,
@@ -474,7 +605,11 @@ impl Database {
&self,
buffer: &buffer::Model,
tx: &DatabaseTransaction,
) -> Result<(String, Vec<proto::Operation>)> {
) -> Result<(
String,
Vec<proto::Operation>,
Option<buffer_operation::Model>,
)> {
let id = buffer.id;
let (base_text, version) = if buffer.epoch > 0 {
let snapshot = buffer_snapshot::Entity::find()
@@ -499,16 +634,28 @@ impl Database {
.eq(id)
.and(buffer_operation::Column::Epoch.eq(buffer.epoch)),
)
.order_by_asc(buffer_operation::Column::LamportTimestamp)
.order_by_asc(buffer_operation::Column::ReplicaId)
.stream(&*tx)
.await?;
let mut operations = Vec::new();
let mut last_row = None;
while let Some(row) = rows.next().await {
let row = row?;
last_row = Some(buffer_operation::Model {
buffer_id: row.buffer_id,
epoch: row.epoch,
lamport_timestamp: row.lamport_timestamp,
replica_id: row.lamport_timestamp,
value: Default::default(),
});
operations.push(proto::Operation {
variant: Some(operation_from_storage(row?, version)?),
})
variant: Some(operation_from_storage(row, version)?),
});
}
Ok((base_text, operations))
Ok((base_text, operations, last_row))
}
async fn snapshot_channel_buffer(
@@ -517,7 +664,7 @@ impl Database {
tx: &DatabaseTransaction,
) -> Result<()> {
let buffer = self.get_channel_buffer(channel_id, tx).await?;
let (base_text, operations) = self.get_buffer_state(&buffer, tx).await?;
let (base_text, operations, _) = self.get_buffer_state(&buffer, tx).await?;
if operations.is_empty() {
return Ok(());
}
@@ -550,6 +697,150 @@ impl Database {
Ok(())
}
pub async fn observe_buffer_version(
&self,
buffer_id: BufferId,
user_id: UserId,
epoch: i32,
version: &[proto::VectorClockEntry],
) -> Result<()> {
self.transaction(|tx| async move {
// For now, combine concurrent operations.
let Some(component) = version.iter().max_by_key(|version| version.timestamp) else {
return Ok(());
};
self.save_max_operation(
user_id,
buffer_id,
epoch,
component.replica_id as i32,
component.timestamp as i32,
&*tx,
)
.await?;
Ok(())
})
.await
}
pub async fn unseen_channel_buffer_changes(
&self,
user_id: UserId,
channel_ids: &[ChannelId],
tx: &DatabaseTransaction,
) -> Result<Vec<proto::UnseenChannelBufferChange>> {
#[derive(Debug, Clone, Copy, EnumIter, DeriveColumn)]
enum QueryIds {
ChannelId,
Id,
}
let mut channel_ids_by_buffer_id = HashMap::default();
let mut rows = buffer::Entity::find()
.filter(buffer::Column::ChannelId.is_in(channel_ids.iter().copied()))
.stream(&*tx)
.await?;
while let Some(row) = rows.next().await {
let row = row?;
channel_ids_by_buffer_id.insert(row.id, row.channel_id);
}
drop(rows);
let mut observed_edits_by_buffer_id = HashMap::default();
let mut rows = observed_buffer_edits::Entity::find()
.filter(observed_buffer_edits::Column::UserId.eq(user_id))
.filter(
observed_buffer_edits::Column::BufferId
.is_in(channel_ids_by_buffer_id.keys().copied()),
)
.stream(&*tx)
.await?;
while let Some(row) = rows.next().await {
let row = row?;
observed_edits_by_buffer_id.insert(row.buffer_id, row);
}
drop(rows);
let latest_operations = self
.get_latest_operations_for_buffers(channel_ids_by_buffer_id.keys().copied(), &*tx)
.await?;
let mut changes = Vec::default();
for latest in latest_operations {
if let Some(observed) = observed_edits_by_buffer_id.get(&latest.buffer_id) {
if (
observed.epoch,
observed.lamport_timestamp,
observed.replica_id,
) >= (latest.epoch, latest.lamport_timestamp, latest.replica_id)
{
continue;
}
}
if let Some(channel_id) = channel_ids_by_buffer_id.get(&latest.buffer_id) {
changes.push(proto::UnseenChannelBufferChange {
channel_id: channel_id.to_proto(),
epoch: latest.epoch as u64,
version: vec![proto::VectorClockEntry {
replica_id: latest.replica_id as u32,
timestamp: latest.lamport_timestamp as u32,
}],
});
}
}
Ok(changes)
}
pub async fn get_latest_operations_for_buffers(
&self,
buffer_ids: impl IntoIterator<Item = BufferId>,
tx: &DatabaseTransaction,
) -> Result<Vec<buffer_operation::Model>> {
let mut values = String::new();
for id in buffer_ids {
if !values.is_empty() {
values.push_str(", ");
}
write!(&mut values, "({})", id).unwrap();
}
if values.is_empty() {
return Ok(Vec::default());
}
let sql = format!(
r#"
SELECT
*
FROM
(
SELECT
*,
row_number() OVER (
PARTITION BY buffer_id
ORDER BY
epoch DESC,
lamport_timestamp DESC,
replica_id DESC
) as row_number
FROM buffer_operations
WHERE
buffer_id in ({values})
) AS last_operations
WHERE
row_number = 1
"#,
);
let stmt = Statement::from_string(self.pool.get_database_backend(), sql);
Ok(buffer_operation::Entity::find()
.from_raw_sql(stmt)
.all(&*tx)
.await?)
}
}
fn operation_to_storage(

View File

@@ -1,8 +1,7 @@
use super::*;
use rpc::proto::ChannelEdge;
use smallvec::SmallVec;
use super::*;
type ChannelDescendants = HashMap<ChannelId, SmallSet<ChannelId>>;
impl Database {
@@ -391,7 +390,8 @@ impl Database {
.all(&*tx)
.await?;
self.get_user_channels(channel_memberships, &tx).await
self.get_user_channels(user_id, channel_memberships, &tx)
.await
})
.await
}
@@ -414,13 +414,15 @@ impl Database {
.all(&*tx)
.await?;
self.get_user_channels(channel_membership, &tx).await
self.get_user_channels(user_id, channel_membership, &tx)
.await
})
.await
}
pub async fn get_user_channels(
&self,
user_id: UserId,
channel_memberships: Vec<channel_member::Model>,
tx: &DatabaseTransaction,
) -> Result<ChannelsForUser> {
@@ -460,10 +462,21 @@ impl Database {
}
}
let channel_ids = graph.channels.iter().map(|c| c.id).collect::<Vec<_>>();
let channel_buffer_changes = self
.unseen_channel_buffer_changes(user_id, &channel_ids, &*tx)
.await?;
let unseen_messages = self
.unseen_channel_messages(user_id, &channel_ids, &*tx)
.await?;
Ok(ChannelsForUser {
channels: graph,
channel_participants,
channels_with_admin_privileges,
unseen_buffer_changes: channel_buffer_changes,
channel_messages: unseen_messages,
})
}
@@ -645,7 +658,7 @@ impl Database {
) -> Result<Vec<ChannelId>> {
let paths = channel_path::Entity::find()
.filter(channel_path::Column::ChannelId.eq(channel_id))
.order_by(channel_path::Column::IdPath, sea_query::Order::Desc)
.order_by(channel_path::Column::IdPath, sea_orm::Order::Desc)
.all(tx)
.await?;
let mut channel_ids = Vec::new();

View File

@@ -18,12 +18,12 @@ impl Database {
let user_b_participant = Alias::new("user_b_participant");
let mut db_contacts = contact::Entity::find()
.column_as(
Expr::tbl(user_a_participant.clone(), room_participant::Column::Id)
Expr::col((user_a_participant.clone(), room_participant::Column::Id))
.is_not_null(),
"user_a_busy",
)
.column_as(
Expr::tbl(user_b_participant.clone(), room_participant::Column::Id)
Expr::col((user_b_participant.clone(), room_participant::Column::Id))
.is_not_null(),
"user_b_busy",
)

View File

@@ -89,6 +89,7 @@ impl Database {
let mut rows = channel_message::Entity::find()
.filter(condition)
.order_by_asc(channel_message::Column::Id)
.limit(count as u64)
.stream(&*tx)
.await?;
@@ -108,7 +109,7 @@ impl Database {
}),
});
}
drop(rows);
Ok(messages)
})
.await
@@ -121,7 +122,7 @@ impl Database {
body: &str,
timestamp: OffsetDateTime,
nonce: u128,
) -> Result<(MessageId, Vec<ConnectionId>)> {
) -> Result<(MessageId, Vec<ConnectionId>, Vec<UserId>)> {
self.transaction(|tx| async move {
let mut rows = channel_chat_participant::Entity::find()
.filter(channel_chat_participant::Column::ChannelId.eq(channel_id))
@@ -130,11 +131,13 @@ impl Database {
let mut is_participant = false;
let mut participant_connection_ids = Vec::new();
let mut participant_user_ids = Vec::new();
while let Some(row) = rows.next().await {
let row = row?;
if row.user_id == user_id {
is_participant = true;
}
participant_user_ids.push(row.user_id);
participant_connection_ids.push(row.connection());
}
drop(rows);
@@ -167,11 +170,141 @@ impl Database {
ConnectionId,
}
Ok((message.last_insert_id, participant_connection_ids))
// Observe this message for the sender
self.observe_channel_message_internal(
channel_id,
user_id,
message.last_insert_id,
&*tx,
)
.await?;
let mut channel_members = self.get_channel_members_internal(channel_id, &*tx).await?;
channel_members.retain(|member| !participant_user_ids.contains(member));
Ok((
message.last_insert_id,
participant_connection_ids,
channel_members,
))
})
.await
}
pub async fn observe_channel_message(
&self,
channel_id: ChannelId,
user_id: UserId,
message_id: MessageId,
) -> Result<()> {
self.transaction(|tx| async move {
self.observe_channel_message_internal(channel_id, user_id, message_id, &*tx)
.await?;
Ok(())
})
.await
}
async fn observe_channel_message_internal(
&self,
channel_id: ChannelId,
user_id: UserId,
message_id: MessageId,
tx: &DatabaseTransaction,
) -> Result<()> {
observed_channel_messages::Entity::insert(observed_channel_messages::ActiveModel {
user_id: ActiveValue::Set(user_id),
channel_id: ActiveValue::Set(channel_id),
channel_message_id: ActiveValue::Set(message_id),
})
.on_conflict(
OnConflict::columns([
observed_channel_messages::Column::ChannelId,
observed_channel_messages::Column::UserId,
])
.update_column(observed_channel_messages::Column::ChannelMessageId)
.action_cond_where(observed_channel_messages::Column::ChannelMessageId.lt(message_id))
.to_owned(),
)
// TODO: Try to upgrade SeaORM so we don't have to do this hack around their bug
.exec_without_returning(&*tx)
.await?;
Ok(())
}
pub async fn unseen_channel_messages(
&self,
user_id: UserId,
channel_ids: &[ChannelId],
tx: &DatabaseTransaction,
) -> Result<Vec<proto::UnseenChannelMessage>> {
let mut observed_messages_by_channel_id = HashMap::default();
let mut rows = observed_channel_messages::Entity::find()
.filter(observed_channel_messages::Column::UserId.eq(user_id))
.filter(observed_channel_messages::Column::ChannelId.is_in(channel_ids.iter().copied()))
.stream(&*tx)
.await?;
while let Some(row) = rows.next().await {
let row = row?;
observed_messages_by_channel_id.insert(row.channel_id, row);
}
drop(rows);
let mut values = String::new();
for id in channel_ids {
if !values.is_empty() {
values.push_str(", ");
}
write!(&mut values, "({})", id).unwrap();
}
if values.is_empty() {
return Ok(Default::default());
}
let sql = format!(
r#"
SELECT
*
FROM (
SELECT
*,
row_number() OVER (
PARTITION BY channel_id
ORDER BY id DESC
) as row_number
FROM channel_messages
WHERE
channel_id in ({values})
) AS messages
WHERE
row_number = 1
"#,
);
let stmt = Statement::from_string(self.pool.get_database_backend(), sql);
let last_messages = channel_message::Model::find_by_statement(stmt)
.all(&*tx)
.await?;
let mut changes = Vec::new();
for last_message in last_messages {
if let Some(observed_message) =
observed_messages_by_channel_id.get(&last_message.channel_id)
{
if observed_message.channel_message_id == last_message.id {
continue;
}
}
changes.push(proto::UnseenChannelMessage {
channel_id: last_message.channel_id.to_proto(),
message_id: last_message.id.to_proto(),
});
}
Ok(changes)
}
pub async fn remove_channel_message(
&self,
channel_id: ChannelId,

View File

@@ -738,7 +738,7 @@ impl Database {
Condition::any()
.add(
Condition::all()
.add(follower::Column::ProjectId.eq(project_id))
.add(follower::Column::ProjectId.eq(Some(project_id)))
.add(
follower::Column::LeaderConnectionServerId
.eq(connection.owner_id),
@@ -747,7 +747,7 @@ impl Database {
)
.add(
Condition::all()
.add(follower::Column::ProjectId.eq(project_id))
.add(follower::Column::ProjectId.eq(Some(project_id)))
.add(
follower::Column::FollowerConnectionServerId
.eq(connection.owner_id),
@@ -862,13 +862,46 @@ impl Database {
.await
}
pub async fn check_room_participants(
&self,
room_id: RoomId,
leader_id: ConnectionId,
follower_id: ConnectionId,
) -> Result<()> {
self.transaction(|tx| async move {
use room_participant::Column;
let count = room_participant::Entity::find()
.filter(
Condition::all().add(Column::RoomId.eq(room_id)).add(
Condition::any()
.add(Column::AnsweringConnectionId.eq(leader_id.id as i32).and(
Column::AnsweringConnectionServerId.eq(leader_id.owner_id as i32),
))
.add(Column::AnsweringConnectionId.eq(follower_id.id as i32).and(
Column::AnsweringConnectionServerId.eq(follower_id.owner_id as i32),
)),
),
)
.count(&*tx)
.await?;
if count < 2 {
Err(anyhow!("not room participants"))?;
}
Ok(())
})
.await
}
pub async fn follow(
&self,
room_id: RoomId,
project_id: ProjectId,
leader_connection: ConnectionId,
follower_connection: ConnectionId,
) -> Result<RoomGuard<proto::Room>> {
let room_id = self.room_id_for_project(project_id).await?;
self.room_transaction(room_id, |tx| async move {
follower::ActiveModel {
room_id: ActiveValue::set(room_id),
@@ -894,15 +927,16 @@ impl Database {
pub async fn unfollow(
&self,
room_id: RoomId,
project_id: ProjectId,
leader_connection: ConnectionId,
follower_connection: ConnectionId,
) -> Result<RoomGuard<proto::Room>> {
let room_id = self.room_id_for_project(project_id).await?;
self.room_transaction(room_id, |tx| async move {
follower::Entity::delete_many()
.filter(
Condition::all()
.add(follower::Column::RoomId.eq(room_id))
.add(follower::Column::ProjectId.eq(project_id))
.add(
follower::Column::LeaderConnectionServerId

View File

@@ -128,6 +128,7 @@ impl Database {
calling_connection_server_id: ActiveValue::set(Some(ServerId(
connection.owner_id as i32,
))),
participant_index: ActiveValue::set(Some(0)),
..Default::default()
}
.insert(&*tx)
@@ -152,6 +153,7 @@ impl Database {
room_id: ActiveValue::set(room_id),
user_id: ActiveValue::set(called_user_id),
answering_connection_lost: ActiveValue::set(false),
participant_index: ActiveValue::NotSet,
calling_user_id: ActiveValue::set(calling_user_id),
calling_connection_id: ActiveValue::set(calling_connection.id as i32),
calling_connection_server_id: ActiveValue::set(Some(ServerId(
@@ -283,6 +285,26 @@ impl Database {
.await?
.ok_or_else(|| anyhow!("no such room"))?;
#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
enum QueryParticipantIndices {
ParticipantIndex,
}
let existing_participant_indices: Vec<i32> = room_participant::Entity::find()
.filter(
room_participant::Column::RoomId
.eq(room_id)
.and(room_participant::Column::ParticipantIndex.is_not_null()),
)
.select_only()
.column(room_participant::Column::ParticipantIndex)
.into_values::<_, QueryParticipantIndices>()
.all(&*tx)
.await?;
let mut participant_index = 0;
while existing_participant_indices.contains(&participant_index) {
participant_index += 1;
}
if let Some(channel_id) = channel_id {
self.check_user_is_channel_member(channel_id, user_id, &*tx)
.await?;
@@ -300,6 +322,7 @@ impl Database {
calling_connection_server_id: ActiveValue::set(Some(ServerId(
connection.owner_id as i32,
))),
participant_index: ActiveValue::Set(Some(participant_index)),
..Default::default()
}])
.on_conflict(
@@ -308,6 +331,7 @@ impl Database {
room_participant::Column::AnsweringConnectionId,
room_participant::Column::AnsweringConnectionServerId,
room_participant::Column::AnsweringConnectionLost,
room_participant::Column::ParticipantIndex,
])
.to_owned(),
)
@@ -322,6 +346,7 @@ impl Database {
.add(room_participant::Column::AnsweringConnectionId.is_null()),
)
.set(room_participant::ActiveModel {
participant_index: ActiveValue::Set(Some(participant_index)),
answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
answering_connection_server_id: ActiveValue::set(Some(ServerId(
connection.owner_id as i32,
@@ -960,6 +985,39 @@ impl Database {
Ok(room)
}
pub async fn room_connection_ids(
&self,
room_id: RoomId,
connection_id: ConnectionId,
) -> Result<RoomGuard<HashSet<ConnectionId>>> {
self.room_transaction(room_id, |tx| async move {
let mut participants = room_participant::Entity::find()
.filter(room_participant::Column::RoomId.eq(room_id))
.stream(&*tx)
.await?;
let mut is_participant = false;
let mut connection_ids = HashSet::default();
while let Some(participant) = participants.next().await {
let participant = participant?;
if let Some(answering_connection) = participant.answering_connection() {
if answering_connection == connection_id {
is_participant = true;
} else {
connection_ids.insert(answering_connection);
}
}
}
if !is_participant {
Err(anyhow!("not a room participant"))?;
}
Ok(connection_ids)
})
.await
}
async fn get_channel_room(
&self,
room_id: RoomId,
@@ -978,10 +1036,15 @@ impl Database {
let mut pending_participants = Vec::new();
while let Some(db_participant) = db_participants.next().await {
let db_participant = db_participant?;
if let Some((answering_connection_id, answering_connection_server_id)) = db_participant
.answering_connection_id
.zip(db_participant.answering_connection_server_id)
{
if let (
Some(answering_connection_id),
Some(answering_connection_server_id),
Some(participant_index),
) = (
db_participant.answering_connection_id,
db_participant.answering_connection_server_id,
db_participant.participant_index,
) {
let location = match (
db_participant.location_kind,
db_participant.location_project_id,
@@ -1012,6 +1075,7 @@ impl Database {
peer_id: Some(answering_connection.into()),
projects: Default::default(),
location: Some(proto::ParticipantLocation { variant: location }),
participant_index: participant_index as u32,
},
);
} else {

View File

@@ -184,7 +184,7 @@ impl Database {
Ok(user::Entity::find()
.from_raw_sql(Statement::from_sql_and_values(
self.pool.get_database_backend(),
query.into(),
query,
vec![like_string.into(), name_query.into(), limit.into()],
))
.all(&*tx)

View File

@@ -12,6 +12,8 @@ pub mod contact;
pub mod feature_flag;
pub mod follower;
pub mod language_server;
pub mod observed_buffer_edits;
pub mod observed_channel_messages;
pub mod project;
pub mod project_collaborator;
pub mod room;

View File

@@ -0,0 +1,43 @@
use crate::db::{BufferId, UserId};
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "observed_buffer_edits")]
pub struct Model {
#[sea_orm(primary_key)]
pub user_id: UserId,
pub buffer_id: BufferId,
pub epoch: i32,
pub lamport_timestamp: i32,
pub replica_id: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::buffer::Entity",
from = "Column::BufferId",
to = "super::buffer::Column::Id"
)]
Buffer,
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::UserId",
to = "super::user::Column::Id"
)]
User,
}
impl Related<super::buffer::Entity> for Entity {
fn to() -> RelationDef {
Relation::Buffer.def()
}
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,41 @@
use crate::db::{ChannelId, MessageId, UserId};
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "observed_channel_messages")]
pub struct Model {
#[sea_orm(primary_key)]
pub user_id: UserId,
pub channel_id: ChannelId,
pub channel_message_id: MessageId,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::channel::Entity",
from = "Column::ChannelId",
to = "super::channel::Column::Id"
)]
Channel,
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::UserId",
to = "super::user::Column::Id"
)]
User,
}
impl Related<super::channel::Entity> for Entity {
fn to() -> RelationDef {
Relation::Channel.def()
}
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -1,4 +1,5 @@
use crate::db::{ProjectId, RoomId, RoomParticipantId, ServerId, UserId};
use rpc::ConnectionId;
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
@@ -17,6 +18,16 @@ pub struct Model {
pub calling_user_id: UserId,
pub calling_connection_id: i32,
pub calling_connection_server_id: Option<ServerId>,
pub participant_index: Option<i32>,
}
impl Model {
pub fn answering_connection(&self) -> Option<ConnectionId> {
Some(ConnectionId {
owner_id: self.answering_connection_server_id?.0 as u32,
id: self.answering_connection_id? as u32,
})
}
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]

View File

@@ -39,7 +39,7 @@ impl TestDb {
db.pool
.execute(sea_orm::Statement::from_string(
db.pool.get_database_backend(),
sql.into(),
sql,
))
.await
.unwrap();
@@ -134,7 +134,7 @@ impl Drop for TestDb {
db.pool
.execute(sea_orm::Statement::from_string(
db.pool.get_database_backend(),
query.into(),
query,
))
.await
.log_err();

View File

@@ -1,6 +1,6 @@
use super::*;
use crate::test_both_dbs;
use language::proto;
use language::proto::{self, serialize_version};
use text::Buffer;
test_both_dbs!(
@@ -134,12 +134,12 @@ async fn test_channel_buffers(db: &Arc<Database>) {
let zed_collaborats = db.get_channel_buffer_collaborators(zed_id).await.unwrap();
assert_eq!(zed_collaborats, &[a_id, b_id]);
let collaborators = db
let left_buffer = db
.leave_channel_buffer(zed_id, connection_id_b)
.await
.unwrap();
assert_eq!(collaborators, &[connection_id_a],);
assert_eq!(left_buffer.connections, &[connection_id_a],);
let cargo_id = db.create_root_channel("cargo", "2", a_id).await.unwrap();
let _ = db
@@ -163,3 +163,349 @@ async fn test_channel_buffers(db: &Arc<Database>) {
assert_eq!(buffer_response_b.base_text, "hello, cruel world");
assert_eq!(buffer_response_b.operations, &[]);
}
test_both_dbs!(
test_channel_buffers_last_operations,
test_channel_buffers_last_operations_postgres,
test_channel_buffers_last_operations_sqlite
);
async fn test_channel_buffers_last_operations(db: &Database) {
let user_id = db
.create_user(
"user_a@example.com",
false,
NewUserParams {
github_login: "user_a".into(),
github_user_id: 101,
invite_count: 0,
},
)
.await
.unwrap()
.user_id;
let observer_id = db
.create_user(
"user_b@example.com",
false,
NewUserParams {
github_login: "user_b".into(),
github_user_id: 102,
invite_count: 0,
},
)
.await
.unwrap()
.user_id;
let owner_id = db.create_server("production").await.unwrap().0 as u32;
let connection_id = ConnectionId {
owner_id,
id: user_id.0 as u32,
};
let mut buffers = Vec::new();
let mut text_buffers = Vec::new();
for i in 0..3 {
let channel = db
.create_root_channel(&format!("channel-{i}"), &format!("room-{i}"), user_id)
.await
.unwrap();
db.invite_channel_member(channel, observer_id, user_id, false)
.await
.unwrap();
db.respond_to_channel_invite(channel, observer_id, true)
.await
.unwrap();
db.join_channel_buffer(channel, user_id, connection_id)
.await
.unwrap();
buffers.push(
db.transaction(|tx| async move { db.get_channel_buffer(channel, &*tx).await })
.await
.unwrap(),
);
text_buffers.push(Buffer::new(0, 0, "".to_string()));
}
let operations = db
.transaction(|tx| {
let buffers = &buffers;
async move {
db.get_latest_operations_for_buffers([buffers[0].id, buffers[2].id], &*tx)
.await
}
})
.await
.unwrap();
assert!(operations.is_empty());
update_buffer(
buffers[0].channel_id,
user_id,
db,
vec![
text_buffers[0].edit([(0..0, "a")]),
text_buffers[0].edit([(0..0, "b")]),
text_buffers[0].edit([(0..0, "c")]),
],
)
.await;
update_buffer(
buffers[1].channel_id,
user_id,
db,
vec![
text_buffers[1].edit([(0..0, "d")]),
text_buffers[1].edit([(1..1, "e")]),
text_buffers[1].edit([(2..2, "f")]),
],
)
.await;
// cause buffer 1's epoch to increment.
db.leave_channel_buffer(buffers[1].channel_id, connection_id)
.await
.unwrap();
db.join_channel_buffer(buffers[1].channel_id, user_id, connection_id)
.await
.unwrap();
text_buffers[1] = Buffer::new(1, 0, "def".to_string());
update_buffer(
buffers[1].channel_id,
user_id,
db,
vec![
text_buffers[1].edit([(0..0, "g")]),
text_buffers[1].edit([(0..0, "h")]),
],
)
.await;
update_buffer(
buffers[2].channel_id,
user_id,
db,
vec![text_buffers[2].edit([(0..0, "i")])],
)
.await;
let operations = db
.transaction(|tx| {
let buffers = &buffers;
async move {
db.get_latest_operations_for_buffers([buffers[1].id, buffers[2].id], &*tx)
.await
}
})
.await
.unwrap();
assert_operations(
&operations,
&[
(buffers[1].id, 1, &text_buffers[1]),
(buffers[2].id, 0, &text_buffers[2]),
],
);
let operations = db
.transaction(|tx| {
let buffers = &buffers;
async move {
db.get_latest_operations_for_buffers([buffers[0].id, buffers[1].id], &*tx)
.await
}
})
.await
.unwrap();
assert_operations(
&operations,
&[
(buffers[0].id, 0, &text_buffers[0]),
(buffers[1].id, 1, &text_buffers[1]),
],
);
let buffer_changes = db
.transaction(|tx| {
let buffers = &buffers;
async move {
db.unseen_channel_buffer_changes(
observer_id,
&[
buffers[0].channel_id,
buffers[1].channel_id,
buffers[2].channel_id,
],
&*tx,
)
.await
}
})
.await
.unwrap();
pretty_assertions::assert_eq!(
buffer_changes,
[
rpc::proto::UnseenChannelBufferChange {
channel_id: buffers[0].channel_id.to_proto(),
epoch: 0,
version: serialize_version(&text_buffers[0].version()),
},
rpc::proto::UnseenChannelBufferChange {
channel_id: buffers[1].channel_id.to_proto(),
epoch: 1,
version: serialize_version(&text_buffers[1].version())
.into_iter()
.filter(|vector| vector.replica_id
== buffer_changes[1].version.first().unwrap().replica_id)
.collect::<Vec<_>>(),
},
rpc::proto::UnseenChannelBufferChange {
channel_id: buffers[2].channel_id.to_proto(),
epoch: 0,
version: serialize_version(&text_buffers[2].version()),
},
]
);
db.observe_buffer_version(
buffers[1].id,
observer_id,
1,
serialize_version(&text_buffers[1].version()).as_slice(),
)
.await
.unwrap();
let buffer_changes = db
.transaction(|tx| {
let buffers = &buffers;
async move {
db.unseen_channel_buffer_changes(
observer_id,
&[
buffers[0].channel_id,
buffers[1].channel_id,
buffers[2].channel_id,
],
&*tx,
)
.await
}
})
.await
.unwrap();
assert_eq!(
buffer_changes,
[
rpc::proto::UnseenChannelBufferChange {
channel_id: buffers[0].channel_id.to_proto(),
epoch: 0,
version: serialize_version(&text_buffers[0].version()),
},
rpc::proto::UnseenChannelBufferChange {
channel_id: buffers[2].channel_id.to_proto(),
epoch: 0,
version: serialize_version(&text_buffers[2].version()),
},
]
);
// Observe an earlier version of the buffer.
db.observe_buffer_version(
buffers[1].id,
observer_id,
1,
&[rpc::proto::VectorClockEntry {
replica_id: 0,
timestamp: 0,
}],
)
.await
.unwrap();
let buffer_changes = db
.transaction(|tx| {
let buffers = &buffers;
async move {
db.unseen_channel_buffer_changes(
observer_id,
&[
buffers[0].channel_id,
buffers[1].channel_id,
buffers[2].channel_id,
],
&*tx,
)
.await
}
})
.await
.unwrap();
assert_eq!(
buffer_changes,
[
rpc::proto::UnseenChannelBufferChange {
channel_id: buffers[0].channel_id.to_proto(),
epoch: 0,
version: serialize_version(&text_buffers[0].version()),
},
rpc::proto::UnseenChannelBufferChange {
channel_id: buffers[2].channel_id.to_proto(),
epoch: 0,
version: serialize_version(&text_buffers[2].version()),
},
]
);
}
async fn update_buffer(
channel_id: ChannelId,
user_id: UserId,
db: &Database,
operations: Vec<text::Operation>,
) {
let operations = operations
.into_iter()
.map(|op| proto::serialize_operation(&language::Operation::Buffer(op)))
.collect::<Vec<_>>();
db.update_channel_buffer(channel_id, user_id, &operations)
.await
.unwrap();
}
fn assert_operations(
operations: &[buffer_operation::Model],
expected: &[(BufferId, i32, &text::Buffer)],
) {
let actual = operations
.iter()
.map(|op| buffer_operation::Model {
buffer_id: op.buffer_id,
epoch: op.epoch,
lamport_timestamp: op.lamport_timestamp,
replica_id: op.replica_id,
value: vec![],
})
.collect::<Vec<_>>();
let expected = expected
.iter()
.map(|(buffer_id, epoch, buffer)| buffer_operation::Model {
buffer_id: *buffer_id,
epoch: *epoch,
lamport_timestamp: buffer.lamport_clock.value as i32 - 1,
replica_id: buffer.replica_id() as i32,
value: vec![],
})
.collect::<Vec<_>>();
assert_eq!(actual, expected, "unexpected operations")
}

View File

@@ -57,3 +57,188 @@ async fn test_channel_message_nonces(db: &Arc<Database>) {
assert_eq!(msg1_id, msg3_id);
assert_eq!(msg2_id, msg4_id);
}
test_both_dbs!(
test_channel_message_new_notification,
test_channel_message_new_notification_postgres,
test_channel_message_new_notification_sqlite
);
async fn test_channel_message_new_notification(db: &Arc<Database>) {
let user = db
.create_user(
"user_a@example.com",
false,
NewUserParams {
github_login: "user_a".into(),
github_user_id: 1,
invite_count: 0,
},
)
.await
.unwrap()
.user_id;
let observer = db
.create_user(
"user_b@example.com",
false,
NewUserParams {
github_login: "user_b".into(),
github_user_id: 1,
invite_count: 0,
},
)
.await
.unwrap()
.user_id;
let channel_1 = db
.create_channel("channel", None, "room", user)
.await
.unwrap();
let channel_2 = db
.create_channel("channel-2", None, "room", user)
.await
.unwrap();
db.invite_channel_member(channel_1, observer, user, false)
.await
.unwrap();
db.respond_to_channel_invite(channel_1, observer, true)
.await
.unwrap();
db.invite_channel_member(channel_2, observer, user, false)
.await
.unwrap();
db.respond_to_channel_invite(channel_2, observer, true)
.await
.unwrap();
let owner_id = db.create_server("test").await.unwrap().0 as u32;
let user_connection_id = rpc::ConnectionId { owner_id, id: 0 };
db.join_channel_chat(channel_1, user_connection_id, user)
.await
.unwrap();
let _ = db
.create_channel_message(channel_1, user, "1_1", OffsetDateTime::now_utc(), 1)
.await
.unwrap();
let (second_message, _, _) = db
.create_channel_message(channel_1, user, "1_2", OffsetDateTime::now_utc(), 2)
.await
.unwrap();
let (third_message, _, _) = db
.create_channel_message(channel_1, user, "1_3", OffsetDateTime::now_utc(), 3)
.await
.unwrap();
db.join_channel_chat(channel_2, user_connection_id, user)
.await
.unwrap();
let (fourth_message, _, _) = db
.create_channel_message(channel_2, user, "2_1", OffsetDateTime::now_utc(), 4)
.await
.unwrap();
// Check that observer has new messages
let unseen_messages = db
.transaction(|tx| async move {
db.unseen_channel_messages(observer, &[channel_1, channel_2], &*tx)
.await
})
.await
.unwrap();
assert_eq!(
unseen_messages,
[
rpc::proto::UnseenChannelMessage {
channel_id: channel_1.to_proto(),
message_id: third_message.to_proto(),
},
rpc::proto::UnseenChannelMessage {
channel_id: channel_2.to_proto(),
message_id: fourth_message.to_proto(),
},
]
);
// Observe the second message
db.observe_channel_message(channel_1, observer, second_message)
.await
.unwrap();
// Make sure the observer still has a new message
let unseen_messages = db
.transaction(|tx| async move {
db.unseen_channel_messages(observer, &[channel_1, channel_2], &*tx)
.await
})
.await
.unwrap();
assert_eq!(
unseen_messages,
[
rpc::proto::UnseenChannelMessage {
channel_id: channel_1.to_proto(),
message_id: third_message.to_proto(),
},
rpc::proto::UnseenChannelMessage {
channel_id: channel_2.to_proto(),
message_id: fourth_message.to_proto(),
},
]
);
// Observe the third message,
db.observe_channel_message(channel_1, observer, third_message)
.await
.unwrap();
// Make sure the observer does not have a new method
let unseen_messages = db
.transaction(|tx| async move {
db.unseen_channel_messages(observer, &[channel_1, channel_2], &*tx)
.await
})
.await
.unwrap();
assert_eq!(
unseen_messages,
[rpc::proto::UnseenChannelMessage {
channel_id: channel_2.to_proto(),
message_id: fourth_message.to_proto(),
}]
);
// Observe the second message again, should not regress our observed state
db.observe_channel_message(channel_1, observer, second_message)
.await
.unwrap();
// Make sure the observer does not have a new message
let unseen_messages = db
.transaction(|tx| async move {
db.unseen_channel_messages(observer, &[channel_1, channel_2], &*tx)
.await
})
.await
.unwrap();
assert_eq!(
unseen_messages,
[rpc::proto::UnseenChannelMessage {
channel_id: channel_2.to_proto(),
message_id: fourth_message.to_proto(),
}]
);
}

View File

@@ -3,8 +3,8 @@ mod connection_pool;
use crate::{
auth,
db::{
self, ChannelId, ChannelsForUser, Database, MessageId, ProjectId, RoomId, ServerId, User,
UserId,
self, BufferId, ChannelId, ChannelsForUser, Database, MessageId, ProjectId, RoomId,
ServerId, User, UserId,
},
executor::Executor,
AppState, Result,
@@ -38,8 +38,8 @@ use lazy_static::lazy_static;
use prometheus::{register_int_gauge, IntGauge};
use rpc::{
proto::{
self, Ack, AddChannelBufferCollaborator, AnyTypedEnvelope, ChannelEdge, EntityMessage,
EnvelopedMessage, LiveKitConnectionInfo, RequestMessage,
self, Ack, AnyTypedEnvelope, ChannelEdge, EntityMessage, EnvelopedMessage,
LiveKitConnectionInfo, RequestMessage, UpdateChannelBufferCollaborators,
},
Connection, ConnectionId, Peer, Receipt, TypedEnvelope,
};
@@ -274,7 +274,9 @@ impl Server {
.add_message_handler(unfollow)
.add_message_handler(update_followers)
.add_message_handler(update_diff_base)
.add_request_handler(get_private_user_info);
.add_request_handler(get_private_user_info)
.add_message_handler(acknowledge_channel_message)
.add_message_handler(acknowledge_buffer_version);
Arc::new(server)
}
@@ -313,9 +315,16 @@ impl Server {
.trace_err()
{
for connection_id in refreshed_channel_buffer.connection_ids {
for message in &refreshed_channel_buffer.removed_collaborators {
peer.send(connection_id, message.clone()).trace_err();
}
peer.send(
connection_id,
proto::UpdateChannelBufferCollaborators {
channel_id: channel_id.to_proto(),
collaborators: refreshed_channel_buffer
.collaborators
.clone(),
},
)
.trace_err();
}
}
}
@@ -1883,94 +1892,94 @@ async fn follow(
response: Response<proto::Follow>,
session: Session,
) -> Result<()> {
let project_id = ProjectId::from_proto(request.project_id);
let room_id = RoomId::from_proto(request.room_id);
let project_id = request.project_id.map(ProjectId::from_proto);
let leader_id = request
.leader_id
.ok_or_else(|| anyhow!("invalid leader id"))?
.into();
let follower_id = session.connection_id;
{
let project_connection_ids = session
.db()
.await
.project_connection_ids(project_id, session.connection_id)
.await?;
session
.db()
.await
.check_room_participants(room_id, leader_id, session.connection_id)
.await?;
if !project_connection_ids.contains(&leader_id) {
Err(anyhow!("no such peer"))?;
}
}
let mut response_payload = session
let response_payload = session
.peer
.forward_request(session.connection_id, leader_id, request)
.await?;
response_payload
.views
.retain(|view| view.leader_id != Some(follower_id.into()));
response.send(response_payload)?;
let room = session
.db()
.await
.follow(project_id, leader_id, follower_id)
.await?;
room_updated(&room, &session.peer);
if let Some(project_id) = project_id {
let room = session
.db()
.await
.follow(room_id, project_id, leader_id, follower_id)
.await?;
room_updated(&room, &session.peer);
}
Ok(())
}
async fn unfollow(request: proto::Unfollow, session: Session) -> Result<()> {
let project_id = ProjectId::from_proto(request.project_id);
let room_id = RoomId::from_proto(request.room_id);
let project_id = request.project_id.map(ProjectId::from_proto);
let leader_id = request
.leader_id
.ok_or_else(|| anyhow!("invalid leader id"))?
.into();
let follower_id = session.connection_id;
if !session
session
.db()
.await
.project_connection_ids(project_id, session.connection_id)
.await?
.contains(&leader_id)
{
Err(anyhow!("no such peer"))?;
}
.check_room_participants(room_id, leader_id, session.connection_id)
.await?;
session
.peer
.forward_send(session.connection_id, leader_id, request)?;
let room = session
.db()
.await
.unfollow(project_id, leader_id, follower_id)
.await?;
room_updated(&room, &session.peer);
if let Some(project_id) = project_id {
let room = session
.db()
.await
.unfollow(room_id, project_id, leader_id, follower_id)
.await?;
room_updated(&room, &session.peer);
}
Ok(())
}
async fn update_followers(request: proto::UpdateFollowers, session: Session) -> Result<()> {
let project_id = ProjectId::from_proto(request.project_id);
let project_connection_ids = session
.db
.lock()
.await
.project_connection_ids(project_id, session.connection_id)
.await?;
let room_id = RoomId::from_proto(request.room_id);
let database = session.db.lock().await;
let leader_id = request.variant.as_ref().and_then(|variant| match variant {
proto::update_followers::Variant::CreateView(payload) => payload.leader_id,
let connection_ids = if let Some(project_id) = request.project_id {
let project_id = ProjectId::from_proto(project_id);
database
.project_connection_ids(project_id, session.connection_id)
.await?
} else {
database
.room_connection_ids(room_id, session.connection_id)
.await?
};
// For now, don't send view update messages back to that view's current leader.
let connection_id_to_omit = request.variant.as_ref().and_then(|variant| match variant {
proto::update_followers::Variant::UpdateView(payload) => payload.leader_id,
proto::update_followers::Variant::UpdateActiveView(payload) => payload.leader_id,
_ => None,
});
for follower_peer_id in request.follower_ids.iter().copied() {
let follower_connection_id = follower_peer_id.into();
if project_connection_ids.contains(&follower_connection_id)
&& Some(follower_peer_id) != leader_id
if Some(follower_peer_id) != connection_id_to_omit
&& connection_ids.contains(&follower_connection_id)
{
session.peer.forward_send(
session.connection_id,
@@ -2561,6 +2570,8 @@ async fn respond_to_channel_invite(
name: channel.name,
}),
);
update.unseen_channel_messages = result.channel_messages;
update.unseen_channel_buffer_changes = result.unseen_buffer_changes;
update.insert_edge = result.channels.edges;
update
.channel_participants
@@ -2658,18 +2669,12 @@ async fn join_channel_buffer(
.join_channel_buffer(channel_id, session.user_id, session.connection_id)
.await?;
let replica_id = open_response.replica_id;
let collaborators = open_response.collaborators.clone();
response.send(open_response)?;
let update = AddChannelBufferCollaborator {
let update = UpdateChannelBufferCollaborators {
channel_id: channel_id.to_proto(),
collaborator: Some(proto::Collaborator {
user_id: session.user_id.to_proto(),
peer_id: Some(session.connection_id.into()),
replica_id,
}),
collaborators: collaborators.clone(),
};
channel_buffer_updated(
session.connection_id,
@@ -2690,7 +2695,7 @@ async fn update_channel_buffer(
let db = session.db().await;
let channel_id = ChannelId::from_proto(request.channel_id);
let collaborators = db
let (collaborators, non_collaborators, epoch, version) = db
.update_channel_buffer(channel_id, session.user_id, &request.operations)
.await?;
@@ -2703,6 +2708,29 @@ async fn update_channel_buffer(
},
&session.peer,
);
let pool = &*session.connection_pool().await;
broadcast(
None,
non_collaborators
.iter()
.flat_map(|user_id| pool.user_connection_ids(*user_id)),
|peer_id| {
session.peer.send(
peer_id.into(),
proto::UpdateChannels {
unseen_channel_buffer_changes: vec![proto::UnseenChannelBufferChange {
channel_id: channel_id.to_proto(),
epoch: epoch as u64,
version: version.clone(),
}],
..Default::default()
},
)
},
);
Ok(())
}
@@ -2716,8 +2744,8 @@ async fn rejoin_channel_buffers(
.rejoin_channel_buffers(&request.buffers, session.user_id, session.connection_id)
.await?;
for buffer in &buffers {
let collaborators_to_notify = buffer
for rejoined_buffer in &buffers {
let collaborators_to_notify = rejoined_buffer
.buffer
.collaborators
.iter()
@@ -2725,10 +2753,9 @@ async fn rejoin_channel_buffers(
channel_buffer_updated(
session.connection_id,
collaborators_to_notify,
&proto::UpdateChannelBufferCollaborator {
channel_id: buffer.buffer.channel_id,
old_peer_id: Some(buffer.old_connection_id.into()),
new_peer_id: Some(session.connection_id.into()),
&proto::UpdateChannelBufferCollaborators {
channel_id: rejoined_buffer.buffer.channel_id,
collaborators: rejoined_buffer.buffer.collaborators.clone(),
},
&session.peer,
);
@@ -2749,7 +2776,7 @@ async fn leave_channel_buffer(
let db = session.db().await;
let channel_id = ChannelId::from_proto(request.channel_id);
let collaborators_to_notify = db
let left_buffer = db
.leave_channel_buffer(channel_id, session.connection_id)
.await?;
@@ -2757,10 +2784,10 @@ async fn leave_channel_buffer(
channel_buffer_updated(
session.connection_id,
collaborators_to_notify,
&proto::RemoveChannelBufferCollaborator {
left_buffer.connections,
&proto::UpdateChannelBufferCollaborators {
channel_id: channel_id.to_proto(),
peer_id: Some(session.connection_id.into()),
collaborators: left_buffer.collaborators,
},
&session.peer,
);
@@ -2799,7 +2826,7 @@ async fn send_channel_message(
.ok_or_else(|| anyhow!("nonce can't be blank"))?;
let channel_id = ChannelId::from_proto(request.channel_id);
let (message_id, connection_ids) = session
let (message_id, connection_ids, non_participants) = session
.db()
.await
.create_channel_message(
@@ -2829,6 +2856,27 @@ async fn send_channel_message(
response.send(proto::SendChannelMessageResponse {
message: Some(message),
})?;
let pool = &*session.connection_pool().await;
broadcast(
None,
non_participants
.iter()
.flat_map(|user_id| pool.user_connection_ids(*user_id)),
|peer_id| {
session.peer.send(
peer_id.into(),
proto::UpdateChannels {
unseen_channel_messages: vec![proto::UnseenChannelMessage {
channel_id: channel_id.to_proto(),
message_id: message_id.to_proto(),
}],
..Default::default()
},
)
},
);
Ok(())
}
@@ -2851,6 +2899,38 @@ async fn remove_channel_message(
Ok(())
}
async fn acknowledge_channel_message(
request: proto::AckChannelMessage,
session: Session,
) -> Result<()> {
let channel_id = ChannelId::from_proto(request.channel_id);
let message_id = MessageId::from_proto(request.message_id);
session
.db()
.await
.observe_channel_message(channel_id, session.user_id, message_id)
.await?;
Ok(())
}
async fn acknowledge_buffer_version(
request: proto::AckBufferOperation,
session: Session,
) -> Result<()> {
let buffer_id = BufferId::from_proto(request.buffer_id);
session
.db()
.await
.observe_buffer_version(
buffer_id,
session.user_id,
request.epoch as i32,
&request.version,
)
.await?;
Ok(())
}
async fn join_channel_chat(
request: proto::JoinChannelChat,
response: Response<proto::JoinChannelChat>,
@@ -2986,6 +3066,8 @@ fn build_initial_channels_update(
});
}
update.unseen_channel_buffer_changes = channels.unseen_buffer_changes;
update.unseen_channel_messages = channels.channel_messages;
update.insert_edge = channels.channels.edges;
for (channel_id, participants) in channels.channel_participants {
@@ -3235,13 +3317,13 @@ async fn leave_channel_buffers_for_session(session: &Session) -> Result<()> {
.leave_channel_buffers(session.connection_id)
.await?;
for (channel_id, connections) in left_channel_buffers {
for left_buffer in left_channel_buffers {
channel_buffer_updated(
session.connection_id,
connections,
&proto::RemoveChannelBufferCollaborator {
channel_id: channel_id.to_proto(),
peer_id: Some(session.connection_id.into()),
left_buffer.connections,
&proto::UpdateChannelBufferCollaborators {
channel_id: left_buffer.channel_id.to_proto(),
collaborators: left_buffer.collaborators,
},
&session.peer,
);

View File

@@ -4,6 +4,7 @@ use gpui::{ModelHandle, TestAppContext};
mod channel_buffer_tests;
mod channel_message_tests;
mod channel_tests;
mod following_tests;
mod integration_tests;
mod random_channel_buffer_tests;
mod random_project_collaboration_tests;

View File

@@ -3,15 +3,17 @@ use crate::{
tests::TestServer,
};
use call::ActiveCall;
use channel::Channel;
use client::UserId;
use channel::{Channel, ACKNOWLEDGE_DEBOUNCE_INTERVAL};
use client::ParticipantIndex;
use client::{Collaborator, UserId};
use collab_ui::channel_view::ChannelView;
use collections::HashMap;
use editor::{Anchor, Editor, ToOffset};
use futures::future;
use gpui::{executor::Deterministic, ModelHandle, TestAppContext};
use rpc::{proto, RECEIVE_TIMEOUT};
use gpui::{executor::Deterministic, ModelHandle, TestAppContext, ViewContext};
use rpc::{proto::PeerId, RECEIVE_TIMEOUT};
use serde_json::json;
use std::sync::Arc;
use std::{ops::Range, sync::Arc};
#[gpui::test]
async fn test_core_channel_buffers(
@@ -100,7 +102,7 @@ async fn test_core_channel_buffers(
channel_buffer_b.read_with(cx_b, |buffer, _| {
assert_collaborators(
&buffer.collaborators(),
&[client_b.user_id(), client_a.user_id()],
&[client_a.user_id(), client_b.user_id()],
);
});
@@ -120,10 +122,10 @@ async fn test_core_channel_buffers(
}
#[gpui::test]
async fn test_channel_buffer_replica_ids(
async fn test_channel_notes_participant_indices(
deterministic: Arc<Deterministic>,
cx_a: &mut TestAppContext,
cx_b: &mut TestAppContext,
mut cx_a: &mut TestAppContext,
mut cx_b: &mut TestAppContext,
cx_c: &mut TestAppContext,
) {
deterministic.forbid_parking();
@@ -132,6 +134,13 @@ async fn test_channel_buffer_replica_ids(
let client_b = server.create_client(cx_b, "user_b").await;
let client_c = server.create_client(cx_c, "user_c").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);
cx_c.update(editor::init);
let channel_id = server
.make_channel(
"the-channel",
@@ -141,140 +150,173 @@ async fn test_channel_buffer_replica_ids(
)
.await;
let active_call_a = cx_a.read(ActiveCall::global);
let active_call_b = cx_b.read(ActiveCall::global);
let active_call_c = cx_c.read(ActiveCall::global);
// Clients A and B join a channel.
active_call_a
.update(cx_a, |call, cx| call.join_channel(channel_id, cx))
.await
.unwrap();
active_call_b
.update(cx_b, |call, cx| call.join_channel(channel_id, cx))
.await
.unwrap();
// Clients A, B, and C join a channel buffer
// C first so that the replica IDs in the project and the channel buffer are different
let channel_buffer_c = client_c
.channel_store()
.update(cx_c, |store, cx| store.open_channel_buffer(channel_id, cx))
.await
.unwrap();
let channel_buffer_b = client_b
.channel_store()
.update(cx_b, |store, cx| store.open_channel_buffer(channel_id, cx))
.await
.unwrap();
let channel_buffer_a = client_a
.channel_store()
.update(cx_a, |store, cx| store.open_channel_buffer(channel_id, cx))
.await
.unwrap();
// Client B shares a project
client_b
client_a
.fs()
.insert_tree("/dir", json!({ "file.txt": "contents" }))
.insert_tree("/root", json!({"file.txt": "123"}))
.await;
let (project_b, _) = client_b.build_local_project("/dir", cx_b).await;
let shared_project_id = active_call_b
.update(cx_b, |call, cx| call.share_project(project_b.clone(), cx))
let (project_a, worktree_id_a) = client_a.build_local_project("/root", cx_a).await;
let project_b = client_b.build_empty_local_project(cx_b);
let project_c = client_c.build_empty_local_project(cx_c);
let workspace_a = client_a.build_workspace(&project_a, cx_a).root(cx_a);
let workspace_b = client_b.build_workspace(&project_b, cx_b).root(cx_b);
let workspace_c = client_c.build_workspace(&project_c, cx_c).root(cx_c);
// Clients A, B, and C open the channel notes
let channel_view_a = cx_a
.update(|cx| ChannelView::open(channel_id, workspace_a.clone(), cx))
.await
.unwrap();
let channel_view_b = cx_b
.update(|cx| ChannelView::open(channel_id, workspace_b.clone(), cx))
.await
.unwrap();
let channel_view_c = cx_c
.update(|cx| ChannelView::open(channel_id, workspace_c.clone(), cx))
.await
.unwrap();
// Client A joins the project
let project_a = client_a.build_remote_project(shared_project_id, cx_a).await;
// Clients A, B, and C all insert and select some text
channel_view_a.update(cx_a, |notes, cx| {
notes.editor.update(cx, |editor, cx| {
editor.insert("a", cx);
editor.change_selections(None, cx, |selections| {
selections.select_ranges(vec![0..1]);
});
});
});
deterministic.run_until_parked();
// Client C is in a separate project.
client_c.fs().insert_tree("/dir", json!({})).await;
let (separate_project_c, _) = client_c.build_local_project("/dir", cx_c).await;
// Note that each user has a different replica id in the projects vs the
// channel buffer.
channel_buffer_a.read_with(cx_a, |channel_buffer, cx| {
assert_eq!(project_a.read(cx).replica_id(), 1);
assert_eq!(channel_buffer.buffer().read(cx).replica_id(), 2);
channel_view_b.update(cx_b, |notes, cx| {
notes.editor.update(cx, |editor, cx| {
editor.move_down(&Default::default(), cx);
editor.insert("b", cx);
editor.change_selections(None, cx, |selections| {
selections.select_ranges(vec![1..2]);
});
});
});
channel_buffer_b.read_with(cx_b, |channel_buffer, cx| {
assert_eq!(project_b.read(cx).replica_id(), 0);
assert_eq!(channel_buffer.buffer().read(cx).replica_id(), 1);
});
channel_buffer_c.read_with(cx_c, |channel_buffer, cx| {
// C is not in the project
assert_eq!(channel_buffer.buffer().read(cx).replica_id(), 0);
deterministic.run_until_parked();
channel_view_c.update(cx_c, |notes, cx| {
notes.editor.update(cx, |editor, cx| {
editor.move_down(&Default::default(), cx);
editor.insert("c", cx);
editor.change_selections(None, cx, |selections| {
selections.select_ranges(vec![2..3]);
});
});
});
let channel_window_a =
cx_a.add_window(|cx| ChannelView::new(project_a.clone(), channel_buffer_a.clone(), cx));
let channel_window_b =
cx_b.add_window(|cx| ChannelView::new(project_b.clone(), channel_buffer_b.clone(), cx));
let channel_window_c = cx_c.add_window(|cx| {
ChannelView::new(separate_project_c.clone(), channel_buffer_c.clone(), cx)
// Client A sees clients B and C without assigned colors, because they aren't
// in a call together.
deterministic.run_until_parked();
channel_view_a.update(cx_a, |notes, cx| {
notes.editor.update(cx, |editor, cx| {
assert_remote_selections(editor, &[(None, 1..2), (None, 2..3)], cx);
});
});
let channel_view_a = channel_window_a.root(cx_a);
let channel_view_b = channel_window_b.root(cx_b);
let channel_view_c = channel_window_c.root(cx_c);
// Clients A and B join the same call.
for (call, cx) in [(&active_call_a, &mut cx_a), (&active_call_b, &mut cx_b)] {
call.update(*cx, |call, cx| call.join_channel(channel_id, cx))
.await
.unwrap();
}
// For clients A and B, the replica ids in the channel buffer are mapped
// so that they match the same users' replica ids in their shared project.
channel_view_a.read_with(cx_a, |view, cx| {
assert_eq!(
view.editor.read(cx).replica_id_map().unwrap(),
&[(1, 0), (2, 1)].into_iter().collect::<HashMap<_, _>>()
);
// Clients A and B see each other with two different assigned colors. Client C
// still doesn't have a color.
deterministic.run_until_parked();
channel_view_a.update(cx_a, |notes, cx| {
notes.editor.update(cx, |editor, cx| {
assert_remote_selections(
editor,
&[(Some(ParticipantIndex(1)), 1..2), (None, 2..3)],
cx,
);
});
});
channel_view_b.read_with(cx_b, |view, cx| {
assert_eq!(
view.editor.read(cx).replica_id_map().unwrap(),
&[(1, 0), (2, 1)].into_iter().collect::<HashMap<u16, u16>>(),
)
channel_view_b.update(cx_b, |notes, cx| {
notes.editor.update(cx, |editor, cx| {
assert_remote_selections(
editor,
&[(Some(ParticipantIndex(0)), 0..1), (None, 2..3)],
cx,
);
});
});
// Client C only sees themself, as they're not part of any shared project
channel_view_c.read_with(cx_c, |view, cx| {
assert_eq!(
view.editor.read(cx).replica_id_map().unwrap(),
&[(0, 0)].into_iter().collect::<HashMap<u16, u16>>(),
);
});
// Client C joins the project that clients A and B are in.
active_call_c
.update(cx_c, |call, cx| call.join_channel(channel_id, cx))
// Client A shares a project, and client B joins.
let project_id = active_call_a
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_c = client_c.build_remote_project(shared_project_id, cx_c).await;
deterministic.run_until_parked();
project_c.read_with(cx_c, |project, _| {
assert_eq!(project.replica_id(), 2);
});
let project_b = client_b.build_remote_project(project_id, cx_b).await;
let workspace_b = client_b.build_workspace(&project_b, cx_b).root(cx_b);
// For clients A and B, client C's replica id in the channel buffer is
// now mapped to their replica id in the shared project.
channel_view_a.read_with(cx_a, |view, cx| {
assert_eq!(
view.editor.read(cx).replica_id_map().unwrap(),
&[(1, 0), (2, 1), (0, 2)]
.into_iter()
.collect::<HashMap<_, _>>()
);
// Clients A and B open the same file.
let editor_a = workspace_a
.update(cx_a, |workspace, cx| {
workspace.open_path((worktree_id_a, "file.txt"), None, true, cx)
})
.await
.unwrap()
.downcast::<Editor>()
.unwrap();
let editor_b = workspace_b
.update(cx_b, |workspace, cx| {
workspace.open_path((worktree_id_a, "file.txt"), None, true, cx)
})
.await
.unwrap()
.downcast::<Editor>()
.unwrap();
editor_a.update(cx_a, |editor, cx| {
editor.change_selections(None, cx, |selections| {
selections.select_ranges(vec![0..1]);
});
});
channel_view_b.read_with(cx_b, |view, cx| {
assert_eq!(
view.editor.read(cx).replica_id_map().unwrap(),
&[(1, 0), (2, 1), (0, 2)]
.into_iter()
.collect::<HashMap<_, _>>(),
)
editor_b.update(cx_b, |editor, cx| {
editor.change_selections(None, cx, |selections| {
selections.select_ranges(vec![2..3]);
});
});
deterministic.run_until_parked();
// Clients A and B see each other with the same colors as in the channel notes.
editor_a.update(cx_a, |editor, cx| {
assert_remote_selections(editor, &[(Some(ParticipantIndex(1)), 2..3)], cx);
});
editor_b.update(cx_b, |editor, cx| {
assert_remote_selections(editor, &[(Some(ParticipantIndex(0)), 0..1)], cx);
});
}
#[track_caller]
fn assert_remote_selections(
editor: &mut Editor,
expected_selections: &[(Option<ParticipantIndex>, Range<usize>)],
cx: &mut ViewContext<Editor>,
) {
let snapshot = editor.snapshot(cx);
let range = Anchor::min()..Anchor::max();
let remote_selections = snapshot
.remote_selections_in_range(&range, editor.collaboration_hub().unwrap(), cx)
.map(|s| {
let start = s.selection.start.to_offset(&snapshot.buffer_snapshot);
let end = s.selection.end.to_offset(&snapshot.buffer_snapshot);
(s.participant_index, start..end)
})
.collect::<Vec<_>>();
assert_eq!(
remote_selections, expected_selections,
"incorrect remote selections"
);
}
#[gpui::test]
async fn test_reopen_channel_buffer(deterministic: Arc<Deterministic>, cx_a: &mut TestAppContext) {
async fn test_multiple_handles_to_channel_buffer(
deterministic: Arc<Deterministic>,
cx_a: &mut TestAppContext,
) {
deterministic.forbid_parking();
let mut server = TestServer::start(&deterministic).await;
let client_a = server.create_client(cx_a, "user_a").await;
@@ -368,10 +410,7 @@ async fn test_channel_buffer_disconnect(
channel_buffer_a.update(cx_a, |buffer, _| {
assert_eq!(
buffer.channel().as_ref(),
&Channel {
id: channel_id,
name: "the-channel".to_string()
}
&channel(channel_id, "the-channel")
);
assert!(!buffer.is_connected());
});
@@ -396,15 +435,21 @@ async fn test_channel_buffer_disconnect(
channel_buffer_b.update(cx_b, |buffer, _| {
assert_eq!(
buffer.channel().as_ref(),
&Channel {
id: channel_id,
name: "the-channel".to_string()
}
&channel(channel_id, "the-channel")
);
assert!(!buffer.is_connected());
});
}
fn channel(id: u64, name: &'static str) -> Channel {
Channel {
id,
name: name.to_string(),
unseen_note_version: None,
unseen_message_id: None,
}
}
#[gpui::test]
async fn test_rejoin_channel_buffer(
deterministic: Arc<Deterministic>,
@@ -565,26 +610,284 @@ async fn test_channel_buffers_and_server_restarts(
channel_buffer_a.read_with(cx_a, |buffer_a, _| {
channel_buffer_b.read_with(cx_b, |buffer_b, _| {
assert_eq!(
buffer_a
.collaborators()
.iter()
.map(|c| c.user_id)
.collect::<Vec<_>>(),
vec![client_a.user_id().unwrap(), client_b.user_id().unwrap()]
assert_collaborators(
buffer_a.collaborators(),
&[client_a.user_id(), client_b.user_id()],
);
assert_eq!(buffer_a.collaborators(), buffer_b.collaborators());
});
});
}
#[gpui::test(iterations = 10)]
async fn test_following_to_channel_notes_without_a_shared_project(
deterministic: Arc<Deterministic>,
mut cx_a: &mut TestAppContext,
mut cx_b: &mut TestAppContext,
mut cx_c: &mut TestAppContext,
) {
deterministic.forbid_parking();
let mut server = TestServer::start(&deterministic).await;
let client_a = server.create_client(cx_a, "user_a").await;
let client_b = server.create_client(cx_b, "user_b").await;
let client_c = server.create_client(cx_c, "user_c").await;
cx_a.update(editor::init);
cx_b.update(editor::init);
cx_c.update(editor::init);
cx_a.update(collab_ui::channel_view::init);
cx_b.update(collab_ui::channel_view::init);
cx_c.update(collab_ui::channel_view::init);
let channel_1_id = server
.make_channel(
"channel-1",
None,
(&client_a, cx_a),
&mut [(&client_b, cx_b), (&client_c, cx_c)],
)
.await;
let channel_2_id = server
.make_channel(
"channel-2",
None,
(&client_a, cx_a),
&mut [(&client_b, cx_b), (&client_c, cx_c)],
)
.await;
// Clients A, B, and C join a channel.
let active_call_a = cx_a.read(ActiveCall::global);
let active_call_b = cx_b.read(ActiveCall::global);
let active_call_c = cx_c.read(ActiveCall::global);
for (call, cx) in [
(&active_call_a, &mut cx_a),
(&active_call_b, &mut cx_b),
(&active_call_c, &mut cx_c),
] {
call.update(*cx, |call, cx| call.join_channel(channel_1_id, cx))
.await
.unwrap();
}
deterministic.run_until_parked();
// Clients A, B, and C all open their own unshared projects.
client_a.fs().insert_tree("/a", json!({})).await;
client_b.fs().insert_tree("/b", json!({})).await;
client_c.fs().insert_tree("/c", json!({})).await;
let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
let (project_b, _) = client_b.build_local_project("/b", cx_b).await;
let (project_c, _) = client_b.build_local_project("/c", cx_c).await;
let workspace_a = client_a.build_workspace(&project_a, cx_a).root(cx_a);
let workspace_b = client_b.build_workspace(&project_b, cx_b).root(cx_b);
let _workspace_c = client_c.build_workspace(&project_c, cx_c).root(cx_c);
active_call_a
.update(cx_a, |call, cx| call.set_location(Some(&project_a), cx))
.await
.unwrap();
// Client A opens the notes for channel 1.
let channel_view_1_a = cx_a
.update(|cx| ChannelView::open(channel_1_id, workspace_a.clone(), cx))
.await
.unwrap();
channel_view_1_a.update(cx_a, |notes, cx| {
assert_eq!(notes.channel(cx).name, "channel-1");
notes.editor.update(cx, |editor, cx| {
editor.insert("Hello from A.", cx);
editor.change_selections(None, cx, |selections| {
selections.select_ranges(vec![3..4]);
});
});
});
// Client B follows client A.
workspace_b
.update(cx_b, |workspace, cx| {
workspace.follow(client_a.peer_id().unwrap(), cx).unwrap()
})
.await
.unwrap();
// Client B is taken to the notes for channel 1, with the same
// text selected as client A.
deterministic.run_until_parked();
let channel_view_1_b = workspace_b.read_with(cx_b, |workspace, cx| {
assert_eq!(
workspace.leader_for_pane(workspace.active_pane()),
Some(client_a.peer_id().unwrap())
);
workspace
.active_item(cx)
.expect("no active item")
.downcast::<ChannelView>()
.expect("active item is not a channel view")
});
channel_view_1_b.read_with(cx_b, |notes, cx| {
assert_eq!(notes.channel(cx).name, "channel-1");
let editor = notes.editor.read(cx);
assert_eq!(editor.text(cx), "Hello from A.");
assert_eq!(editor.selections.ranges::<usize>(cx), &[3..4]);
});
// Client A opens the notes for channel 2.
let channel_view_2_a = cx_a
.update(|cx| ChannelView::open(channel_2_id, workspace_a.clone(), cx))
.await
.unwrap();
channel_view_2_a.read_with(cx_a, |notes, cx| {
assert_eq!(notes.channel(cx).name, "channel-2");
});
// Client B is taken to the notes for channel 2.
deterministic.run_until_parked();
let channel_view_2_b = workspace_b.read_with(cx_b, |workspace, cx| {
assert_eq!(
workspace.leader_for_pane(workspace.active_pane()),
Some(client_a.peer_id().unwrap())
);
workspace
.active_item(cx)
.expect("no active item")
.downcast::<ChannelView>()
.expect("active item is not a channel view")
});
channel_view_2_b.read_with(cx_b, |notes, cx| {
assert_eq!(notes.channel(cx).name, "channel-2");
});
}
#[gpui::test]
async fn test_channel_buffer_changes(
deterministic: Arc<Deterministic>,
cx_a: &mut TestAppContext,
cx_b: &mut TestAppContext,
) {
deterministic.forbid_parking();
let mut server = TestServer::start(&deterministic).await;
let client_a = server.create_client(cx_a, "user_a").await;
let client_b = server.create_client(cx_b, "user_b").await;
let channel_id = server
.make_channel(
"the-channel",
None,
(&client_a, cx_a),
&mut [(&client_b, cx_b)],
)
.await;
let channel_buffer_a = client_a
.channel_store()
.update(cx_a, |store, cx| store.open_channel_buffer(channel_id, cx))
.await
.unwrap();
// Client A makes an edit, and client B should see that the note has changed.
channel_buffer_a.update(cx_a, |buffer, cx| {
buffer.buffer().update(cx, |buffer, cx| {
buffer.edit([(0..0, "1")], None, cx);
})
});
deterministic.run_until_parked();
let has_buffer_changed = cx_b.read(|cx| {
client_b
.channel_store()
.read(cx)
.has_channel_buffer_changed(channel_id)
.unwrap()
});
assert!(has_buffer_changed);
// Opening the buffer should clear the changed flag.
let project_b = client_b.build_empty_local_project(cx_b);
let workspace_b = client_b.build_workspace(&project_b, cx_b).root(cx_b);
let channel_view_b = cx_b
.update(|cx| ChannelView::open(channel_id, workspace_b.clone(), cx))
.await
.unwrap();
deterministic.run_until_parked();
let has_buffer_changed = cx_b.read(|cx| {
client_b
.channel_store()
.read(cx)
.has_channel_buffer_changed(channel_id)
.unwrap()
});
assert!(!has_buffer_changed);
// Editing the channel while the buffer is open should not show that the buffer has changed.
channel_buffer_a.update(cx_a, |buffer, cx| {
buffer.buffer().update(cx, |buffer, cx| {
buffer.edit([(0..0, "2")], None, cx);
})
});
deterministic.run_until_parked();
let has_buffer_changed = cx_b.read(|cx| {
client_b
.channel_store()
.read(cx)
.has_channel_buffer_changed(channel_id)
.unwrap()
});
assert!(!has_buffer_changed);
deterministic.advance_clock(ACKNOWLEDGE_DEBOUNCE_INTERVAL);
// Test that the server is tracking things correctly, and we retain our 'not changed'
// state across a disconnect
server.simulate_long_connection_interruption(client_b.peer_id().unwrap(), &deterministic);
let has_buffer_changed = cx_b.read(|cx| {
client_b
.channel_store()
.read(cx)
.has_channel_buffer_changed(channel_id)
.unwrap()
});
assert!(!has_buffer_changed);
// Closing the buffer should re-enable change tracking
cx_b.update(|cx| {
workspace_b.update(cx, |workspace, cx| {
workspace.close_all_items_and_panes(&Default::default(), cx)
});
drop(channel_view_b)
});
deterministic.run_until_parked();
channel_buffer_a.update(cx_a, |buffer, cx| {
buffer.buffer().update(cx, |buffer, cx| {
buffer.edit([(0..0, "3")], None, cx);
})
});
deterministic.run_until_parked();
let has_buffer_changed = cx_b.read(|cx| {
client_b
.channel_store()
.read(cx)
.has_channel_buffer_changed(channel_id)
.unwrap()
});
assert!(has_buffer_changed);
}
#[track_caller]
fn assert_collaborators(collaborators: &[proto::Collaborator], ids: &[Option<UserId>]) {
fn assert_collaborators(collaborators: &HashMap<PeerId, Collaborator>, ids: &[Option<UserId>]) {
let mut user_ids = collaborators
.values()
.map(|collaborator| collaborator.user_id)
.collect::<Vec<_>>();
user_ids.sort();
assert_eq!(
collaborators
.into_iter()
.map(|collaborator| collaborator.user_id)
.collect::<Vec<_>>(),
user_ids,
ids.into_iter().map(|id| id.unwrap()).collect::<Vec<_>>()
);
}

View File

@@ -1,7 +1,9 @@
use crate::{rpc::RECONNECT_TIMEOUT, tests::TestServer};
use channel::{ChannelChat, ChannelMessageId};
use gpui::{executor::Deterministic, ModelHandle, TestAppContext};
use collab_ui::chat_panel::ChatPanel;
use gpui::{executor::Deterministic, BorrowAppContext, ModelHandle, TestAppContext};
use std::sync::Arc;
use workspace::dock::Panel;
#[gpui::test]
async fn test_basic_channel_messages(
@@ -223,3 +225,136 @@ fn assert_messages(chat: &ModelHandle<ChannelChat>, messages: &[&str], cx: &mut
messages
);
}
#[gpui::test]
async fn test_channel_message_changes(
deterministic: Arc<Deterministic>,
cx_a: &mut TestAppContext,
cx_b: &mut TestAppContext,
) {
deterministic.forbid_parking();
let mut server = TestServer::start(&deterministic).await;
let client_a = server.create_client(cx_a, "user_a").await;
let client_b = server.create_client(cx_b, "user_b").await;
let channel_id = server
.make_channel(
"the-channel",
None,
(&client_a, cx_a),
&mut [(&client_b, cx_b)],
)
.await;
// Client A sends a message, client B should see that there is a new message.
let channel_chat_a = client_a
.channel_store()
.update(cx_a, |store, cx| store.open_channel_chat(channel_id, cx))
.await
.unwrap();
channel_chat_a
.update(cx_a, |c, cx| c.send_message("one".into(), cx).unwrap())
.await
.unwrap();
deterministic.run_until_parked();
let b_has_messages = cx_b.read_with(|cx| {
client_b
.channel_store()
.read(cx)
.has_new_messages(channel_id)
.unwrap()
});
assert!(b_has_messages);
// Opening the chat should clear the changed flag.
cx_b.update(|cx| {
collab_ui::init(&client_b.app_state, cx);
});
let project_b = client_b.build_empty_local_project(cx_b);
let workspace_b = client_b.build_workspace(&project_b, cx_b).root(cx_b);
let chat_panel_b = workspace_b.update(cx_b, |workspace, cx| ChatPanel::new(workspace, cx));
chat_panel_b
.update(cx_b, |chat_panel, cx| {
chat_panel.set_active(true, cx);
chat_panel.select_channel(channel_id, cx)
})
.await
.unwrap();
deterministic.run_until_parked();
let b_has_messages = cx_b.read_with(|cx| {
client_b
.channel_store()
.read(cx)
.has_new_messages(channel_id)
.unwrap()
});
assert!(!b_has_messages);
// Sending a message while the chat is open should not change the flag.
channel_chat_a
.update(cx_a, |c, cx| c.send_message("two".into(), cx).unwrap())
.await
.unwrap();
deterministic.run_until_parked();
let b_has_messages = cx_b.read_with(|cx| {
client_b
.channel_store()
.read(cx)
.has_new_messages(channel_id)
.unwrap()
});
assert!(!b_has_messages);
// Sending a message while the chat is closed should change the flag.
chat_panel_b.update(cx_b, |chat_panel, cx| {
chat_panel.set_active(false, cx);
});
// Sending a message while the chat is open should not change the flag.
channel_chat_a
.update(cx_a, |c, cx| c.send_message("three".into(), cx).unwrap())
.await
.unwrap();
deterministic.run_until_parked();
let b_has_messages = cx_b.read_with(|cx| {
client_b
.channel_store()
.read(cx)
.has_new_messages(channel_id)
.unwrap()
});
assert!(b_has_messages);
// Closing the chat should re-enable change tracking
cx_b.update(|_| drop(chat_panel_b));
channel_chat_a
.update(cx_a, |c, cx| c.send_message("four".into(), cx).unwrap())
.await
.unwrap();
deterministic.run_until_parked();
let b_has_messages = cx_b.read_with(|cx| {
client_b
.channel_store()
.read(cx)
.has_new_messages(channel_id)
.unwrap()
});
assert!(b_has_messages);
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -273,7 +273,7 @@ impl RandomizedTest for RandomChannelBufferTest {
// channel buffer.
let collaborators = channel_buffer.collaborators();
let mut user_ids =
collaborators.iter().map(|c| c.user_id).collect::<Vec<_>>();
collaborators.values().map(|c| c.user_id).collect::<Vec<_>>();
user_ids.sort();
assert_eq!(
user_ids,

View File

@@ -1,7 +1,7 @@
use crate::{
db::{tests::TestDb, NewUserParams, UserId},
executor::Executor,
rpc::{Server, CLEANUP_TIMEOUT},
rpc::{Server, CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
AppState,
};
use anyhow::anyhow;
@@ -17,6 +17,7 @@ use gpui::{executor::Deterministic, ModelHandle, Task, TestAppContext, WindowHan
use language::LanguageRegistry;
use parking_lot::Mutex;
use project::{Project, WorktreeId};
use rpc::RECEIVE_TIMEOUT;
use settings::SettingsStore;
use std::{
cell::{Ref, RefCell, RefMut},
@@ -29,7 +30,7 @@ use std::{
},
};
use util::http::FakeHttpClient;
use workspace::Workspace;
use workspace::{Workspace, WorkspaceStore};
pub struct TestServer {
pub app_state: Arc<AppState>,
@@ -151,12 +152,12 @@ impl TestServer {
Arc::get_mut(&mut client)
.unwrap()
.set_id(user_id.0 as usize)
.set_id(user_id.to_proto())
.override_authenticate(move |cx| {
cx.spawn(|_| async move {
let access_token = "the-token".to_string();
Ok(Credentials {
user_id: user_id.0 as u64,
user_id: user_id.to_proto(),
access_token,
})
})
@@ -204,13 +205,17 @@ impl TestServer {
let fs = FakeFs::new(cx.background());
let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
let workspace_store = cx.add_model(|cx| WorkspaceStore::new(client.clone(), cx));
let channel_store =
cx.add_model(|cx| ChannelStore::new(client.clone(), user_store.clone(), cx));
let mut language_registry = LanguageRegistry::test();
language_registry.set_executor(cx.background());
let app_state = Arc::new(workspace::AppState {
client: client.clone(),
user_store: user_store.clone(),
workspace_store,
channel_store: channel_store.clone(),
languages: Arc::new(LanguageRegistry::test()),
languages: Arc::new(language_registry),
fs: fs.clone(),
build_window_options: |_, _, _| Default::default(),
initialize_workspace: |_, _, _, _| Task::ready(Ok(())),
@@ -251,6 +256,19 @@ impl TestServer {
.store(true, SeqCst);
}
pub fn simulate_long_connection_interruption(
&self,
peer_id: PeerId,
deterministic: &Arc<Deterministic>,
) {
self.forbid_connections();
self.disconnect_client(peer_id);
deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
self.allow_connections();
deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
deterministic.run_until_parked();
}
pub fn forbid_connections(&self) {
self.forbid_connections.store(true, SeqCst);
}
@@ -536,15 +554,7 @@ impl TestClient {
root_path: impl AsRef<Path>,
cx: &mut TestAppContext,
) -> (ModelHandle<Project>, WorktreeId) {
let project = cx.update(|cx| {
Project::local(
self.client().clone(),
self.app_state.user_store.clone(),
self.app_state.languages.clone(),
self.app_state.fs.clone(),
cx,
)
});
let project = self.build_empty_local_project(cx);
let (worktree, _) = project
.update(cx, |p, cx| {
p.find_or_create_local_worktree(root_path, true, cx)
@@ -557,6 +567,18 @@ impl TestClient {
(project, worktree.read_with(cx, |tree, _| tree.id()))
}
pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> ModelHandle<Project> {
cx.update(|cx| {
Project::local(
self.client().clone(),
self.app_state.user_store.clone(),
self.app_state.languages.clone(),
self.app_state.fs.clone(),
cx,
)
})
}
pub async fn build_remote_project(
&self,
host_project_id: u64,

View File

@@ -37,6 +37,7 @@ fuzzy = { path = "../fuzzy" }
gpui = { path = "../gpui" }
language = { path = "../language" }
menu = { path = "../menu" }
rich_text = { path = "../rich_text" }
picker = { path = "../picker" }
project = { path = "../project" }
recent_projects = {path = "../recent_projects"}

View File

@@ -1,10 +1,12 @@
use anyhow::{anyhow, Result};
use call::ActiveCall;
use channel::{ChannelBuffer, ChannelBufferEvent, ChannelId};
use client::proto;
use clock::ReplicaId;
use call::report_call_event_for_channel;
use channel::{Channel, ChannelBuffer, ChannelBufferEvent, ChannelId, ChannelStore};
use client::{
proto::{self, PeerId},
Collaborator, ParticipantIndex,
};
use collections::HashMap;
use editor::Editor;
use editor::{CollaborationHub, Editor};
use gpui::{
actions,
elements::{ChildView, Label},
@@ -13,7 +15,11 @@ use gpui::{
ViewContext, ViewHandle,
};
use project::Project;
use std::any::{Any, TypeId};
use std::{
any::{Any, TypeId},
sync::Arc,
};
use util::ResultExt;
use workspace::{
item::{FollowableItem, Item, ItemHandle},
register_followable_item,
@@ -23,44 +29,43 @@ use workspace::{
actions!(channel_view, [Deploy]);
pub(crate) fn init(cx: &mut AppContext) {
pub fn init(cx: &mut AppContext) {
register_followable_item::<ChannelView>(cx)
}
pub struct ChannelView {
pub editor: ViewHandle<Editor>,
project: ModelHandle<Project>,
channel_store: ModelHandle<ChannelStore>,
channel_buffer: ModelHandle<ChannelBuffer>,
remote_id: Option<ViewId>,
_editor_event_subscription: Subscription,
}
impl ChannelView {
pub fn deploy(channel_id: ChannelId, workspace: ViewHandle<Workspace>, cx: &mut AppContext) {
pub fn open(
channel_id: ChannelId,
workspace: ViewHandle<Workspace>,
cx: &mut AppContext,
) -> Task<Result<ViewHandle<Self>>> {
let pane = workspace.read(cx).active_pane().clone();
let channel_view = Self::open(channel_id, pane.clone(), workspace.clone(), cx);
let channel_view = Self::open_in_pane(channel_id, pane.clone(), workspace.clone(), cx);
cx.spawn(|mut cx| async move {
let channel_view = channel_view.await?;
pane.update(&mut cx, |pane, cx| {
let room_id = ActiveCall::global(cx)
.read(cx)
.room()
.map(|room| room.read(cx).id());
ActiveCall::report_call_event_for_room(
report_call_event_for_channel(
"open channel notes",
room_id,
Some(channel_id),
channel_id,
&workspace.read(cx).app_state().client,
cx,
);
pane.add_item(Box::new(channel_view), true, true, None, cx);
pane.add_item(Box::new(channel_view.clone()), true, true, None, cx);
});
anyhow::Ok(())
anyhow::Ok(channel_view)
})
.detach();
}
pub fn open(
pub fn open_in_pane(
channel_id: ChannelId,
pane: ViewHandle<Pane>,
workspace: ViewHandle<Workspace>,
@@ -79,17 +84,24 @@ impl ChannelView {
cx.spawn(|mut cx| async move {
let channel_buffer = channel_buffer.await?;
let markdown = markdown.await?;
channel_buffer.update(&mut cx, |buffer, cx| {
buffer.buffer().update(cx, |buffer, cx| {
buffer.set_language(Some(markdown), cx);
})
});
if let Some(markdown) = markdown.await.log_err() {
channel_buffer.update(&mut cx, |buffer, cx| {
buffer.buffer().update(cx, |buffer, cx| {
buffer.set_language(Some(markdown), cx);
})
});
}
pane.update(&mut cx, |pane, cx| {
pane.items_of_type::<Self>()
.find(|channel_view| channel_view.read(cx).channel_buffer == channel_buffer)
.unwrap_or_else(|| cx.add_view(|cx| Self::new(project, channel_buffer, cx)))
.unwrap_or_else(|| {
cx.add_view(|cx| {
let mut this = Self::new(project, channel_store, channel_buffer, cx);
this.acknowledge_buffer_version(cx);
this
})
})
})
.ok_or_else(|| anyhow!("pane was dropped"))
})
@@ -97,44 +109,35 @@ impl ChannelView {
pub fn new(
project: ModelHandle<Project>,
channel_store: ModelHandle<ChannelStore>,
channel_buffer: ModelHandle<ChannelBuffer>,
cx: &mut ViewContext<Self>,
) -> Self {
let buffer = channel_buffer.read(cx).buffer();
let editor = cx.add_view(|cx| Editor::for_buffer(buffer, None, cx));
let editor = cx.add_view(|cx| {
let mut editor = Editor::for_buffer(buffer, None, cx);
editor.set_collaboration_hub(Box::new(ChannelBufferCollaborationHub(
channel_buffer.clone(),
)));
editor
});
let _editor_event_subscription = cx.subscribe(&editor, |_, _, e, cx| cx.emit(e.clone()));
cx.subscribe(&project, Self::handle_project_event).detach();
cx.subscribe(&channel_buffer, Self::handle_channel_buffer_event)
.detach();
let this = Self {
Self {
editor,
project,
channel_store,
channel_buffer,
remote_id: None,
_editor_event_subscription,
};
this.refresh_replica_id_map(cx);
this
}
}
fn handle_project_event(
&mut self,
_: ModelHandle<Project>,
event: &project::Event,
cx: &mut ViewContext<Self>,
) {
match event {
project::Event::RemoteIdChanged(_) => {}
project::Event::DisconnectedFromHost => {}
project::Event::Closed => {}
project::Event::CollaboratorUpdated { .. } => {}
project::Event::CollaboratorLeft(_) => {}
project::Event::CollaboratorJoined(_) => {}
_ => return,
}
self.refresh_replica_id_map(cx);
pub fn channel(&self, cx: &AppContext) -> Arc<Channel> {
self.channel_buffer.read(cx).channel()
}
fn handle_channel_buffer_event(
@@ -144,48 +147,41 @@ impl ChannelView {
cx: &mut ViewContext<Self>,
) {
match event {
ChannelBufferEvent::CollaboratorsChanged => {
self.refresh_replica_id_map(cx);
}
ChannelBufferEvent::Disconnected => self.editor.update(cx, |editor, cx| {
editor.set_read_only(true);
cx.notify();
}),
ChannelBufferEvent::BufferEdited => {
if cx.is_self_focused() || self.editor.is_focused(cx) {
self.acknowledge_buffer_version(cx);
} else {
self.channel_store.update(cx, |store, cx| {
let channel_buffer = self.channel_buffer.read(cx);
store.notes_changed(
channel_buffer.channel().id,
channel_buffer.epoch(),
&channel_buffer.buffer().read(cx).version(),
cx,
)
});
}
}
_ => {}
}
}
/// Build a mapping of channel buffer replica ids to the corresponding
/// replica ids in the current project.
///
/// Using this mapping, a given user can be displayed with the same color
/// in the channel buffer as in other files in the project. Users who are
/// in the channel buffer but not the project will not have a color.
fn refresh_replica_id_map(&self, cx: &mut ViewContext<Self>) {
let mut project_replica_ids_by_channel_buffer_replica_id = HashMap::default();
let project = self.project.read(cx);
let channel_buffer = self.channel_buffer.read(cx);
project_replica_ids_by_channel_buffer_replica_id
.insert(channel_buffer.replica_id(cx), project.replica_id());
project_replica_ids_by_channel_buffer_replica_id.extend(
channel_buffer
.collaborators()
.iter()
.filter_map(|channel_buffer_collaborator| {
project
.collaborators()
.values()
.find_map(|project_collaborator| {
(project_collaborator.user_id == channel_buffer_collaborator.user_id)
.then_some((
channel_buffer_collaborator.replica_id as ReplicaId,
project_collaborator.replica_id,
))
})
}),
);
self.editor.update(cx, |editor, cx| {
editor.set_replica_id_map(Some(project_replica_ids_by_channel_buffer_replica_id), cx)
fn acknowledge_buffer_version(&mut self, cx: &mut ViewContext<'_, '_, ChannelView>) {
self.channel_store.update(cx, |store, cx| {
let channel_buffer = self.channel_buffer.read(cx);
store.acknowledge_notes_version(
channel_buffer.channel().id,
channel_buffer.epoch(),
&channel_buffer.buffer().read(cx).version(),
cx,
)
});
self.channel_buffer.update(cx, |buffer, cx| {
buffer.acknowledge_buffer_version(cx);
});
}
}
@@ -205,6 +201,7 @@ impl View for ChannelView {
fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
if cx.is_self_focused() {
self.acknowledge_buffer_version(cx);
cx.focus(self.editor.as_any())
}
}
@@ -244,6 +241,7 @@ impl Item for ChannelView {
fn clone_on_split(&self, _: WorkspaceId, cx: &mut ViewContext<Self>) -> Option<Self> {
Some(Self::new(
self.project.clone(),
self.channel_store.clone(),
self.channel_buffer.clone(),
cx,
))
@@ -316,7 +314,7 @@ impl FollowableItem for ChannelView {
unreachable!()
};
let open = ChannelView::open(state.channel_id, pane, workspace, cx);
let open = ChannelView::open_in_pane(state.channel_id, pane, workspace, cx);
Some(cx.spawn(|mut cx| async move {
let this = open.await?;
@@ -376,17 +374,32 @@ impl FollowableItem for ChannelView {
})
}
fn set_leader_replica_id(
&mut self,
leader_replica_id: Option<u16>,
cx: &mut ViewContext<Self>,
) {
fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
self.editor.update(cx, |editor, cx| {
editor.set_leader_replica_id(leader_replica_id, cx)
editor.set_leader_peer_id(leader_peer_id, cx)
})
}
fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool {
Editor::should_unfollow_on_event(event, cx)
}
fn is_project_item(&self, _cx: &AppContext) -> bool {
false
}
}
struct ChannelBufferCollaborationHub(ModelHandle<ChannelBuffer>);
impl CollaborationHub for ChannelBufferCollaborationHub {
fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
self.0.read(cx).collaborators()
}
fn user_participant_indices<'a>(
&self,
cx: &'a AppContext,
) -> &'a HashMap<u64, ParticipantIndex> {
self.0.read(cx).user_store().read(cx).participant_indices()
}
}

View File

@@ -3,6 +3,7 @@ use anyhow::Result;
use call::ActiveCall;
use channel::{ChannelChat, ChannelChatEvent, ChannelMessageId, ChannelStore};
use client::Client;
use collections::HashMap;
use db::kvp::KEY_VALUE_STORE;
use editor::Editor;
use feature_flags::{ChannelsAlpha, FeatureFlagAppExt};
@@ -12,12 +13,13 @@ use gpui::{
platform::{CursorStyle, MouseButton},
serde_json,
views::{ItemType, Select, SelectStyle},
AnyViewHandle, AppContext, AsyncAppContext, Entity, ModelHandle, Subscription, Task, View,
ViewContext, ViewHandle, WeakViewHandle,
AnyViewHandle, AppContext, AsyncAppContext, Entity, ImageData, ModelHandle, Subscription, Task,
View, ViewContext, ViewHandle, WeakViewHandle,
};
use language::language_settings::SoftWrap;
use language::{language_settings::SoftWrap, LanguageRegistry};
use menu::Confirm;
use project::Fs;
use rich_text::RichText;
use serde::{Deserialize, Serialize};
use settings::SettingsStore;
use std::sync::Arc;
@@ -35,6 +37,7 @@ const CHAT_PANEL_KEY: &'static str = "ChatPanel";
pub struct ChatPanel {
client: Arc<Client>,
channel_store: ModelHandle<ChannelStore>,
languages: Arc<LanguageRegistry>,
active_chat: Option<(ModelHandle<ChannelChat>, Subscription)>,
message_list: ListState<ChatPanel>,
input_editor: ViewHandle<Editor>,
@@ -42,10 +45,12 @@ pub struct ChatPanel {
local_timezone: UtcOffset,
fs: Arc<dyn Fs>,
width: Option<f32>,
active: bool,
pending_serialization: Task<Option<()>>,
subscriptions: Vec<gpui::Subscription>,
workspace: WeakViewHandle<Workspace>,
has_focus: bool,
markdown_data: HashMap<ChannelMessageId, RichText>,
}
#[derive(Serialize, Deserialize)]
@@ -77,6 +82,7 @@ impl ChatPanel {
let fs = workspace.app_state().fs.clone();
let client = workspace.app_state().client.clone();
let channel_store = workspace.app_state().channel_store.clone();
let languages = workspace.app_state().languages.clone();
let input_editor = cx.add_view(|cx| {
let mut editor = Editor::auto_height(
@@ -129,6 +135,8 @@ impl ChatPanel {
fs,
client,
channel_store,
languages,
active_chat: Default::default(),
pending_serialization: Task::ready(None),
message_list,
@@ -138,7 +146,9 @@ impl ChatPanel {
has_focus: false,
subscriptions: Vec::new(),
workspace: workspace_handle,
active: false,
width: None,
markdown_data: Default::default(),
};
let mut old_dock_position = this.position(cx);
@@ -154,9 +164,9 @@ impl ChatPanel {
}),
);
this.init_active_channel(cx);
this.update_channel_count(cx);
cx.observe(&this.channel_store, |this, _, cx| {
this.init_active_channel(cx);
this.update_channel_count(cx)
})
.detach();
@@ -175,10 +185,33 @@ impl ChatPanel {
})
.detach();
let markdown = this.languages.language_for_name("Markdown");
cx.spawn(|this, mut cx| async move {
let markdown = markdown.await?;
this.update(&mut cx, |this, cx| {
this.input_editor.update(cx, |editor, cx| {
editor.buffer().update(cx, |multi_buffer, cx| {
multi_buffer
.as_singleton()
.unwrap()
.update(cx, |buffer, cx| buffer.set_language(Some(markdown), cx))
})
})
})?;
anyhow::Ok(())
})
.detach_and_log_err(cx);
this
})
}
pub fn active_chat(&self) -> Option<ModelHandle<ChannelChat>> {
self.active_chat.as_ref().map(|(chat, _)| chat.clone())
}
pub fn load(
workspace: WeakViewHandle<Workspace>,
cx: AsyncAppContext,
@@ -225,10 +258,8 @@ impl ChatPanel {
);
}
fn init_active_channel(&mut self, cx: &mut ViewContext<Self>) {
fn update_channel_count(&mut self, cx: &mut ViewContext<Self>) {
let channel_count = self.channel_store.read(cx).channel_count();
self.message_list.reset(0);
self.active_chat = None;
self.channel_select.update(cx, |select, cx| {
select.set_item_count(channel_count, cx);
});
@@ -247,6 +278,7 @@ impl ChatPanel {
}
let subscription = cx.subscribe(&chat, Self::channel_did_change);
self.active_chat = Some((chat, subscription));
self.acknowledge_last_message(cx);
self.channel_select.update(cx, |select, cx| {
if let Some(ix) = self.channel_store.read(cx).index_of_channel(id) {
select.set_selected_index(ix, cx);
@@ -268,11 +300,34 @@ impl ChatPanel {
new_count,
} => {
self.message_list.splice(old_range.clone(), *new_count);
if self.active {
self.acknowledge_last_message(cx);
}
}
ChannelChatEvent::NewMessage {
channel_id,
message_id,
} => {
if !self.active {
self.channel_store.update(cx, |store, cx| {
store.new_message(*channel_id, *message_id, cx)
})
}
}
}
cx.notify();
}
fn acknowledge_last_message(&mut self, cx: &mut ViewContext<'_, '_, ChatPanel>) {
if self.active {
if let Some((chat, _)) = &self.active_chat {
chat.update(cx, |chat, cx| {
chat.acknowledge_last_message(cx);
});
}
}
}
fn render_channel(&self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
let theme = theme::current(cx);
Flex::column()
@@ -299,13 +354,33 @@ impl ChatPanel {
messages.flex(1., true).into_any()
}
fn render_message(&self, ix: usize, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
let message = self.active_chat.as_ref().unwrap().0.read(cx).message(ix);
fn render_message(&mut self, ix: usize, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
let (message, is_continuation, is_last) = {
let active_chat = self.active_chat.as_ref().unwrap().0.read(cx);
let last_message = active_chat.message(ix.saturating_sub(1));
let this_message = active_chat.message(ix);
let is_continuation = last_message.id != this_message.id
&& this_message.sender.id == last_message.sender.id;
(
active_chat.message(ix).clone(),
is_continuation,
active_chat.message_count() == ix + 1,
)
};
let is_pending = message.is_pending();
let text = self
.markdown_data
.entry(message.id)
.or_insert_with(|| rich_text::render_markdown(message.body, &self.languages, None));
let now = OffsetDateTime::now_utc();
let theme = theme::current(cx);
let style = if message.is_pending() {
let style = if is_pending {
&theme.chat_panel.pending_message
} else if is_continuation {
&theme.chat_panel.continuation_message
} else {
&theme.chat_panel.message
};
@@ -318,52 +393,90 @@ impl ChatPanel {
None
};
enum DeleteMessage {}
let body = message.body.clone();
Flex::column()
.with_child(
enum MessageBackgroundHighlight {}
MouseEventHandler::new::<MessageBackgroundHighlight, _>(ix, cx, |state, cx| {
let container = style.container.style_for(state);
if is_continuation {
Flex::row()
.with_child(
Label::new(
message.sender.github_login.clone(),
style.sender.text.clone(),
text.element(
theme.editor.syntax.clone(),
style.body.clone(),
theme.editor.document_highlight_read_background,
cx,
)
.contained()
.with_style(style.sender.container),
.flex(1., true),
)
.with_child(render_remove(message_id_to_remove, cx, &theme))
.contained()
.with_style(*container)
.with_margin_bottom(if is_last {
theme.chat_panel.last_message_bottom_spacing
} else {
0.
})
.into_any()
} else {
Flex::column()
.with_child(
Flex::row()
.with_child(
Flex::row()
.with_child(render_avatar(
message.sender.avatar.clone(),
&theme,
))
.with_child(
Label::new(
message.sender.github_login.clone(),
style.sender.text.clone(),
)
.contained()
.with_style(style.sender.container),
)
.with_child(
Label::new(
format_timestamp(
message.timestamp,
now,
self.local_timezone,
),
style.timestamp.text.clone(),
)
.contained()
.with_style(style.timestamp.container),
)
.align_children_center()
.flex(1., true),
)
.with_child(render_remove(message_id_to_remove, cx, &theme))
.align_children_center(),
)
.with_child(
Label::new(
format_timestamp(message.timestamp, now, self.local_timezone),
style.timestamp.text.clone(),
)
.contained()
.with_style(style.timestamp.container),
Flex::row()
.with_child(
text.element(
theme.editor.syntax.clone(),
style.body.clone(),
theme.editor.document_highlight_read_background,
cx,
)
.flex(1., true),
)
// Add a spacer to make everything line up
.with_child(render_remove(None, cx, &theme)),
)
.with_children(message_id_to_remove.map(|id| {
MouseEventHandler::new::<DeleteMessage, _>(
id as usize,
cx,
|mouse_state, _| {
let button_style =
theme.chat_panel.icon_button.style_for(mouse_state);
render_icon_button(button_style, "icons/x.svg")
.aligned()
.into_any()
},
)
.with_padding(Padding::uniform(2.))
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, this, cx| {
this.remove_message(id, cx);
})
.flex_float()
})),
)
.with_child(Text::new(body, style.body.clone()))
.contained()
.with_style(style.container)
.into_any()
.contained()
.with_style(*container)
.with_margin_bottom(if is_last {
theme.chat_panel.last_message_bottom_spacing
} else {
0.
})
.into_any()
}
})
.into_any()
}
fn render_input_box(&self, theme: &Arc<Theme>, cx: &AppContext) -> AnyElement<Self> {
@@ -409,7 +522,7 @@ impl ChatPanel {
})
.on_click(MouseButton::Left, move |_, _, cx| {
if let Some(workspace) = workspace.upgrade(cx) {
ChannelView::deploy(channel_id, workspace, cx);
ChannelView::open(channel_id, workspace, cx).detach();
}
})
.with_tooltip::<OpenChannelNotes>(
@@ -537,6 +650,7 @@ impl ChatPanel {
cx.spawn(|this, mut cx| async move {
let chat = open_chat.await?;
this.update(&mut cx, |this, cx| {
this.markdown_data = Default::default();
this.set_active_chat(chat, cx);
})
})
@@ -546,7 +660,7 @@ impl ChatPanel {
if let Some((chat, _)) = &self.active_chat {
let channel_id = chat.read(cx).channel().id;
if let Some(workspace) = self.workspace.upgrade(cx) {
ChannelView::deploy(channel_id, workspace, cx);
ChannelView::open(channel_id, workspace, cx).detach();
}
}
}
@@ -561,6 +675,72 @@ impl ChatPanel {
}
}
fn render_avatar(avatar: Option<Arc<ImageData>>, theme: &Arc<Theme>) -> AnyElement<ChatPanel> {
let avatar_style = theme.chat_panel.avatar;
avatar
.map(|avatar| {
Image::from_data(avatar)
.with_style(avatar_style.image)
.aligned()
.contained()
.with_corner_radius(avatar_style.outer_corner_radius)
.constrained()
.with_width(avatar_style.outer_width)
.with_height(avatar_style.outer_width)
.into_any()
})
.unwrap_or_else(|| {
Empty::new()
.constrained()
.with_width(avatar_style.outer_width)
.into_any()
})
.contained()
.with_style(theme.chat_panel.avatar_container)
.into_any()
}
fn render_remove(
message_id_to_remove: Option<u64>,
cx: &mut ViewContext<'_, '_, ChatPanel>,
theme: &Arc<Theme>,
) -> AnyElement<ChatPanel> {
enum DeleteMessage {}
message_id_to_remove
.map(|id| {
MouseEventHandler::new::<DeleteMessage, _>(id as usize, cx, |mouse_state, _| {
let button_style = theme.chat_panel.icon_button.style_for(mouse_state);
render_icon_button(button_style, "icons/x.svg")
.aligned()
.into_any()
})
.with_padding(Padding::uniform(2.))
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, this, cx| {
this.remove_message(id, cx);
})
.flex_float()
.into_any()
})
.unwrap_or_else(|| {
let style = theme.chat_panel.icon_button.default;
Empty::new()
.constrained()
.with_width(style.icon_width)
.aligned()
.constrained()
.with_width(style.button_width)
.with_height(style.button_width)
.contained()
.with_uniform_padding(2.)
.flex_float()
.into_any()
})
}
impl Entity for ChatPanel {
type Event = Event;
}
@@ -627,8 +807,12 @@ impl Panel for ChatPanel {
}
fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
if active && !is_chat_feature_enabled(cx) {
cx.emit(Event::Dismissed);
self.active = active;
if active {
self.acknowledge_last_message(cx);
if !is_chat_feature_enabled(cx) {
cx.emit(Event::Dismissed);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -215,7 +215,13 @@ impl CollabTitlebarItem {
let git_style = theme.titlebar.git_menu_button.clone();
let item_spacing = theme.titlebar.item_spacing;
let mut ret = Flex::row().with_child(
let mut ret = Flex::row();
if let Some(project_host) = self.collect_project_host(theme.clone(), cx) {
ret = ret.with_child(project_host)
}
ret = ret.with_child(
Stack::new()
.with_child(
MouseEventHandler::new::<ToggleProjectMenu, _>(0, cx, |mouse_state, cx| {
@@ -283,6 +289,71 @@ impl CollabTitlebarItem {
ret.into_any()
}
fn collect_project_host(
&self,
theme: Arc<Theme>,
cx: &mut ViewContext<Self>,
) -> Option<AnyElement<Self>> {
if ActiveCall::global(cx).read(cx).room().is_none() {
return None;
}
let project = self.project.read(cx);
let user_store = self.user_store.read(cx);
if project.is_local() {
return None;
}
let Some(host) = project.host() else {
return None;
};
let (Some(host_user), Some(participant_index)) = (
user_store.get_cached_user(host.user_id),
user_store.participant_indices().get(&host.user_id),
) else {
return None;
};
enum ProjectHost {}
enum ProjectHostTooltip {}
let host_style = theme.titlebar.project_host.clone();
let selection_style = theme
.editor
.selection_style_for_room_participant(participant_index.0);
let peer_id = host.peer_id.clone();
Some(
MouseEventHandler::new::<ProjectHost, _>(0, cx, |mouse_state, _| {
let mut host_style = host_style.style_for(mouse_state).clone();
host_style.text.color = selection_style.cursor;
Label::new(host_user.github_login.clone(), host_style.text)
.contained()
.with_style(host_style.container)
.aligned()
.left()
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, this, cx| {
if let Some(workspace) = this.workspace.upgrade(cx) {
if let Some(task) =
workspace.update(cx, |workspace, cx| workspace.follow(peer_id, cx))
{
task.detach_and_log_err(cx);
}
}
})
.with_tooltip::<ProjectHostTooltip>(
0,
host_user.github_login.clone() + " is sharing this project. Click to follow.",
None,
theme.tooltip.clone(),
cx,
)
.into_any_named("project-host"),
)
}
fn window_activation_changed(&mut self, active: bool, cx: &mut ViewContext<Self>) {
let project = if active {
Some(self.project.clone())
@@ -877,7 +948,7 @@ impl CollabTitlebarItem {
fn render_face_pile(
&self,
user: &User,
replica_id: Option<ReplicaId>,
_replica_id: Option<ReplicaId>,
peer_id: PeerId,
location: Option<ParticipantLocation>,
muted: bool,
@@ -886,23 +957,20 @@ impl CollabTitlebarItem {
theme: &Theme,
cx: &mut ViewContext<Self>,
) -> AnyElement<Self> {
let user_id = user.id;
let project_id = workspace.read(cx).project().read(cx).remote_id();
let room = ActiveCall::global(cx).read(cx).room();
let is_being_followed = workspace.read(cx).is_being_followed(peer_id);
let followed_by_self = room
.and_then(|room| {
Some(
is_being_followed
&& room
.read(cx)
.followers_for(peer_id, project_id?)
.iter()
.any(|&follower| {
Some(follower) == workspace.read(cx).client().peer_id()
}),
)
})
.unwrap_or(false);
let room = ActiveCall::global(cx).read(cx).room().cloned();
let self_peer_id = workspace.read(cx).client().peer_id();
let self_following = workspace.read(cx).is_being_followed(peer_id);
let self_following_initialized = self_following
&& room.as_ref().map_or(false, |room| match project_id {
None => true,
Some(project_id) => room
.read(cx)
.followers_for(peer_id, project_id)
.iter()
.any(|&follower| Some(follower) == self_peer_id),
});
let leader_style = theme.titlebar.leader_avatar;
let follower_style = theme.titlebar.follower_avatar;
@@ -921,147 +989,131 @@ impl CollabTitlebarItem {
.background_color
.unwrap_or_default();
if let Some(replica_id) = replica_id {
if followed_by_self {
let selection = theme.editor.replica_selection_style(replica_id).selection;
let participant_index = self
.user_store
.read(cx)
.participant_indices()
.get(&user_id)
.copied();
if let Some(participant_index) = participant_index {
if self_following_initialized {
let selection = theme
.editor
.selection_style_for_room_participant(participant_index.0)
.selection;
background_color = Color::blend(selection, background_color);
background_color.a = 255;
}
}
let mut content = Stack::new()
.with_children(user.avatar.as_ref().map(|avatar| {
let face_pile = FacePile::new(theme.titlebar.follower_avatar_overlap)
.with_child(Self::render_face(
avatar.clone(),
Self::location_style(workspace, location, leader_style, cx),
background_color,
microphone_state,
))
.with_children(
(|| {
let project_id = project_id?;
let room = room?.read(cx);
let followers = room.followers_for(peer_id, project_id);
enum TitlebarParticipant {}
Some(followers.into_iter().flat_map(|&follower| {
let remote_participant =
room.remote_participant_for_peer_id(follower);
let avatar = remote_participant
.and_then(|p| p.user.avatar.clone())
.or_else(|| {
if follower == workspace.read(cx).client().peer_id()? {
workspace
.read(cx)
.user_store()
.read(cx)
.current_user()?
.avatar
.clone()
} else {
None
let content = MouseEventHandler::new::<TitlebarParticipant, _>(
peer_id.as_u64() as usize,
cx,
move |_, cx| {
Stack::new()
.with_children(user.avatar.as_ref().map(|avatar| {
let face_pile = FacePile::new(theme.titlebar.follower_avatar_overlap)
.with_child(Self::render_face(
avatar.clone(),
Self::location_style(workspace, location, leader_style, cx),
background_color,
microphone_state,
))
.with_children(
(|| {
let project_id = project_id?;
let room = room?.read(cx);
let followers = room.followers_for(peer_id, project_id);
Some(followers.into_iter().filter_map(|&follower| {
if Some(follower) == self_peer_id {
return None;
}
})?;
let participant =
room.remote_participant_for_peer_id(follower)?;
Some(Self::render_face(
participant.user.avatar.clone()?,
follower_style,
background_color,
None,
))
}))
})()
.into_iter()
.flatten(),
)
.with_children(
self_following_initialized
.then(|| self.user_store.read(cx).current_user())
.and_then(|user| {
Some(Self::render_face(
user?.avatar.clone()?,
follower_style,
background_color,
None,
))
}),
);
Some(Self::render_face(
avatar.clone(),
follower_style,
background_color,
None,
))
}))
})()
.into_iter()
.flatten(),
);
let mut container = face_pile
.contained()
.with_style(theme.titlebar.leader_selection);
let mut container = face_pile
.contained()
.with_style(theme.titlebar.leader_selection);
if let Some(replica_id) = replica_id {
if followed_by_self {
let color = theme.editor.replica_selection_style(replica_id).selection;
container = container.with_background_color(color);
}
}
container
}))
.with_children((|| {
let replica_id = replica_id?;
let color = theme.editor.replica_selection_style(replica_id).cursor;
Some(
AvatarRibbon::new(color)
.constrained()
.with_width(theme.titlebar.avatar_ribbon.width)
.with_height(theme.titlebar.avatar_ribbon.height)
.aligned()
.bottom(),
)
})())
.into_any();
if let Some(location) = location {
if let Some(replica_id) = replica_id {
enum ToggleFollow {}
content = MouseEventHandler::new::<ToggleFollow, _>(
replica_id.into(),
cx,
move |_, _| content,
)
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, item, cx| {
if let Some(workspace) = item.workspace.upgrade(cx) {
if let Some(task) = workspace
.update(cx, |workspace, cx| workspace.toggle_follow(peer_id, cx))
{
task.detach_and_log_err(cx);
if let Some(participant_index) = participant_index {
if self_following_initialized {
let color = theme
.editor
.selection_style_for_room_participant(participant_index.0)
.selection;
container = container.with_background_color(color);
}
}
}
})
.with_tooltip::<ToggleFollow>(
peer_id.as_u64() as usize,
if is_being_followed {
format!("Unfollow {}", user.github_login)
} else {
format!("Follow {}", user.github_login)
},
Some(Box::new(FollowNextCollaborator)),
theme.tooltip.clone(),
cx,
)
.into_any();
} else if let ParticipantLocation::SharedProject { project_id } = location {
enum JoinProject {}
let user_id = user.id;
content = MouseEventHandler::new::<JoinProject, _>(
peer_id.as_u64() as usize,
cx,
move |_, _| content,
)
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, this, cx| {
if let Some(workspace) = this.workspace.upgrade(cx) {
let app_state = workspace.read(cx).app_state().clone();
workspace::join_remote_project(project_id, user_id, app_state, cx)
.detach_and_log_err(cx);
}
})
.with_tooltip::<JoinProject>(
peer_id.as_u64() as usize,
format!("Follow {} into external project", user.github_login),
Some(Box::new(FollowNextCollaborator)),
theme.tooltip.clone(),
cx,
)
.into_any();
}
container
}))
.with_children((|| {
let participant_index = participant_index?;
let color = theme
.editor
.selection_style_for_room_participant(participant_index.0)
.cursor;
Some(
AvatarRibbon::new(color)
.constrained()
.with_width(theme.titlebar.avatar_ribbon.width)
.with_height(theme.titlebar.avatar_ribbon.height)
.aligned()
.bottom(),
)
})())
},
);
if Some(peer_id) == self_peer_id {
return content.into_any();
}
content
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, this, cx| {
let Some(workspace) = this.workspace.upgrade(cx) else {
return;
};
if let Some(task) =
workspace.update(cx, |workspace, cx| workspace.follow(peer_id, cx))
{
task.detach_and_log_err(cx);
}
})
.with_tooltip::<TitlebarParticipant>(
peer_id.as_u64() as usize,
format!("Follow {}", user.github_login),
Some(Box::new(FollowNextCollaborator)),
theme.tooltip.clone(),
cx,
)
.into_any()
}
fn location_style(

View File

@@ -7,10 +7,10 @@ mod face_pile;
mod incoming_call_notification;
mod notifications;
mod panel_settings;
mod project_shared_notification;
pub mod project_shared_notification;
mod sharing_status_indicator;
use call::{ActiveCall, Room};
use call::{report_call_event_for_room, ActiveCall, Room};
use gpui::{
actions,
geometry::{
@@ -55,18 +55,18 @@ pub fn toggle_screen_sharing(_: &ToggleScreenSharing, cx: &mut AppContext) {
let client = call.client();
let toggle_screen_sharing = room.update(cx, |room, cx| {
if room.is_screen_sharing() {
ActiveCall::report_call_event_for_room(
report_call_event_for_room(
"disable screen share",
Some(room.id()),
room.id(),
room.channel_id(),
&client,
cx,
);
Task::ready(room.unshare_screen(cx))
} else {
ActiveCall::report_call_event_for_room(
report_call_event_for_room(
"enable screen share",
Some(room.id()),
room.id(),
room.channel_id(),
&client,
cx,
@@ -83,23 +83,13 @@ pub fn toggle_mute(_: &ToggleMute, cx: &mut AppContext) {
if let Some(room) = call.room().cloned() {
let client = call.client();
room.update(cx, |room, cx| {
if room.is_muted(cx) {
ActiveCall::report_call_event_for_room(
"enable microphone",
Some(room.id()),
room.channel_id(),
&client,
cx,
);
let operation = if room.is_muted(cx) {
"enable microphone"
} else {
ActiveCall::report_call_event_for_room(
"disable microphone",
Some(room.id()),
room.channel_id(),
&client,
cx,
);
}
"disable microphone"
};
report_call_event_for_room(operation, room.id(), room.channel_id(), &client, cx);
room.toggle_mute(cx)
})
.map(|task| task.detach_and_log_err(cx))

View File

@@ -40,7 +40,9 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut AppContext) {
.push(window);
}
}
room::Event::RemoteProjectUnshared { project_id } => {
room::Event::RemoteProjectUnshared { project_id }
| room::Event::RemoteProjectJoined { project_id }
| room::Event::RemoteProjectInvitationDiscarded { project_id } => {
if let Some(windows) = notification_windows.remove(&project_id) {
for window in windows {
window.remove(cx);
@@ -82,7 +84,6 @@ impl ProjectSharedNotification {
}
fn join(&mut self, cx: &mut ViewContext<Self>) {
cx.remove_window();
if let Some(app_state) = self.app_state.upgrade() {
workspace::join_remote_project(self.project_id, self.owner.id, app_state, cx)
.detach_and_log_err(cx);
@@ -90,7 +91,15 @@ impl ProjectSharedNotification {
}
fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
cx.remove_window();
if let Some(active_room) =
ActiveCall::global(cx).read_with(cx, |call, _| call.room().cloned())
{
active_room.update(cx, |_, cx| {
cx.emit(room::Event::RemoteProjectInvitationDiscarded {
project_id: self.project_id,
});
});
}
}
fn render_owner(&self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {

View File

@@ -18,6 +18,15 @@ actions!(command_palette, [Toggle]);
pub type CommandPalette = Picker<CommandPaletteDelegate>;
pub type CommandPaletteInterceptor =
Box<dyn Fn(&str, &AppContext) -> Option<CommandInterceptResult>>;
pub struct CommandInterceptResult {
pub action: Box<dyn Action>,
pub string: String,
pub positions: Vec<usize>,
}
pub struct CommandPaletteDelegate {
actions: Vec<Command>,
matches: Vec<StringMatch>,
@@ -117,7 +126,7 @@ impl PickerDelegate for CommandPaletteDelegate {
}
})
.collect::<Vec<_>>();
let actions = cx.read(move |cx| {
let mut actions = cx.read(move |cx| {
let hit_counts = cx.optional_global::<HitCounts>();
actions.sort_by_key(|action| {
(
@@ -136,7 +145,7 @@ impl PickerDelegate for CommandPaletteDelegate {
char_bag: command.name.chars().collect(),
})
.collect::<Vec<_>>();
let matches = if query.is_empty() {
let mut matches = if query.is_empty() {
candidates
.into_iter()
.enumerate()
@@ -158,6 +167,40 @@ impl PickerDelegate for CommandPaletteDelegate {
)
.await
};
let intercept_result = cx.read(|cx| {
if cx.has_global::<CommandPaletteInterceptor>() {
cx.global::<CommandPaletteInterceptor>()(&query, cx)
} else {
None
}
});
if let Some(CommandInterceptResult {
action,
string,
positions,
}) = intercept_result
{
if let Some(idx) = matches
.iter()
.position(|m| actions[m.candidate_id].action.id() == action.id())
{
matches.remove(idx);
}
actions.push(Command {
name: string.clone(),
action,
keystrokes: vec![],
});
matches.insert(
0,
StringMatch {
candidate_id: actions.len() - 1,
string,
positions,
score: 0.0,
},
)
}
picker
.update(&mut cx, |picker, _| {
let delegate = picker.delegate_mut();
@@ -222,7 +265,7 @@ impl PickerDelegate for CommandPaletteDelegate {
.with_children(
[
(keystroke.ctrl, "^"),
(keystroke.alt, ""),
(keystroke.alt, ""),
(keystroke.cmd, ""),
(keystroke.shift, ""),
]

View File

@@ -21,6 +21,9 @@ util = { path = "../util" }
workspace = { path = "../workspace" }
anyhow.workspace = true
schemars.workspace = true
serde.workspace = true
serde_derive.workspace = true
smallvec.workspace = true
postage.workspace = true

View File

@@ -1,4 +1,6 @@
pub mod items;
mod project_diagnostics_settings;
mod toolbar_controls;
use anyhow::Result;
use collections::{BTreeSet, HashSet};
@@ -19,6 +21,7 @@ use language::{
};
use lsp::LanguageServerId;
use project::{DiagnosticSummary, Project, ProjectPath};
use project_diagnostics_settings::ProjectDiagnosticsSettings;
use serde_json::json;
use smallvec::SmallVec;
use std::{
@@ -30,18 +33,21 @@ use std::{
sync::Arc,
};
use theme::ThemeSettings;
pub use toolbar_controls::ToolbarControls;
use util::TryFutureExt;
use workspace::{
item::{BreadcrumbText, Item, ItemEvent, ItemHandle},
ItemNavHistory, Pane, PaneBackdrop, ToolbarItemLocation, Workspace,
};
actions!(diagnostics, [Deploy]);
actions!(diagnostics, [Deploy, ToggleWarnings]);
const CONTEXT_LINE_COUNT: u32 = 1;
pub fn init(cx: &mut AppContext) {
settings::register::<ProjectDiagnosticsSettings>(cx);
cx.add_action(ProjectDiagnosticsEditor::deploy);
cx.add_action(ProjectDiagnosticsEditor::toggle_warnings);
items::init(cx);
}
@@ -55,6 +61,7 @@ struct ProjectDiagnosticsEditor {
excerpts: ModelHandle<MultiBuffer>,
path_states: Vec<PathState>,
paths_to_update: BTreeSet<(ProjectPath, LanguageServerId)>,
include_warnings: bool,
}
struct PathState {
@@ -187,6 +194,7 @@ impl ProjectDiagnosticsEditor {
editor,
path_states: Default::default(),
paths_to_update,
include_warnings: settings::get::<ProjectDiagnosticsSettings>(cx).include_warnings,
};
this.update_excerpts(None, cx);
this
@@ -204,6 +212,18 @@ impl ProjectDiagnosticsEditor {
}
}
fn toggle_warnings(&mut self, _: &ToggleWarnings, cx: &mut ViewContext<Self>) {
self.include_warnings = !self.include_warnings;
self.paths_to_update = self
.project
.read(cx)
.diagnostic_summaries(cx)
.map(|(path, server_id, _)| (path, server_id))
.collect();
self.update_excerpts(None, cx);
cx.notify();
}
fn update_excerpts(
&mut self,
language_server_id: Option<LanguageServerId>,
@@ -277,14 +297,18 @@ impl ProjectDiagnosticsEditor {
let mut blocks_to_add = Vec::new();
let mut blocks_to_remove = HashSet::default();
let mut first_excerpt_id = None;
let max_severity = if self.include_warnings {
DiagnosticSeverity::WARNING
} else {
DiagnosticSeverity::ERROR
};
let excerpts_snapshot = self.excerpts.update(cx, |excerpts, excerpts_cx| {
let mut old_groups = path_state.diagnostic_groups.iter().enumerate().peekable();
let mut new_groups = snapshot
.diagnostic_groups(language_server_id)
.into_iter()
.filter(|(_, group)| {
group.entries[group.primary_ix].diagnostic.severity
<= DiagnosticSeverity::WARNING
group.entries[group.primary_ix].diagnostic.severity <= max_severity
})
.peekable();
loop {
@@ -1501,6 +1525,7 @@ mod tests {
client::init_settings(cx);
workspace::init_settings(cx);
Project::init_settings(cx);
crate::init(cx);
});
}

View File

@@ -0,0 +1,28 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Debug)]
pub struct ProjectDiagnosticsSettings {
pub include_warnings: bool,
}
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug)]
pub struct ProjectDiagnosticsSettingsContent {
include_warnings: Option<bool>,
}
impl settings::Setting for ProjectDiagnosticsSettings {
const KEY: Option<&'static str> = Some("diagnostics");
type FileContent = ProjectDiagnosticsSettingsContent;
fn load(
default_value: &Self::FileContent,
user_values: &[&Self::FileContent],
_cx: &gpui::AppContext,
) -> anyhow::Result<Self>
where
Self: Sized,
{
Self::load_via_json_merge(default_value, user_values)
}
}

View File

@@ -0,0 +1,115 @@
use crate::{ProjectDiagnosticsEditor, ToggleWarnings};
use gpui::{
elements::*,
platform::{CursorStyle, MouseButton},
Action, Entity, EventContext, View, ViewContext, WeakViewHandle,
};
use workspace::{item::ItemHandle, ToolbarItemLocation, ToolbarItemView};
pub struct ToolbarControls {
editor: Option<WeakViewHandle<ProjectDiagnosticsEditor>>,
}
impl Entity for ToolbarControls {
type Event = ();
}
impl View for ToolbarControls {
fn ui_name() -> &'static str {
"ToolbarControls"
}
fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
let include_warnings = self
.editor
.as_ref()
.and_then(|editor| editor.upgrade(cx))
.map(|editor| editor.read(cx).include_warnings)
.unwrap_or(false);
let tooltip = if include_warnings {
"Exclude Warnings".into()
} else {
"Include Warnings".into()
};
Flex::row()
.with_child(render_toggle_button(
0,
"icons/warning.svg",
include_warnings,
(tooltip, Some(Box::new(ToggleWarnings))),
cx,
move |this, cx| {
if let Some(editor) = this.editor.and_then(|editor| editor.upgrade(cx)) {
editor.update(cx, |editor, cx| {
editor.toggle_warnings(&Default::default(), cx)
});
}
},
))
.into_any()
}
}
impl ToolbarItemView for ToolbarControls {
fn set_active_pane_item(
&mut self,
active_pane_item: Option<&dyn ItemHandle>,
_: &mut ViewContext<Self>,
) -> ToolbarItemLocation {
if let Some(pane_item) = active_pane_item.as_ref() {
if let Some(editor) = pane_item.downcast::<ProjectDiagnosticsEditor>() {
self.editor = Some(editor.downgrade());
ToolbarItemLocation::PrimaryRight { flex: None }
} else {
ToolbarItemLocation::Hidden
}
} else {
ToolbarItemLocation::Hidden
}
}
}
impl ToolbarControls {
pub fn new() -> Self {
ToolbarControls { editor: None }
}
}
fn render_toggle_button<
F: 'static + Fn(&mut ToolbarControls, &mut EventContext<ToolbarControls>),
>(
index: usize,
icon: &'static str,
toggled: bool,
tooltip: (String, Option<Box<dyn Action>>),
cx: &mut ViewContext<ToolbarControls>,
on_click: F,
) -> AnyElement<ToolbarControls> {
enum Button {}
let theme = theme::current(cx);
let (tooltip_text, action) = tooltip;
MouseEventHandler::new::<Button, _>(index, cx, |mouse_state, _| {
let style = theme
.workspace
.toolbar
.toggleable_tool
.in_state(toggled)
.style_for(mouse_state);
Svg::new(icon)
.with_color(style.color)
.constrained()
.with_width(style.icon_width)
.aligned()
.constrained()
.with_width(style.button_width)
.with_height(style.button_width)
.contained()
.with_style(style.container)
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, view, cx| on_click(view, cx))
.with_tooltip::<Button>(index, tooltip_text, action, theme.tooltip.clone(), cx)
.into_any_named("quick action bar button")
}

View File

@@ -36,6 +36,7 @@ language = { path = "../language" }
lsp = { path = "../lsp" }
project = { path = "../project" }
rpc = { path = "../rpc" }
rich_text = { path = "../rich_text" }
settings = { path = "../settings" }
snippet = { path = "../snippet" }
sum_tree = { path = "../sum_tree" }

View File

@@ -25,7 +25,7 @@ use ::git::diff::DiffHunk;
use aho_corasick::AhoCorasick;
use anyhow::{anyhow, Context, Result};
use blink_manager::BlinkManager;
use client::{ClickhouseEvent, TelemetrySettings};
use client::{ClickhouseEvent, Collaborator, ParticipantIndex, TelemetrySettings};
use clock::{Global, ReplicaId};
use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
use convert_case::{Case, Casing};
@@ -79,6 +79,7 @@ pub use multi_buffer::{
use ordered_float::OrderedFloat;
use project::{FormatTrigger, Location, Project, ProjectPath, ProjectTransaction};
use rand::{seq::SliceRandom, thread_rng};
use rpc::proto::PeerId;
use scroll::{
autoscroll::Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide,
};
@@ -103,7 +104,7 @@ use sum_tree::TreeMap;
use text::Rope;
use theme::{DiagnosticStyle, Theme, ThemeSettings};
use util::{post_inc, RangeExt, ResultExt, TryFutureExt};
use workspace::{ItemNavHistory, ViewId, Workspace};
use workspace::{ItemNavHistory, SplitDirection, ViewId, Workspace};
use crate::git::diff_hunk_to_display;
@@ -363,6 +364,7 @@ pub fn init_settings(cx: &mut AppContext) {
pub fn init(cx: &mut AppContext) {
init_settings(cx);
cx.add_action(Editor::new_file);
cx.add_action(Editor::new_file_in_direction);
cx.add_action(Editor::cancel);
cx.add_action(Editor::newline);
cx.add_action(Editor::newline_above);
@@ -580,11 +582,11 @@ pub struct Editor {
get_field_editor_theme: Option<Arc<GetFieldEditorTheme>>,
override_text_style: Option<Box<OverrideTextStyle>>,
project: Option<ModelHandle<Project>>,
collaboration_hub: Option<Box<dyn CollaborationHub>>,
focused: bool,
blink_manager: ModelHandle<BlinkManager>,
pub show_local_selections: bool,
mode: EditorMode,
replica_id_mapping: Option<HashMap<ReplicaId, ReplicaId>>,
show_gutter: bool,
show_wrap_guides: Option<bool>,
placeholder_text: Option<Arc<str>>,
@@ -608,7 +610,7 @@ pub struct Editor {
keymap_context_layers: BTreeMap<TypeId, KeymapContext>,
input_enabled: bool,
read_only: bool,
leader_replica_id: Option<u16>,
leader_peer_id: Option<PeerId>,
remote_id: Option<ViewId>,
hover_state: HoverState,
gutter_hovered: bool,
@@ -630,6 +632,15 @@ pub struct EditorSnapshot {
ongoing_scroll: OngoingScroll,
}
pub struct RemoteSelection {
pub replica_id: ReplicaId,
pub selection: Selection<Anchor>,
pub cursor_shape: CursorShape,
pub peer_id: PeerId,
pub line_mode: bool,
pub participant_index: Option<ParticipantIndex>,
}
#[derive(Clone, Debug)]
struct SelectionHistoryEntry {
selections: Arc<[Selection<Anchor>]>,
@@ -1046,7 +1057,8 @@ impl CompletionsMenu {
item_ix: Some(item_ix),
},
cx,
);
)
.map(|task| task.detach());
})
.into_any(),
);
@@ -1538,12 +1550,12 @@ impl Editor {
active_diagnostics: None,
soft_wrap_mode_override,
get_field_editor_theme,
collaboration_hub: project.clone().map(|project| Box::new(project) as _),
project,
focused: false,
blink_manager: blink_manager.clone(),
show_local_selections: true,
mode,
replica_id_mapping: None,
show_gutter: mode == EditorMode::Full,
show_wrap_guides: None,
placeholder_text: None,
@@ -1570,7 +1582,7 @@ impl Editor {
keymap_context_layers: Default::default(),
input_enabled: true,
read_only: false,
leader_replica_id: None,
leader_peer_id: None,
remote_id: None,
hover_state: Default::default(),
link_go_to_definition_state: Default::default(),
@@ -1633,12 +1645,32 @@ impl Editor {
}
}
pub fn new_file_in_direction(
workspace: &mut Workspace,
action: &workspace::NewFileInDirection,
cx: &mut ViewContext<Workspace>,
) {
let project = workspace.project().clone();
if project.read(cx).is_remote() {
cx.propagate_action();
} else if let Some(buffer) = project
.update(cx, |project, cx| project.create_buffer("", None, cx))
.log_err()
{
workspace.split_item(
action.0,
Box::new(cx.add_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
cx,
);
}
}
pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
self.buffer.read(cx).replica_id()
}
pub fn leader_replica_id(&self) -> Option<ReplicaId> {
self.leader_replica_id
pub fn leader_peer_id(&self) -> Option<PeerId> {
self.leader_peer_id
}
pub fn buffer(&self) -> &ModelHandle<MultiBuffer> {
@@ -1702,6 +1734,14 @@ impl Editor {
self.mode
}
pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
self.collaboration_hub.as_deref()
}
pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
self.collaboration_hub = Some(hub);
}
pub fn set_placeholder_text(
&mut self,
placeholder_text: impl Into<Arc<str>>,
@@ -1778,26 +1818,13 @@ impl Editor {
cx.notify();
}
pub fn replica_id_map(&self) -> Option<&HashMap<ReplicaId, ReplicaId>> {
self.replica_id_mapping.as_ref()
}
pub fn set_replica_id_map(
&mut self,
mapping: Option<HashMap<ReplicaId, ReplicaId>>,
cx: &mut ViewContext<Self>,
) {
self.replica_id_mapping = mapping;
cx.notify();
}
fn selections_did_change(
&mut self,
local: bool,
old_cursor_position: &Anchor,
cx: &mut ViewContext<Self>,
) {
if self.focused && self.leader_replica_id.is_none() {
if self.focused && self.leader_peer_id.is_none() {
self.buffer.update(cx, |buffer, cx| {
buffer.set_active_selections(
&self.selections.disjoint_anchors(),
@@ -4632,7 +4659,13 @@ impl Editor {
}
pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
self.manipulate_text(cx, |text| text.to_case(Case::Title))
self.manipulate_text(cx, |text| {
// Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
// https://github.com/rutrum/convert-case/issues/16
text.split("\n")
.map(|line| line.to_case(Case::Title))
.join("\n")
})
}
pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
@@ -4648,7 +4681,13 @@ impl Editor {
_: &ConvertToUpperCamelCase,
cx: &mut ViewContext<Self>,
) {
self.manipulate_text(cx, |text| text.to_case(Case::UpperCamel))
self.manipulate_text(cx, |text| {
// Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
// https://github.com/rutrum/convert-case/issues/16
text.split("\n")
.map(|line| line.to_case(Case::UpperCamel))
.join("\n")
})
}
pub fn convert_to_lower_camel_case(
@@ -7136,7 +7175,7 @@ impl Editor {
);
});
if split {
workspace.split_item(Box::new(editor), cx);
workspace.split_item(SplitDirection::Right, Box::new(editor), cx);
} else {
workspace.add_item(Box::new(editor), cx);
}
@@ -8567,6 +8606,50 @@ impl Editor {
self.handle_input(text, cx);
}
pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
let Some(project) = self.project.as_ref() else {
return false;
};
let project = project.read(cx);
let mut supports = false;
self.buffer().read(cx).for_each_buffer(|buffer| {
if !supports {
supports = project
.language_servers_for_buffer(buffer.read(cx), cx)
.any(
|(_, server)| match server.capabilities().inlay_hint_provider {
Some(lsp::OneOf::Left(enabled)) => enabled,
Some(lsp::OneOf::Right(_)) => true,
None => false,
},
)
}
});
supports
}
}
pub trait CollaborationHub {
fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
fn user_participant_indices<'a>(
&self,
cx: &'a AppContext,
) -> &'a HashMap<u64, ParticipantIndex>;
}
impl CollaborationHub for ModelHandle<Project> {
fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
self.read(cx).collaborators()
}
fn user_participant_indices<'a>(
&self,
cx: &'a AppContext,
) -> &'a HashMap<u64, ParticipantIndex> {
self.read(cx).user_store().read(cx).participant_indices()
}
}
fn inlay_hint_settings(
@@ -8612,6 +8695,34 @@ fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot)
}
impl EditorSnapshot {
pub fn remote_selections_in_range<'a>(
&'a self,
range: &'a Range<Anchor>,
collaboration_hub: &dyn CollaborationHub,
cx: &'a AppContext,
) -> impl 'a + Iterator<Item = RemoteSelection> {
let participant_indices = collaboration_hub.user_participant_indices(cx);
let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
let collaborators_by_replica_id = collaborators_by_peer_id
.iter()
.map(|(_, collaborator)| (collaborator.replica_id, collaborator))
.collect::<HashMap<_, _>>();
self.buffer_snapshot
.remote_selections_in_range(range)
.filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
let collaborator = collaborators_by_replica_id.get(&replica_id)?;
let participant_index = participant_indices.get(&collaborator.user_id).copied();
Some(RemoteSelection {
replica_id,
selection,
cursor_shape,
line_mode,
participant_index,
peer_id: collaborator.peer_id,
})
})
}
pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
self.display_snapshot.buffer_snapshot.language_at(position)
}
@@ -8725,7 +8836,7 @@ impl View for Editor {
self.focused = true;
self.buffer.update(cx, |buffer, cx| {
buffer.finalize_last_transaction(cx);
if self.leader_replica_id.is_none() {
if self.leader_peer_id.is_none() {
buffer.set_active_selections(
&self.selections.disjoint_anchors(),
self.selections.line_mode,

View File

@@ -1429,7 +1429,7 @@ async fn test_scroll_page_up_page_down(cx: &mut gpui::TestAppContext) {
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 3.));
editor.scroll_screen(&ScrollAmount::Page(-0.5), cx);
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 2.));
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 1.));
editor.scroll_screen(&ScrollAmount::Page(0.5), cx);
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 3.));
});
@@ -2792,6 +2792,34 @@ async fn test_manipulate_text(cx: &mut TestAppContext) {
«hello worldˇ»
"});
// Test multiple line, single selection case
// Test code hack that covers the fact that to_case crate doesn't support '\n' as a word boundary
cx.set_state(indoc! {"
«The quick brown
fox jumps over
the lazy dogˇ»
"});
cx.update_editor(|e, cx| e.convert_to_title_case(&ConvertToTitleCase, cx));
cx.assert_editor_state(indoc! {"
«The Quick Brown
Fox Jumps Over
The Lazy Dogˇ»
"});
// Test multiple line, single selection case
// Test code hack that covers the fact that to_case crate doesn't support '\n' as a word boundary
cx.set_state(indoc! {"
«The quick brown
fox jumps over
the lazy dogˇ»
"});
cx.update_editor(|e, cx| e.convert_to_upper_camel_case(&ConvertToUpperCamelCase, cx));
cx.assert_editor_state(indoc! {"
«TheQuickBrown
FoxJumpsOver
TheLazyDogˇ»
"});
// From here on out, test more complex cases of manipulate_text()
// Test no selection case - should affect words cursors are in

View File

@@ -17,7 +17,6 @@ use crate::{
},
mouse_context_menu, EditorSettings, EditorStyle, GutterHover, UnfoldAt,
};
use clock::ReplicaId;
use collections::{BTreeMap, HashMap};
use git::diff::DiffHunkStatus;
use gpui::{
@@ -55,6 +54,7 @@ use std::{
sync::Arc,
};
use text::Point;
use theme::SelectionStyle;
use workspace::item::Item;
enum FoldMarkers {}
@@ -868,14 +868,7 @@ impl EditorElement {
let corner_radius = 0.15 * layout.position_map.line_height;
let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
for (replica_id, selections) in &layout.selections {
let replica_id = *replica_id;
let selection_style = if let Some(replica_id) = replica_id {
style.replica_selection_style(replica_id)
} else {
&style.absent_selection
};
for (selection_style, selections) in &layout.selections {
for selection in selections {
self.paint_highlighted_range(
selection.range.clone(),
@@ -2193,7 +2186,7 @@ impl Element<Editor> for EditorElement {
.anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
};
let mut selections: Vec<(Option<ReplicaId>, Vec<SelectionLayout>)> = Vec::new();
let mut selections: Vec<(SelectionStyle, Vec<SelectionLayout>)> = Vec::new();
let mut active_rows = BTreeMap::new();
let mut fold_ranges = Vec::new();
let is_singleton = editor.is_singleton(cx);
@@ -2219,35 +2212,6 @@ impl Element<Editor> for EditorElement {
}),
);
let mut remote_selections = HashMap::default();
for (replica_id, line_mode, cursor_shape, selection) in snapshot
.buffer_snapshot
.remote_selections_in_range(&(start_anchor..end_anchor))
{
let replica_id = if let Some(mapping) = &editor.replica_id_mapping {
mapping.get(&replica_id).copied()
} else {
Some(replica_id)
};
// The local selections match the leader's selections.
if replica_id.is_some() && replica_id == editor.leader_replica_id {
continue;
}
remote_selections
.entry(replica_id)
.or_insert(Vec::new())
.push(SelectionLayout::new(
selection,
line_mode,
cursor_shape,
&snapshot.display_snapshot,
false,
false,
));
}
selections.extend(remote_selections);
let mut newest_selection_head = None;
if editor.show_local_selections {
@@ -2282,19 +2246,58 @@ impl Element<Editor> for EditorElement {
layouts.push(layout);
}
// Render the local selections in the leader's color when following.
let local_replica_id = if let Some(leader_replica_id) = editor.leader_replica_id {
leader_replica_id
} else {
let replica_id = editor.replica_id(cx);
if let Some(mapping) = &editor.replica_id_mapping {
mapping.get(&replica_id).copied().unwrap_or(replica_id)
} else {
replica_id
}
};
selections.push((style.selection, layouts));
}
selections.push((Some(local_replica_id), layouts));
if let Some(collaboration_hub) = &editor.collaboration_hub {
// When following someone, render the local selections in their color.
if let Some(leader_id) = editor.leader_peer_id {
if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
if let Some(participant_index) = collaboration_hub
.user_participant_indices(cx)
.get(&collaborator.user_id)
{
if let Some((local_selection_style, _)) = selections.first_mut() {
*local_selection_style =
style.selection_style_for_room_participant(participant_index.0);
}
}
}
}
let mut remote_selections = HashMap::default();
for selection in snapshot.remote_selections_in_range(
&(start_anchor..end_anchor),
collaboration_hub.as_ref(),
cx,
) {
let selection_style = if let Some(participant_index) = selection.participant_index {
style.selection_style_for_room_participant(participant_index.0)
} else {
style.absent_selection
};
// Don't re-render the leader's selections, since the local selections
// match theirs.
if Some(selection.peer_id) == editor.leader_peer_id {
continue;
}
remote_selections
.entry(selection.replica_id)
.or_insert((selection_style, Vec::new()))
.1
.push(SelectionLayout::new(
selection.selection,
selection.line_mode,
selection.cursor_shape,
&snapshot.display_snapshot,
false,
false,
));
}
selections.extend(remote_selections.into_values());
}
let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
@@ -2686,7 +2689,7 @@ pub struct LayoutState {
blocks: Vec<BlockLayout>,
highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
selections: Vec<(Option<ReplicaId>, Vec<SelectionLayout>)>,
selections: Vec<(SelectionStyle, Vec<SelectionLayout>)>,
scrollbar_row_range: Range<f32>,
show_scrollbars: bool,
is_singleton: bool,

View File

@@ -8,12 +8,12 @@ use futures::FutureExt;
use gpui::{
actions,
elements::{Flex, MouseEventHandler, Padding, ParentElement, Text},
fonts::{HighlightStyle, Underline, Weight},
platform::{CursorStyle, MouseButton},
AnyElement, AppContext, CursorRegion, Element, ModelHandle, MouseRegion, Task, ViewContext,
AnyElement, AppContext, Element, ModelHandle, Task, ViewContext,
};
use language::{Bias, DiagnosticEntry, DiagnosticSeverity, Language, LanguageRegistry};
use project::{HoverBlock, HoverBlockKind, InlayHintLabelPart, Project};
use rich_text::{new_paragraph, render_code, render_markdown_mut, RichText};
use std::{ops::Range, sync::Arc, time::Duration};
use util::TryFutureExt;
@@ -346,158 +346,25 @@ fn show_hover(
}
fn render_blocks(
theme_id: usize,
blocks: &[HoverBlock],
language_registry: &Arc<LanguageRegistry>,
language: Option<&Arc<Language>>,
style: &EditorStyle,
) -> RenderedInfo {
let mut text = String::new();
let mut highlights = Vec::new();
let mut region_ranges = Vec::new();
let mut regions = Vec::new();
) -> RichText {
let mut data = RichText {
text: Default::default(),
highlights: Default::default(),
region_ranges: Default::default(),
regions: Default::default(),
};
for block in blocks {
match &block.kind {
HoverBlockKind::PlainText => {
new_paragraph(&mut text, &mut Vec::new());
text.push_str(&block.text);
new_paragraph(&mut data.text, &mut Vec::new());
data.text.push_str(&block.text);
}
HoverBlockKind::Markdown => {
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag};
let mut bold_depth = 0;
let mut italic_depth = 0;
let mut link_url = None;
let mut current_language = None;
let mut list_stack = Vec::new();
for event in Parser::new_ext(&block.text, Options::all()) {
let prev_len = text.len();
match event {
Event::Text(t) => {
if let Some(language) = &current_language {
render_code(
&mut text,
&mut highlights,
t.as_ref(),
language,
style,
);
} else {
text.push_str(t.as_ref());
let mut style = HighlightStyle::default();
if bold_depth > 0 {
style.weight = Some(Weight::BOLD);
}
if italic_depth > 0 {
style.italic = Some(true);
}
if let Some(link_url) = link_url.clone() {
region_ranges.push(prev_len..text.len());
regions.push(RenderedRegion {
link_url: Some(link_url),
code: false,
});
style.underline = Some(Underline {
thickness: 1.0.into(),
..Default::default()
});
}
if style != HighlightStyle::default() {
let mut new_highlight = true;
if let Some((last_range, last_style)) = highlights.last_mut() {
if last_range.end == prev_len && last_style == &style {
last_range.end = text.len();
new_highlight = false;
}
}
if new_highlight {
highlights.push((prev_len..text.len(), style));
}
}
}
}
Event::Code(t) => {
text.push_str(t.as_ref());
region_ranges.push(prev_len..text.len());
if link_url.is_some() {
highlights.push((
prev_len..text.len(),
HighlightStyle {
underline: Some(Underline {
thickness: 1.0.into(),
..Default::default()
}),
..Default::default()
},
));
}
regions.push(RenderedRegion {
code: true,
link_url: link_url.clone(),
});
}
Event::Start(tag) => match tag {
Tag::Paragraph => new_paragraph(&mut text, &mut list_stack),
Tag::Heading(_, _, _) => {
new_paragraph(&mut text, &mut list_stack);
bold_depth += 1;
}
Tag::CodeBlock(kind) => {
new_paragraph(&mut text, &mut list_stack);
current_language = if let CodeBlockKind::Fenced(language) = kind {
language_registry
.language_for_name(language.as_ref())
.now_or_never()
.and_then(Result::ok)
} else {
language.cloned()
}
}
Tag::Emphasis => italic_depth += 1,
Tag::Strong => bold_depth += 1,
Tag::Link(_, url, _) => link_url = Some(url.to_string()),
Tag::List(number) => {
list_stack.push((number, false));
}
Tag::Item => {
let len = list_stack.len();
if let Some((list_number, has_content)) = list_stack.last_mut() {
*has_content = false;
if !text.is_empty() && !text.ends_with('\n') {
text.push('\n');
}
for _ in 0..len - 1 {
text.push_str(" ");
}
if let Some(number) = list_number {
text.push_str(&format!("{}. ", number));
*number += 1;
*has_content = false;
} else {
text.push_str("- ");
}
}
}
_ => {}
},
Event::End(tag) => match tag {
Tag::Heading(_, _, _) => bold_depth -= 1,
Tag::CodeBlock(_) => current_language = None,
Tag::Emphasis => italic_depth -= 1,
Tag::Strong => bold_depth -= 1,
Tag::Link(_, _, _) => link_url = None,
Tag::List(_) => drop(list_stack.pop()),
_ => {}
},
Event::HardBreak => text.push('\n'),
Event::SoftBreak => text.push(' '),
_ => {}
}
}
render_markdown_mut(&block.text, language_registry, language, &mut data)
}
HoverBlockKind::Code { language } => {
if let Some(language) = language_registry
@@ -505,62 +372,17 @@ fn render_blocks(
.now_or_never()
.and_then(Result::ok)
{
render_code(&mut text, &mut highlights, &block.text, &language, style);
render_code(&mut data.text, &mut data.highlights, &block.text, &language);
} else {
text.push_str(&block.text);
data.text.push_str(&block.text);
}
}
}
}
RenderedInfo {
theme_id,
text: text.trim().to_string(),
highlights,
region_ranges,
regions,
}
}
data.text = data.text.trim().to_string();
fn render_code(
text: &mut String,
highlights: &mut Vec<(Range<usize>, HighlightStyle)>,
content: &str,
language: &Arc<Language>,
style: &EditorStyle,
) {
let prev_len = text.len();
text.push_str(content);
for (range, highlight_id) in language.highlight_text(&content.into(), 0..content.len()) {
if let Some(style) = highlight_id.style(&style.syntax) {
highlights.push((prev_len + range.start..prev_len + range.end, style));
}
}
}
fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
let mut is_subsequent_paragraph_of_list = false;
if let Some((_, has_content)) = list_stack.last_mut() {
if *has_content {
is_subsequent_paragraph_of_list = true;
} else {
*has_content = true;
return;
}
}
if !text.is_empty() {
if !text.ends_with('\n') {
text.push('\n');
}
text.push('\n');
}
for _ in 0..list_stack.len().saturating_sub(1) {
text.push_str(" ");
}
if is_subsequent_paragraph_of_list {
text.push_str(" ");
}
data
}
#[derive(Default)]
@@ -623,22 +445,7 @@ pub struct InfoPopover {
symbol_range: RangeInEditor,
pub blocks: Vec<HoverBlock>,
language: Option<Arc<Language>>,
rendered_content: Option<RenderedInfo>,
}
#[derive(Debug, Clone)]
struct RenderedInfo {
theme_id: usize,
text: String,
highlights: Vec<(Range<usize>, HighlightStyle)>,
region_ranges: Vec<Range<usize>>,
regions: Vec<RenderedRegion>,
}
#[derive(Debug, Clone)]
struct RenderedRegion {
code: bool,
link_url: Option<String>,
rendered_content: Option<RichText>,
}
impl InfoPopover {
@@ -647,63 +454,24 @@ impl InfoPopover {
style: &EditorStyle,
cx: &mut ViewContext<Editor>,
) -> AnyElement<Editor> {
if let Some(rendered) = &self.rendered_content {
if rendered.theme_id != style.theme_id {
self.rendered_content = None;
}
}
let rendered_content = self.rendered_content.get_or_insert_with(|| {
render_blocks(
style.theme_id,
&self.blocks,
self.project.read(cx).languages(),
self.language.as_ref(),
style,
)
});
MouseEventHandler::new::<InfoPopover, _>(0, cx, |_, cx| {
let mut region_id = 0;
let view_id = cx.view_id();
MouseEventHandler::new::<InfoPopover, _>(0, cx, move |_, cx| {
let code_span_background_color = style.document_highlight_read_background;
let regions = rendered_content.regions.clone();
Flex::column()
.scrollable::<HoverBlock>(1, None, cx)
.with_child(
Text::new(rendered_content.text.clone(), style.text.clone())
.with_highlights(rendered_content.highlights.clone())
.with_custom_runs(
rendered_content.region_ranges.clone(),
move |ix, bounds, cx| {
region_id += 1;
let region = regions[ix].clone();
if let Some(url) = region.link_url {
cx.scene().push_cursor_region(CursorRegion {
bounds,
style: CursorStyle::PointingHand,
});
cx.scene().push_mouse_region(
MouseRegion::new::<Self>(view_id, region_id, bounds)
.on_click::<Editor, _>(
MouseButton::Left,
move |_, _, cx| cx.platform().open_url(&url),
),
);
}
if region.code {
cx.scene().push_quad(gpui::Quad {
bounds,
background: Some(code_span_background_color),
border: Default::default(),
corner_radii: (2.0).into(),
});
}
},
)
.with_soft_wrap(true),
)
.with_child(rendered_content.element(
style.syntax.clone(),
style.text.clone(),
code_span_background_color,
cx,
))
.contained()
.with_style(style.hover_popover.container)
})
@@ -799,11 +567,12 @@ mod tests {
InlayId,
};
use collections::BTreeSet;
use gpui::fonts::Weight;
use gpui::fonts::{HighlightStyle, Underline, Weight};
use indoc::indoc;
use language::{language_settings::InlayHintSettings, Diagnostic, DiagnosticSet};
use lsp::LanguageServerId;
use project::{HoverBlock, HoverBlockKind};
use rich_text::Highlight;
use smol::stream::StreamExt;
use unindent::Unindent;
use util::test::marked_text_ranges;
@@ -1014,7 +783,7 @@ mod tests {
.await;
cx.condition(|editor, _| editor.hover_state.visible()).await;
cx.editor(|editor, cx| {
cx.editor(|editor, _| {
let blocks = editor.hover_state.info_popover.clone().unwrap().blocks;
assert_eq!(
blocks,
@@ -1024,8 +793,7 @@ mod tests {
}],
);
let style = editor.style(cx);
let rendered = render_blocks(0, &blocks, &Default::default(), None, &style);
let rendered = render_blocks(&blocks, &Default::default(), None);
assert_eq!(
rendered.text,
code_str.trim(),
@@ -1217,7 +985,7 @@ mod tests {
expected_styles,
} in &rows[0..]
{
let rendered = render_blocks(0, &blocks, &Default::default(), None, &style);
let rendered = render_blocks(&blocks, &Default::default(), None);
let (expected_text, ranges) = marked_text_ranges(expected_marked_text, false);
let expected_highlights = ranges
@@ -1228,8 +996,21 @@ mod tests {
rendered.text, expected_text,
"wrong text for input {blocks:?}"
);
let rendered_highlights: Vec<_> = rendered
.highlights
.iter()
.filter_map(|(range, highlight)| {
let style = match highlight {
Highlight::Id(id) => id.style(&style.syntax)?,
Highlight::Highlight(style) => style.clone(),
};
Some((range.clone(), style))
})
.collect();
assert_eq!(
rendered.highlights, expected_highlights,
rendered_highlights, expected_highlights,
"wrong highlights for input {blocks:?}"
);
}

View File

@@ -17,7 +17,7 @@ use language::{
SelectionGoal,
};
use project::{search::SearchQuery, FormatTrigger, Item as _, Project, ProjectPath};
use rpc::proto::{self, update_view};
use rpc::proto::{self, update_view, PeerId};
use smallvec::SmallVec;
use std::{
borrow::Cow,
@@ -156,13 +156,9 @@ impl FollowableItem for Editor {
}))
}
fn set_leader_replica_id(
&mut self,
leader_replica_id: Option<u16>,
cx: &mut ViewContext<Self>,
) {
self.leader_replica_id = leader_replica_id;
if self.leader_replica_id.is_some() {
fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
self.leader_peer_id = leader_peer_id;
if self.leader_peer_id.is_some() {
self.buffer.update(cx, |buffer, cx| {
buffer.remove_active_selections(cx);
});
@@ -309,6 +305,10 @@ impl FollowableItem for Editor {
_ => false,
}
}
fn is_project_item(&self, _cx: &AppContext) -> bool {
true
}
}
async fn update_editor_from_message(
@@ -995,8 +995,10 @@ impl SearchableItem for Editor {
joined_chunks.into()
};
if let Some(replacement) = query.replacement(&text) {
self.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
if let Some(replacement) = query.replacement_for(&text) {
self.transact(cx, |this, cx| {
this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
});
}
}
fn match_index_for_direction(

View File

@@ -15,9 +15,13 @@ impl ScrollAmount {
Self::Line(count) => *count,
Self::Page(count) => editor
.visible_line_count()
// subtract one to leave an anchor line
// round towards zero (so page-up and page-down are symmetric)
.map(|l| (l * count).trunc() - count.signum())
.map(|mut l| {
// for full pages subtract one to leave an anchor line
if count.abs() == 1.0 {
l -= 1.0
}
(l * count).trunc()
})
.unwrap_or(0.),
}
}

View File

@@ -3,8 +3,8 @@ use crate::{
};
use futures::Future;
use gpui::{
keymap_matcher::Keystroke, AnyWindowHandle, AppContext, ContextHandle, ModelContext,
ViewContext, ViewHandle,
executor::Foreground, keymap_matcher::Keystroke, AnyWindowHandle, AppContext, ContextHandle,
ModelContext, ViewContext, ViewHandle,
};
use indoc::indoc;
use language::{Buffer, BufferSnapshot};
@@ -114,6 +114,7 @@ impl<'a> EditorTestContext<'a> {
let keystroke = Keystroke::parse(keystroke_text).unwrap();
self.cx.dispatch_keystroke(self.window, keystroke, false);
keystroke_under_test_handle
}
@@ -126,6 +127,16 @@ impl<'a> EditorTestContext<'a> {
for keystroke_text in keystroke_texts.into_iter() {
self.simulate_keystroke(keystroke_text);
}
// it is common for keyboard shortcuts to kick off async actions, so this ensures that they are complete
// before returning.
// NOTE: we don't do this in simulate_keystroke() because a possible cause of bugs is that typing too
// quickly races with async actions.
if let Foreground::Deterministic { cx_id: _, executor } = self.cx.foreground().as_ref() {
executor.run_until_parked();
} else {
unreachable!();
}
keystrokes_under_test_handle
}

View File

@@ -33,7 +33,7 @@ lazy_static.workspace = true
postage.workspace = true
serde.workspace = true
serde_derive.workspace = true
sysinfo = "0.27.1"
sysinfo.workspace = true
tree-sitter-markdown = { git = "https://github.com/MDeiml/tree-sitter-markdown", rev = "330ecab87a3e3a7211ac69bbadc19eabecdb1cca" }
urlencoding = "2.1.2"

View File

@@ -10,6 +10,7 @@ doctest = false
[dependencies]
editor = { path = "../editor" }
collections = { path = "../collections" }
fuzzy = { path = "../fuzzy" }
gpui = { path = "../gpui" }
menu = { path = "../menu" }

View File

@@ -1,5 +1,6 @@
use collections::HashMap;
use editor::{scroll::autoscroll::Autoscroll, Bias, Editor};
use fuzzy::PathMatch;
use fuzzy::{CharBag, PathMatch, PathMatchCandidate};
use gpui::{
actions, elements::*, AppContext, ModelHandle, MouseState, Task, ViewContext, WeakViewHandle,
};
@@ -32,38 +33,124 @@ pub struct FileFinderDelegate {
history_items: Vec<FoundPath>,
}
#[derive(Debug)]
enum Matches {
History(Vec<FoundPath>),
Search(Vec<PathMatch>),
#[derive(Debug, Default)]
struct Matches {
history: Vec<(FoundPath, Option<PathMatch>)>,
search: Vec<PathMatch>,
}
#[derive(Debug)]
enum Match<'a> {
History(&'a FoundPath),
History(&'a FoundPath, Option<&'a PathMatch>),
Search(&'a PathMatch),
}
impl Matches {
fn len(&self) -> usize {
match self {
Self::History(items) => items.len(),
Self::Search(items) => items.len(),
}
self.history.len() + self.search.len()
}
fn get(&self, index: usize) -> Option<Match<'_>> {
match self {
Self::History(items) => items.get(index).map(Match::History),
Self::Search(items) => items.get(index).map(Match::Search),
if index < self.history.len() {
self.history
.get(index)
.map(|(path, path_match)| Match::History(path, path_match.as_ref()))
} else {
self.search
.get(index - self.history.len())
.map(Match::Search)
}
}
fn push_new_matches(
&mut self,
history_items: &Vec<FoundPath>,
query: &PathLikeWithPosition<FileSearchQuery>,
mut new_search_matches: Vec<PathMatch>,
extend_old_matches: bool,
) {
let matching_history_paths = matching_history_item_paths(history_items, query);
new_search_matches
.retain(|path_match| !matching_history_paths.contains_key(&path_match.path));
let history_items_to_show = history_items
.iter()
.filter_map(|history_item| {
Some((
history_item.clone(),
Some(
matching_history_paths
.get(&history_item.project.path)?
.clone(),
),
))
})
.collect::<Vec<_>>();
self.history = history_items_to_show;
if extend_old_matches {
self.search
.retain(|path_match| !matching_history_paths.contains_key(&path_match.path));
util::extend_sorted(
&mut self.search,
new_search_matches.into_iter(),
100,
|a, b| b.cmp(a),
)
} else {
self.search = new_search_matches;
}
}
}
impl Default for Matches {
fn default() -> Self {
Self::History(Vec::new())
fn matching_history_item_paths(
history_items: &Vec<FoundPath>,
query: &PathLikeWithPosition<FileSearchQuery>,
) -> HashMap<Arc<Path>, PathMatch> {
let history_items_by_worktrees = history_items
.iter()
.filter_map(|found_path| {
let candidate = PathMatchCandidate {
path: &found_path.project.path,
// Only match history items names, otherwise their paths may match too many queries, producing false positives.
// E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
// it would be shown first always, despite the latter being a better match.
char_bag: CharBag::from_iter(
found_path
.project
.path
.file_name()?
.to_string_lossy()
.to_lowercase()
.chars(),
),
};
Some((found_path.project.worktree_id, candidate))
})
.fold(
HashMap::default(),
|mut candidates, (worktree_id, new_candidate)| {
candidates
.entry(worktree_id)
.or_insert_with(Vec::new)
.push(new_candidate);
candidates
},
);
let mut matching_history_paths = HashMap::default();
for (worktree, candidates) in history_items_by_worktrees {
let max_results = candidates.len() + 1;
matching_history_paths.extend(
fuzzy::match_fixed_path_set(
candidates,
worktree.to_usize(),
query.path_like.path_query(),
false,
max_results,
)
.into_iter()
.map(|path_match| (Arc::clone(&path_match.path), path_match)),
);
}
matching_history_paths
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -81,66 +168,96 @@ impl FoundPath {
actions!(file_finder, [Toggle]);
pub fn init(cx: &mut AppContext) {
cx.add_action(toggle_file_finder);
cx.add_action(toggle_or_cycle_file_finder);
FileFinder::init(cx);
}
const MAX_RECENT_SELECTIONS: usize = 20;
fn toggle_file_finder(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
workspace.toggle_modal(cx, |workspace, cx| {
let project = workspace.project().read(cx);
fn toggle_or_cycle_file_finder(
workspace: &mut Workspace,
_: &Toggle,
cx: &mut ViewContext<Workspace>,
) {
match workspace.modal::<FileFinder>() {
Some(file_finder) => file_finder.update(cx, |file_finder, cx| {
let current_index = file_finder.delegate().selected_index();
file_finder.select_next(&menu::SelectNext, cx);
let new_index = file_finder.delegate().selected_index();
if current_index == new_index {
file_finder.select_first(&menu::SelectFirst, cx);
}
}),
None => {
workspace.toggle_modal(cx, |workspace, cx| {
let project = workspace.project().read(cx);
let currently_opened_path = workspace
.active_item(cx)
.and_then(|item| item.project_path(cx))
.map(|project_path| {
let abs_path = project
.worktree_for_id(project_path.worktree_id, cx)
.map(|worktree| worktree.read(cx).abs_path().join(&project_path.path));
FoundPath::new(project_path, abs_path)
});
let currently_opened_path = workspace
.active_item(cx)
.and_then(|item| item.project_path(cx))
.map(|project_path| {
let abs_path = project
.worktree_for_id(project_path.worktree_id, cx)
.map(|worktree| worktree.read(cx).abs_path().join(&project_path.path));
FoundPath::new(project_path, abs_path)
});
// if exists, bubble the currently opened path to the top
let history_items = currently_opened_path
.clone()
.into_iter()
.chain(
workspace
.recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx)
// if exists, bubble the currently opened path to the top
let history_items = currently_opened_path
.clone()
.into_iter()
.filter(|(history_path, _)| {
Some(history_path)
!= currently_opened_path
.as_ref()
.map(|found_path| &found_path.project)
})
.filter(|(_, history_abs_path)| {
history_abs_path.as_ref()
!= currently_opened_path
.as_ref()
.and_then(|found_path| found_path.absolute.as_ref())
})
.map(|(history_path, abs_path)| FoundPath::new(history_path, abs_path)),
)
.collect();
.chain(
workspace
.recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx)
.into_iter()
.filter(|(history_path, _)| {
Some(history_path)
!= currently_opened_path
.as_ref()
.map(|found_path| &found_path.project)
})
.filter(|(_, history_abs_path)| {
history_abs_path.as_ref()
!= currently_opened_path
.as_ref()
.and_then(|found_path| found_path.absolute.as_ref())
})
.filter(|(_, history_abs_path)| match history_abs_path {
Some(abs_path) => history_file_exists(abs_path),
None => true,
})
.map(|(history_path, abs_path)| FoundPath::new(history_path, abs_path)),
)
.collect();
let project = workspace.project().clone();
let workspace = cx.handle().downgrade();
let finder = cx.add_view(|cx| {
Picker::new(
FileFinderDelegate::new(
workspace,
project,
currently_opened_path,
history_items,
cx,
),
cx,
)
});
finder
});
let project = workspace.project().clone();
let workspace = cx.handle().downgrade();
let finder = cx.add_view(|cx| {
Picker::new(
FileFinderDelegate::new(
workspace,
project,
currently_opened_path,
history_items,
cx,
),
cx,
)
});
finder
});
}
}
}
#[cfg(not(test))]
fn history_file_exists(abs_path: &PathBuf) -> bool {
abs_path.exists()
}
#[cfg(test)]
fn history_file_exists(abs_path: &PathBuf) -> bool {
!abs_path.ends_with("nonexistent.rs")
}
pub enum Event {
@@ -255,24 +372,14 @@ impl FileFinderDelegate {
) {
if search_id >= self.latest_search_id {
self.latest_search_id = search_id;
if self.latest_search_did_cancel
let extend_old_matches = self.latest_search_did_cancel
&& Some(query.path_like.path_query())
== self
.latest_search_query
.as_ref()
.map(|query| query.path_like.path_query())
{
match &mut self.matches {
Matches::History(_) => self.matches = Matches::Search(matches),
Matches::Search(search_matches) => {
util::extend_sorted(search_matches, matches.into_iter(), 100, |a, b| {
b.cmp(a)
})
}
}
} else {
self.matches = Matches::Search(matches);
}
.map(|query| query.path_like.path_query());
self.matches
.push_new_matches(&self.history_items, &query, matches, extend_old_matches);
self.latest_search_query = Some(query);
self.latest_search_did_cancel = did_cancel;
cx.notify();
@@ -286,7 +393,7 @@ impl FileFinderDelegate {
ix: usize,
) -> (String, Vec<usize>, String, Vec<usize>) {
let (file_name, file_name_positions, full_path, full_path_positions) = match path_match {
Match::History(found_path) => {
Match::History(found_path, found_path_match) => {
let worktree_id = found_path.project.worktree_id;
let project_relative_path = &found_path.project.path;
let has_worktree = self
@@ -318,14 +425,22 @@ impl FileFinderDelegate {
path = Arc::from(absolute_path.as_path());
}
}
self.labels_for_path_match(&PathMatch {
let mut path_match = PathMatch {
score: ix as f64,
positions: Vec::new(),
worktree_id: worktree_id.to_usize(),
path,
path_prefix: "".into(),
distance_to_relative_ancestor: usize::MAX,
})
};
if let Some(found_path_match) = found_path_match {
path_match
.positions
.extend(found_path_match.positions.iter())
}
self.labels_for_path_match(&path_match)
}
Match::Search(path_match) => self.labels_for_path_match(path_match),
};
@@ -406,23 +521,21 @@ impl PickerDelegate for FileFinderDelegate {
if raw_query.is_empty() {
let project = self.project.read(cx);
self.latest_search_id = post_inc(&mut self.search_count);
self.matches = Matches::History(
self.history_items
self.matches = Matches {
history: self
.history_items
.iter()
.filter(|history_item| {
project
.worktree_for_id(history_item.project.worktree_id, cx)
.is_some()
|| (project.is_local()
&& history_item
.absolute
.as_ref()
.filter(|abs_path| abs_path.exists())
.is_some())
|| (project.is_local() && history_item.absolute.is_some())
})
.cloned()
.map(|p| (p, None))
.collect(),
);
search: Vec::new(),
};
cx.notify();
Task::ready(())
} else {
@@ -454,7 +567,7 @@ impl PickerDelegate for FileFinderDelegate {
}
};
match m {
Match::History(history_match) => {
Match::History(history_match, _) => {
let worktree_id = history_match.project.worktree_id;
if workspace
.project()
@@ -866,11 +979,11 @@ mod tests {
finder.update(cx, |finder, cx| {
let delegate = finder.delegate_mut();
let matches = match &delegate.matches {
Matches::Search(path_matches) => path_matches,
_ => panic!("Search matches expected"),
}
.clone();
assert!(
delegate.matches.history.is_empty(),
"Search matches expected"
);
let matches = delegate.matches.search.clone();
// Simulate a search being cancelled after the time limit,
// returning only a subset of the matches that would have been found.
@@ -893,12 +1006,11 @@ mod tests {
cx,
);
match &delegate.matches {
Matches::Search(new_matches) => {
assert_eq!(new_matches.as_slice(), &matches[0..4])
}
_ => panic!("Search matches expected"),
};
assert!(
delegate.matches.history.is_empty(),
"Search matches expected"
);
assert_eq!(delegate.matches.search.as_slice(), &matches[0..4]);
});
}
@@ -1006,10 +1118,11 @@ mod tests {
cx.read(|cx| {
let finder = finder.read(cx);
let delegate = finder.delegate();
let matches = match &delegate.matches {
Matches::Search(path_matches) => path_matches,
_ => panic!("Search matches expected"),
};
assert!(
delegate.matches.history.is_empty(),
"Search matches expected"
);
let matches = delegate.matches.search.clone();
assert_eq!(matches.len(), 1);
let (file_name, file_name_positions, full_path, full_path_positions) =
@@ -1088,10 +1201,11 @@ mod tests {
finder.read_with(cx, |f, _| {
let delegate = f.delegate();
let matches = match &delegate.matches {
Matches::Search(path_matches) => path_matches,
_ => panic!("Search matches expected"),
};
assert!(
delegate.matches.history.is_empty(),
"Search matches expected"
);
let matches = delegate.matches.search.clone();
assert_eq!(matches[0].path.as_ref(), Path::new("dir2/a.txt"));
assert_eq!(matches[1].path.as_ref(), Path::new("dir1/a.txt"));
});
@@ -1459,6 +1573,451 @@ mod tests {
);
}
#[gpui::test]
async fn test_toggle_panel_new_selections(
deterministic: Arc<gpui::executor::Deterministic>,
cx: &mut gpui::TestAppContext,
) {
let app_state = init_test(cx);
app_state
.fs
.as_fake()
.insert_tree(
"/src",
json!({
"test": {
"first.rs": "// First Rust file",
"second.rs": "// Second Rust file",
"third.rs": "// Third Rust file",
}
}),
)
.await;
let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
let window = cx.add_window(|cx| Workspace::test_new(project, cx));
let workspace = window.root(cx);
// generate some history to select from
open_close_queried_buffer(
"fir",
1,
"first.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
open_close_queried_buffer(
"sec",
1,
"second.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
open_close_queried_buffer(
"thi",
1,
"third.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
let current_history = open_close_queried_buffer(
"sec",
1,
"second.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
for expected_selected_index in 0..current_history.len() {
cx.dispatch_action(window.into(), Toggle);
let selected_index = cx.read(|cx| {
workspace
.read(cx)
.modal::<FileFinder>()
.unwrap()
.read(cx)
.delegate()
.selected_index()
});
assert_eq!(
selected_index, expected_selected_index,
"Should select the next item in the history"
);
}
cx.dispatch_action(window.into(), Toggle);
let selected_index = cx.read(|cx| {
workspace
.read(cx)
.modal::<FileFinder>()
.unwrap()
.read(cx)
.delegate()
.selected_index()
});
assert_eq!(
selected_index, 0,
"Should wrap around the history and start all over"
);
}
#[gpui::test]
async fn test_search_preserves_history_items(
deterministic: Arc<gpui::executor::Deterministic>,
cx: &mut gpui::TestAppContext,
) {
let app_state = init_test(cx);
app_state
.fs
.as_fake()
.insert_tree(
"/src",
json!({
"test": {
"first.rs": "// First Rust file",
"second.rs": "// Second Rust file",
"third.rs": "// Third Rust file",
"fourth.rs": "// Fourth Rust file",
}
}),
)
.await;
let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
let window = cx.add_window(|cx| Workspace::test_new(project, cx));
let workspace = window.root(cx);
let worktree_id = cx.read(|cx| {
let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
assert_eq!(worktrees.len(), 1,);
WorktreeId::from_usize(worktrees[0].id())
});
// generate some history to select from
open_close_queried_buffer(
"fir",
1,
"first.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
open_close_queried_buffer(
"sec",
1,
"second.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
open_close_queried_buffer(
"thi",
1,
"third.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
open_close_queried_buffer(
"sec",
1,
"second.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
cx.dispatch_action(window.into(), Toggle);
let first_query = "f";
let finder = cx.read(|cx| workspace.read(cx).modal::<FileFinder>().unwrap());
finder
.update(cx, |finder, cx| {
finder
.delegate_mut()
.update_matches(first_query.to_string(), cx)
})
.await;
finder.read_with(cx, |finder, _| {
let delegate = finder.delegate();
assert_eq!(delegate.matches.history.len(), 1, "Only one history item contains {first_query}, it should be present and others should be filtered out");
let history_match = delegate.matches.history.first().unwrap();
assert!(history_match.1.is_some(), "Should have path matches for history items after querying");
assert_eq!(history_match.0, FoundPath::new(
ProjectPath {
worktree_id,
path: Arc::from(Path::new("test/first.rs")),
},
Some(PathBuf::from("/src/test/first.rs"))
));
assert_eq!(delegate.matches.search.len(), 1, "Only one non-history item contains {first_query}, it should be present");
assert_eq!(delegate.matches.search.first().unwrap().path.as_ref(), Path::new("test/fourth.rs"));
});
let second_query = "fsdasdsa";
let finder = cx.read(|cx| workspace.read(cx).modal::<FileFinder>().unwrap());
finder
.update(cx, |finder, cx| {
finder
.delegate_mut()
.update_matches(second_query.to_string(), cx)
})
.await;
finder.read_with(cx, |finder, _| {
let delegate = finder.delegate();
assert!(
delegate.matches.history.is_empty(),
"No history entries should match {second_query}"
);
assert!(
delegate.matches.search.is_empty(),
"No search entries should match {second_query}"
);
});
let first_query_again = first_query;
let finder = cx.read(|cx| workspace.read(cx).modal::<FileFinder>().unwrap());
finder
.update(cx, |finder, cx| {
finder
.delegate_mut()
.update_matches(first_query_again.to_string(), cx)
})
.await;
finder.read_with(cx, |finder, _| {
let delegate = finder.delegate();
assert_eq!(delegate.matches.history.len(), 1, "Only one history item contains {first_query_again}, it should be present and others should be filtered out, even after non-matching query");
let history_match = delegate.matches.history.first().unwrap();
assert!(history_match.1.is_some(), "Should have path matches for history items after querying");
assert_eq!(history_match.0, FoundPath::new(
ProjectPath {
worktree_id,
path: Arc::from(Path::new("test/first.rs")),
},
Some(PathBuf::from("/src/test/first.rs"))
));
assert_eq!(delegate.matches.search.len(), 1, "Only one non-history item contains {first_query_again}, it should be present, even after non-matching query");
assert_eq!(delegate.matches.search.first().unwrap().path.as_ref(), Path::new("test/fourth.rs"));
});
}
#[gpui::test]
async fn test_history_items_vs_very_good_external_match(
deterministic: Arc<gpui::executor::Deterministic>,
cx: &mut gpui::TestAppContext,
) {
let app_state = init_test(cx);
app_state
.fs
.as_fake()
.insert_tree(
"/src",
json!({
"collab_ui": {
"first.rs": "// First Rust file",
"second.rs": "// Second Rust file",
"third.rs": "// Third Rust file",
"collab_ui.rs": "// Fourth Rust file",
}
}),
)
.await;
let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
let window = cx.add_window(|cx| Workspace::test_new(project, cx));
let workspace = window.root(cx);
// generate some history to select from
open_close_queried_buffer(
"fir",
1,
"first.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
open_close_queried_buffer(
"sec",
1,
"second.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
open_close_queried_buffer(
"thi",
1,
"third.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
open_close_queried_buffer(
"sec",
1,
"second.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
cx.dispatch_action(window.into(), Toggle);
let query = "collab_ui";
let finder = cx.read(|cx| workspace.read(cx).modal::<FileFinder>().unwrap());
finder
.update(cx, |finder, cx| {
finder.delegate_mut().update_matches(query.to_string(), cx)
})
.await;
finder.read_with(cx, |finder, _| {
let delegate = finder.delegate();
assert!(
delegate.matches.history.is_empty(),
"History items should not math query {query}, they should be matched by name only"
);
let search_entries = delegate
.matches
.search
.iter()
.map(|path_match| path_match.path.to_path_buf())
.collect::<Vec<_>>();
assert_eq!(
search_entries,
vec![
PathBuf::from("collab_ui/collab_ui.rs"),
PathBuf::from("collab_ui/third.rs"),
PathBuf::from("collab_ui/first.rs"),
PathBuf::from("collab_ui/second.rs"),
],
"Despite all search results having the same directory name, the most matching one should be on top"
);
});
}
#[gpui::test]
async fn test_nonexistent_history_items_not_shown(
deterministic: Arc<gpui::executor::Deterministic>,
cx: &mut gpui::TestAppContext,
) {
let app_state = init_test(cx);
app_state
.fs
.as_fake()
.insert_tree(
"/src",
json!({
"test": {
"first.rs": "// First Rust file",
"nonexistent.rs": "// Second Rust file",
"third.rs": "// Third Rust file",
}
}),
)
.await;
let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
let window = cx.add_window(|cx| Workspace::test_new(project, cx));
let workspace = window.root(cx);
// generate some history to select from
open_close_queried_buffer(
"fir",
1,
"first.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
open_close_queried_buffer(
"non",
1,
"nonexistent.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
open_close_queried_buffer(
"thi",
1,
"third.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
open_close_queried_buffer(
"fir",
1,
"first.rs",
window.into(),
&workspace,
&deterministic,
cx,
)
.await;
cx.dispatch_action(window.into(), Toggle);
let query = "rs";
let finder = cx.read(|cx| workspace.read(cx).modal::<FileFinder>().unwrap());
finder
.update(cx, |finder, cx| {
finder.delegate_mut().update_matches(query.to_string(), cx)
})
.await;
finder.read_with(cx, |finder, _| {
let delegate = finder.delegate();
let history_entries = delegate
.matches
.history
.iter()
.map(|(_, path_match)| path_match.as_ref().expect("should have a path match").path.to_path_buf())
.collect::<Vec<_>>();
assert_eq!(
history_entries,
vec![
PathBuf::from("test/first.rs"),
PathBuf::from("test/third.rs"),
],
"Should have all opened files in the history, except the ones that do not exist on disk"
);
});
}
async fn open_close_queried_buffer(
input: &str,
expected_matches: usize,
@@ -1528,13 +2087,8 @@ mod tests {
let active_pane = cx.read(|cx| workspace.read(cx).active_pane().clone());
active_pane
.update(cx, |pane, cx| {
pane.close_active_item(
&workspace::CloseActiveItem {
save_behavior: None,
},
cx,
)
.unwrap()
pane.close_active_item(&workspace::CloseActiveItem { save_intent: None }, cx)
.unwrap()
})
.await
.unwrap();

View File

@@ -9,8 +9,6 @@ path = "src/fs.rs"
[dependencies]
collections = { path = "../collections" }
gpui = { path = "../gpui" }
lsp = { path = "../lsp" }
rope = { path = "../rope" }
text = { path = "../text" }
util = { path = "../util" }
@@ -34,8 +32,10 @@ log.workspace = true
libc = "0.2"
time.workspace = true
gpui = { path = "../gpui", optional = true}
[dev-dependencies]
gpui = { path = "../gpui", features = ["test-support"] }
[features]
test-support = []
test-support = ["gpui/test-support"]

View File

@@ -93,33 +93,6 @@ pub struct Metadata {
pub is_dir: bool,
}
impl From<lsp::CreateFileOptions> for CreateOptions {
fn from(options: lsp::CreateFileOptions) -> Self {
Self {
overwrite: options.overwrite.unwrap_or(false),
ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
}
}
}
impl From<lsp::RenameFileOptions> for RenameOptions {
fn from(options: lsp::RenameFileOptions) -> Self {
Self {
overwrite: options.overwrite.unwrap_or(false),
ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
}
}
}
impl From<lsp::DeleteFileOptions> for RemoveOptions {
fn from(options: lsp::DeleteFileOptions) -> Self {
Self {
recursive: options.recursive.unwrap_or(false),
ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
}
}
}
pub struct RealFs;
#[async_trait::async_trait]
@@ -507,7 +480,7 @@ impl FakeFs {
state.emit_event(&[path]);
}
fn write_file_internal(&self, path: impl AsRef<Path>, content: String) -> Result<()> {
pub fn write_file_internal(&self, path: impl AsRef<Path>, content: String) -> Result<()> {
let mut state = self.state.lock();
let path = path.as_ref();
let inode = state.next_inode;

View File

@@ -4,5 +4,7 @@ mod paths;
mod strings;
pub use char_bag::CharBag;
pub use paths::{match_path_sets, PathMatch, PathMatchCandidate, PathMatchCandidateSet};
pub use paths::{
match_fixed_path_set, match_path_sets, PathMatch, PathMatchCandidate, PathMatchCandidateSet,
};
pub use strings::{match_strings, StringMatch, StringMatchCandidate};

View File

@@ -441,7 +441,7 @@ mod tests {
score,
worktree_id: 0,
positions: Vec::new(),
path: candidate.path.clone(),
path: Arc::from(candidate.path),
path_prefix: "".into(),
distance_to_relative_ancestor: usize::MAX,
},

View File

@@ -14,7 +14,7 @@ use crate::{
#[derive(Clone, Debug)]
pub struct PathMatchCandidate<'a> {
pub path: &'a Arc<Path>,
pub path: &'a Path,
pub char_bag: CharBag,
}
@@ -90,6 +90,44 @@ impl Ord for PathMatch {
}
}
pub fn match_fixed_path_set(
candidates: Vec<PathMatchCandidate>,
worktree_id: usize,
query: &str,
smart_case: bool,
max_results: usize,
) -> Vec<PathMatch> {
let lowercase_query = query.to_lowercase().chars().collect::<Vec<_>>();
let query = query.chars().collect::<Vec<_>>();
let query_char_bag = CharBag::from(&lowercase_query[..]);
let mut matcher = Matcher::new(
&query,
&lowercase_query,
query_char_bag,
smart_case,
max_results,
);
let mut results = Vec::new();
matcher.match_candidates(
&[],
&[],
candidates.into_iter(),
&mut results,
&AtomicBool::new(false),
|candidate, score| PathMatch {
score,
worktree_id,
positions: Vec::new(),
path: Arc::from(candidate.path),
path_prefix: Arc::from(""),
distance_to_relative_ancestor: usize::MAX,
},
);
results
}
pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>(
candidate_sets: &'a [Set],
query: &str,
@@ -157,7 +195,7 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>(
score,
worktree_id,
positions: Vec::new(),
path: candidate.path.clone(),
path: Arc::from(candidate.path),
path_prefix: candidate_set.prefix(),
distance_to_relative_ancestor: relative_to.as_ref().map_or(
usize::MAX,

View File

@@ -11,7 +11,7 @@ path = "src/gpui.rs"
doctest = false
[features]
test-support = ["backtrace", "dhat", "env_logger", "collections/test-support"]
test-support = ["backtrace", "dhat", "env_logger", "collections/test-support", "util/test-support"]
[dependencies]
collections = { path = "../collections" }
@@ -53,7 +53,7 @@ thiserror.workspace = true
time.workspace = true
tiny-skia = "0.5"
usvg = { version = "0.14", features = [] }
uuid = { version = "1.1.2", features = ["v4"] }
uuid.workspace = true
waker-fn = "1.1.0"
[build-dependencies]

View File

@@ -1252,7 +1252,7 @@ impl AppContext {
result
})
} else {
panic!("circular model update");
panic!("circular model update for {}", std::any::type_name::<T>());
}
}

View File

@@ -33,6 +33,7 @@ use std::{
any::{type_name, Any, TypeId},
mem,
ops::{Deref, DerefMut, Range, Sub},
sync::Arc,
};
use taffy::{
tree::{Measurable, MeasureFunc},
@@ -56,7 +57,7 @@ pub struct Window {
pub(crate) rendered_views: HashMap<usize, Box<dyn AnyRootElement>>,
scene: SceneBuilder,
pub(crate) text_style_stack: Vec<TextStyle>,
pub(crate) theme_stack: Vec<Box<dyn Any>>,
pub(crate) theme_stack: Vec<Arc<dyn Any + Send + Sync>>,
pub(crate) new_parents: HashMap<usize, usize>,
pub(crate) views_to_notify_if_ancestors_change: HashMap<usize, SmallVec<[usize; 2]>>,
titlebar_height: f32,
@@ -1336,18 +1337,21 @@ impl<'a> WindowContext<'a> {
self.window.text_style_stack.pop();
}
pub fn theme<T: 'static>(&self) -> &T {
pub fn theme<T: 'static + Send + Sync>(&self) -> Arc<T> {
self.window
.theme_stack
.iter()
.rev()
.find_map(|theme| theme.downcast_ref())
.find_map(|theme| {
let entry = Arc::clone(theme);
entry.downcast::<T>().ok()
})
.ok_or_else(|| anyhow!("no theme provided of type {}", type_name::<T>()))
.unwrap()
}
pub fn push_theme<T: 'static>(&mut self, theme: T) {
self.window.theme_stack.push(Box::new(theme));
pub fn push_theme<T: 'static + Send + Sync>(&mut self, theme: T) {
self.window.theme_stack.push(Arc::new(theme));
}
pub fn pop_theme(&mut self) {

View File

@@ -98,7 +98,12 @@ impl FontCache {
}
Err(anyhow!(
"could not find a non-empty font family matching one of the given names"
"could not find a non-empty font family matching one of the given names: {}",
names
.iter()
.map(|name| format!("`{name}`"))
.collect::<Vec<_>>()
.join(", ")
))
}

View File

@@ -1,12 +1,12 @@
use std::fmt::Debug;
use super::scene::{Path, PathVertex};
use crate::{color::Color, json::ToJson};
use derive_more::Neg;
pub use pathfinder_geometry::*;
use rect::RectF;
use refineable::Refineable;
use serde::{Deserialize, Deserializer};
use serde_json::json;
use std::fmt::Debug;
use vector::{vec2f, Vector2F};
pub struct PathBuilder {
@@ -194,8 +194,8 @@ where
impl Size<DefiniteLength> {
pub fn zero() -> Self {
Self {
width: pixels(0.),
height: pixels(0.),
width: pixels(0.).into(),
height: pixels(0.).into(),
}
}
@@ -235,6 +235,17 @@ pub struct Edges<T: Clone + Default + Debug> {
pub left: T,
}
impl<T: Clone + Default + Debug> Edges<T> {
pub fn uniform(value: T) -> Self {
Self {
top: value.clone(),
right: value.clone(),
bottom: value.clone(),
left: value.clone(),
}
}
}
impl Edges<Length> {
pub fn auto() -> Self {
Self {
@@ -247,10 +258,10 @@ impl Edges<Length> {
pub fn zero() -> Self {
Self {
top: pixels(0.),
right: pixels(0.),
bottom: pixels(0.),
left: pixels(0.),
top: pixels(0.).into(),
right: pixels(0.).into(),
bottom: pixels(0.).into(),
left: pixels(0.).into(),
}
}
@@ -270,10 +281,10 @@ impl Edges<Length> {
impl Edges<DefiniteLength> {
pub fn zero() -> Self {
Self {
top: pixels(0.),
right: pixels(0.),
bottom: pixels(0.),
left: pixels(0.),
top: pixels(0.).into(),
right: pixels(0.).into(),
bottom: pixels(0.).into(),
left: pixels(0.).into(),
}
}
@@ -322,7 +333,7 @@ impl Edges<f32> {
}
}
#[derive(Clone, Copy)]
#[derive(Clone, Copy, Neg)]
pub enum AbsoluteLength {
Pixels(f32),
Rems(f32),
@@ -360,7 +371,7 @@ impl Default for AbsoluteLength {
}
/// A non-auto length that can be defined in pixels, rems, or percent of parent.
#[derive(Clone, Copy)]
#[derive(Clone, Copy, Neg)]
pub enum DefiniteLength {
Absolute(AbsoluteLength),
Relative(f32), // 0. to 1.
@@ -404,7 +415,7 @@ impl Default for DefiniteLength {
}
/// A length that can be defined in pixels, rems, percent of parent, or auto.
#[derive(Clone, Copy)]
#[derive(Clone, Copy, Neg)]
pub enum Length {
Definite(DefiniteLength),
Auto,
@@ -419,16 +430,16 @@ impl std::fmt::Debug for Length {
}
}
pub fn relative<T: From<DefiniteLength>>(fraction: f32) -> T {
DefiniteLength::Relative(fraction).into()
pub fn relative(fraction: f32) -> DefiniteLength {
DefiniteLength::Relative(fraction)
}
pub fn rems<T: From<AbsoluteLength>>(rems: f32) -> T {
AbsoluteLength::Rems(rems).into()
pub fn rems(rems: f32) -> AbsoluteLength {
AbsoluteLength::Rems(rems)
}
pub fn pixels<T: From<AbsoluteLength>>(pixels: f32) -> T {
AbsoluteLength::Pixels(pixels).into()
pub fn pixels(pixels: f32) -> AbsoluteLength {
AbsoluteLength::Pixels(pixels)
}
pub fn auto() -> Length {

View File

@@ -112,7 +112,7 @@ impl std::fmt::Display for Keystroke {
f.write_char('^')?;
}
if self.alt {
f.write_char('')?;
f.write_char('')?;
}
if self.cmd {
f.write_char('⌘')?;

View File

@@ -103,6 +103,7 @@ pub struct Platform {
current_clipboard_item: Mutex<Option<ClipboardItem>>,
cursor: Mutex<CursorStyle>,
active_window: Arc<Mutex<Option<AnyWindowHandle>>>,
active_screen: Screen,
}
impl Platform {
@@ -113,6 +114,7 @@ impl Platform {
current_clipboard_item: Default::default(),
cursor: Mutex::new(CursorStyle::Arrow),
active_window: Default::default(),
active_screen: Screen::new(),
}
}
}
@@ -136,12 +138,16 @@ impl super::Platform for Platform {
fn quit(&self) {}
fn screen_by_id(&self, _id: uuid::Uuid) -> Option<Rc<dyn crate::platform::Screen>> {
None
fn screen_by_id(&self, uuid: uuid::Uuid) -> Option<Rc<dyn crate::platform::Screen>> {
if self.active_screen.uuid == uuid {
Some(Rc::new(self.active_screen.clone()))
} else {
None
}
}
fn screens(&self) -> Vec<Rc<dyn crate::platform::Screen>> {
Default::default()
vec![Rc::new(self.active_screen.clone())]
}
fn open_window(
@@ -158,6 +164,7 @@ impl super::Platform for Platform {
WindowBounds::Fixed(rect) => rect.size(),
},
self.active_window.clone(),
Rc::new(self.active_screen.clone()),
))
}
@@ -170,6 +177,7 @@ impl super::Platform for Platform {
handle,
vec2f(24., 24.),
self.active_window.clone(),
Rc::new(self.active_screen.clone()),
))
}
@@ -238,8 +246,18 @@ impl super::Platform for Platform {
fn restart(&self) {}
}
#[derive(Debug)]
pub struct Screen;
#[derive(Debug, Clone)]
pub struct Screen {
uuid: uuid::Uuid,
}
impl Screen {
fn new() -> Self {
Self {
uuid: uuid::Uuid::new_v4(),
}
}
}
impl super::Screen for Screen {
fn as_any(&self) -> &dyn Any {
@@ -255,7 +273,7 @@ impl super::Screen for Screen {
}
fn display_uuid(&self) -> Option<uuid::Uuid> {
Some(uuid::Uuid::new_v4())
Some(self.uuid)
}
}
@@ -275,6 +293,7 @@ pub struct Window {
pub(crate) edited: bool,
pub(crate) pending_prompts: RefCell<VecDeque<oneshot::Sender<usize>>>,
active_window: Arc<Mutex<Option<AnyWindowHandle>>>,
screen: Rc<Screen>,
}
impl Window {
@@ -282,6 +301,7 @@ impl Window {
handle: AnyWindowHandle,
size: Vector2F,
active_window: Arc<Mutex<Option<AnyWindowHandle>>>,
screen: Rc<Screen>,
) -> Self {
Self {
handle,
@@ -299,6 +319,7 @@ impl Window {
edited: false,
pending_prompts: Default::default(),
active_window,
screen,
}
}
@@ -329,7 +350,7 @@ impl super::Window for Window {
}
fn screen(&self) -> Rc<dyn crate::platform::Screen> {
Rc::new(Screen)
self.screen.clone()
}
fn mouse_position(&self) -> Vector2F {

View File

@@ -53,8 +53,10 @@ impl Select {
}
pub fn set_item_count(&mut self, count: usize, cx: &mut ViewContext<Self>) {
self.item_count = count;
cx.notify();
if count != self.item_count {
self.item_count = count;
cx.notify();
}
}
fn toggle(&mut self, cx: &mut ViewContext<Self>) {
@@ -63,9 +65,11 @@ impl Select {
}
pub fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Self>) {
self.selected_item_ix = ix;
self.is_open = false;
cx.notify();
if ix != self.selected_item_ix || self.is_open {
self.selected_item_ix = ix;
self.is_open = false;
cx.notify();
}
}
pub fn selected_index(&self) -> usize {

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