BlueGit

ict rusty-teams

feat(composer): GIFs and stickers, picker with Emoji, GIF and Sticker tabs

- GIF search through the Teams middle tier (no Giphy key), empty query shows trending
- 404 stickers from the Teams catalog on the public Teams CDN
- Received GIFs and stickers load from Giphy or the Teams CDN, also behind the Teams URL proxy
- Picked GIFs and stickers sit in the draft at the cursor and send as linked images

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-09 · 7 weeks ago

Hash
abde01c3db5253d17673e3dacbd3011798fdf3ec
Parent
fd0a29ba
33 files changed +2669 −81
Cargo.lock +1 −0
@@ -7988,6 +7988,7 @@ dependencies = [
7988 7988 "tempfile",
7989 7989 "thiserror 2.0.21",
7990 7990 "tokio",
7991 "url",
7991 7992 ]
7992 7993
7993 7994 [[package]]
@@ -7988,6 +7988,7 @@ dependencies = [
7988 "tempfile",
7988 "tempfile",
7989 "thiserror 2.0.21",
7989 "thiserror 2.0.21",
7990 "tokio",
7990 "tokio",
7991 "url",
7991]
7992]
7992
7993
7993[[package]]
7994[[package]]
README.md +1 −0
@@ -14,6 +14,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
14 14 - Live updates over the Teams realtime socket, no polling
15 15 - Send, edit, delete, react, quote-reply, @mentions
16 16 - Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
17 - Composer picker for emoji, GIFs and stickers; GIFs and stickers also show in messages
17 18 - Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
18 19 - Link previews: card under messages, preview above the composer that goes out with the message
19 20 - Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
@@ -14,6 +14,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
14- Live updates over the Teams realtime socket, no polling
14- Live updates over the Teams realtime socket, no polling
15- Send, edit, delete, react, quote-reply, @mentions
15- Send, edit, delete, react, quote-reply, @mentions
16- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
16- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
17- Composer picker for emoji, GIFs and stickers; GIFs and stickers also show in messages
17- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
18- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
18- Link previews: card under messages, preview above the composer that goes out with the message
19- Link previews: card under messages, preview above the composer that goes out with the message
19- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
20- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
ROADMAP.md +6 −7
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 68 %** (56 done, 4 partial, 25 missing of 85). Partial counts half.
5 **Parity: 70 %** (58 done, 3 partial, 24 missing of 85). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -11,7 +11,7 @@ Feature parity with the Microsoft Teams desktop client.
11 11 | [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
12 12 | [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13 13 | [Reading](#reading) | 87 % | 16 | 1 | 2 |
14 | [Writing](#writing) | 75 % | 10 | 1 | 3 |
14 | [Writing](#writing) | 86 % | 12 | 0 | 2 |
15 15 | [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16 16 | [Channels](#channels) | 36 % | 2 | 1 | 4 |
17 17 | [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
@@ -26,9 +26,8 @@ Feature parity with the Microsoft Teams desktop client.
26 26 |---|---|---|
27 27 | 1 | Channel: new post with subject, post cards | |
28 28 | 2 | Sign in on Linux without Chrome on a debug port | |
29 | 3 | Emoji picker in the composer | Reaction picker exists |
30 | 4 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
31 | 5 | Unsent messages survive a restart | |
29 | 3 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
30 | 4 | Unsent messages survive a restart | |
32 31
33 32 ## Sign-in and app
34 33
@@ -92,10 +91,10 @@ Feature parity with the Microsoft Teams desktop client.
92 91 | Edit own message | Done | From the menu or Up arrow in an empty composer |
93 92 | Delete own message | Done | |
94 93 | React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
95 | Emoji picker | Partial | For reactions; composer still uses colon codes |
94 | Emoji picker | Done | For reactions and in the composer |
96 95 | Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block; superscript, subscript (Ctrl+Shift+= / Ctrl+=) and Small/Large shown at real size while typing |
97 96 | Attach a file, paste or drag an image | Done | Images sit in the text at the cursor as a large preview and send at that spot; files via OneDrive or the channel's Files |
98 | GIFs and stickers | Missing | |
97 | GIFs and stickers | Done | Show and send; composer picker with Emoji, GIF and Sticker tabs; GIF search needs the org to allow it |
99 98 | Schedule send | Missing | |
100 99 | Unsent messages survive a restart | Missing | Pending sends live in memory only |
101 100
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 68 %** (56 done, 4 partial, 25 missing of 85). Partial counts half.
5**Parity: 70 %** (58 done, 3 partial, 24 missing of 85). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -11,7 +11,7 @@ Feature parity with the Microsoft Teams desktop client.
11| [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
11| [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13| [Reading](#reading) | 87 % | 16 | 1 | 2 |
13| [Reading](#reading) | 87 % | 16 | 1 | 2 |
14| [Writing](#writing) | 75 % | 10 | 1 | 3 |
14| [Writing](#writing) | 86 % | 12 | 0 | 2 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
17| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
17| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
@@ -26,9 +26,8 @@ Feature parity with the Microsoft Teams desktop client.
26|---|---|---|
26|---|---|---|
27| 1 | Channel: new post with subject, post cards | |
27| 1 | Channel: new post with subject, post cards | |
28| 2 | Sign in on Linux without Chrome on a debug port | |
28| 2 | Sign in on Linux without Chrome on a debug port | |
29| 3 | Emoji picker in the composer | Reaction picker exists |
29| 3 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
30| 4 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
30| 4 | Unsent messages survive a restart | |
31| 5 | Unsent messages survive a restart | |
32
31
33## Sign-in and app
32## Sign-in and app
34
33
@@ -92,10 +91,10 @@ Feature parity with the Microsoft Teams desktop client.
92| Edit own message | Done | From the menu or Up arrow in an empty composer |
91| Edit own message | Done | From the menu or Up arrow in an empty composer |
93| Delete own message | Done | |
92| Delete own message | Done | |
94| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
93| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
95| Emoji picker | Partial | For reactions; composer still uses colon codes |
94| Emoji picker | Done | For reactions and in the composer |
96| Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block; superscript, subscript (Ctrl+Shift+= / Ctrl+=) and Small/Large shown at real size while typing |
95| Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block; superscript, subscript (Ctrl+Shift+= / Ctrl+=) and Small/Large shown at real size while typing |
97| Attach a file, paste or drag an image | Done | Images sit in the text at the cursor as a large preview and send at that spot; files via OneDrive or the channel's Files |
96| Attach a file, paste or drag an image | Done | Images sit in the text at the cursor as a large preview and send at that spot; files via OneDrive or the channel's Files |
98| GIFs and stickers | Missing | |
97| GIFs and stickers | Done | Show and send; composer picker with Emoji, GIF and Sticker tabs; GIF search needs the org to allow it |
99| Schedule send | Missing | |
98| Schedule send | Missing | |
100| Unsent messages survive a restart | Missing | Pending sends live in memory only |
99| Unsent messages survive a restart | Missing | Pending sends live in memory only |
101
100
crates/app/Cargo.toml +1 −1
@@ -31,7 +31,7 @@ session.workspace = true
31 31 store.workspace = true
32 32 teams-core.workspace = true
33 33 tokio.workspace = true
34 image = { version = "0.25", default-features = false, features = ["bmp", "jpeg", "png", "webp"] }
34 image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
35 35
36 36 [target.'cfg(windows)'.dependencies]
37 37 uuid.workspace = true
@@ -31,7 +31,7 @@ session.workspace = true
31store.workspace = true
31store.workspace = true
32teams-core.workspace = true
32teams-core.workspace = true
33tokio.workspace = true
33tokio.workspace = true
34image = { version = "0.25", default-features = false, features = ["bmp", "jpeg", "png", "webp"] }
34image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
35
35
36[target.'cfg(windows)'.dependencies]
36[target.'cfg(windows)'.dependencies]
37uuid.workspace = true
37uuid.workspace = true
crates/app/assets/stickers.tsv added +404 −0
@@ -0,0 +1,404 @@
1 Clippy_Admire Clippy Clippy_Admire.gif Admire
2 Clippy_AreYouThere Clippy Clippy_AreYouThere.gif Are You There
3 Clippy_Bandaged Clippy Clippy_Bandaged.gif Bandaged
4 Clippy_Bored Clippy Clippy_Bored.gif Bored
5 Clippy_Brb Clippy Clippy_Brb.gif Brb
6 Clippy_Coffee Clippy Clippy_Coffee.gif Coffee
7 Clippy_CoffeeMug Clippy Clippy_CoffeeMug.gif Coffee Mug
8 Clippy_HappyHour Clippy Clippy_HappyHour.gif Happy Hour
9 Clippy_HelloThere Clippy Clippy_HelloThere.gif Hello There
10 Clippy_ImHere Clippy Clippy_ImHere.gif Im Here
11 Clippy_LooksGreat Clippy Clippy_LooksGreat.gif Looks Great
12 Clippy_Love Clippy Clippy_Love.gif Love
13 Clippy_Meeting Clippy Clippy_Meeting.gif Meeting
14 Clippy_Nap Clippy Clippy_Nap.gif Nap
15 Clippy_Nice Clippy Clippy_Nice.gif Nice
16 Clippy_NoProbs Clippy Clippy_NoProbs.gif No Probs
17 Clippy_Normal Clippy Clippy_Normal.gif Normal
18 Clippy_Ok Clippy Clippy_Ok.gif Ok
19 Clippy_Oof Clippy Clippy_Oof.gif Oof
20 Clippy_Payday Clippy Clippy_Payday.gif Payday
21 Clippy_Presentation Clippy Clippy_Presentation.gif Presentation
22 Clippy_Sad Clippy Clippy_Sad.gif Sad
23 Clippy_ShipIt Clippy Clippy_ShipIt.gif Ship It
24 Clippy_Sick Clippy Clippy_Sick.gif Sick
25 Clippy_Spy Clippy Clippy_Spy.gif Spy
26 Clippy_StocksDown Clippy Clippy_StocksDown.gif Stocks Down
27 Clippy_Sun Clippy Clippy_Sun.gif Sun
28 Clippy_Sunglasses Clippy Clippy_Sunglasses.gif Sunglasses
29 Clippy_Surprise Clippy Clippy_Surprise.gif Surprise
30 Clippy_ThankYou Clippy Clippy_ThankYou.gif Thank You
31 Clippy_Traffic Clippy Clippy_Traffic.gif Traffic
32 Clippy_What Clippy Clippy_What.gif What
33 Clippy_WriteLetter Clippy Clippy_WriteLetter.gif Write Letter
34 Clippy_Yeah Clippy Clippy_Yeah.gif Yeah
35 OfficeDrama_SoCool OfficeDrama OfficeDrama_SoCool_New.png So Cool
36 OfficeDrama_Hahaha OfficeDrama OfficeDrama_Hahaha.png Hahaha
37 OfficeDrama_Hey OfficeDrama OfficeDrama_Hey.png Hey
38 OfficeDrama_Interesting OfficeDrama OfficeDrama_Interesting.png Interesting
39 OfficeDrama_Grrr OfficeDrama OfficeDrama_Grrr.png Grrr
40 OfficeDrama_TellMeMore OfficeDrama OfficeDrama_TellMeMore.png Tell Me More
41 OfficeDrama_Oops OfficeDrama OfficeDrama_Oops.png Oops
42 OfficeDrama_Yes OfficeDrama OfficeDrama_Yes.png Yes
43 OfficeDrama_OhYeah OfficeDrama OfficeDrama_OhYeah.png Oh Yeah
44 OfficeDrama_GotThis OfficeDrama OfficeDrama_GotThis.png Got This
45 OfficeDrama_Coffee OfficeDrama OfficeDrama_Coffee.png Coffee
46 OfficeDrama_NotAgain OfficeDrama OfficeDrama_NotAgain.png Not Again
47 OfficeDrama_Hmm OfficeDrama OfficeDrama_Hmm.png Hmm
48 OfficeDrama_DonutShame OfficeDrama OfficeDrama_DonutShame.png Donut Shame
49 OfficeDrama_Swell OfficeDrama OfficeDrama_Swell.png Swell
50 OfficeDrama_Eew OfficeDrama OfficeDrama_Eew.png Eew
51 OfficeDrama_Meeting OfficeDrama OfficeDrama_Meeting.png Meeting
52 OfficeDrama_Horrified OfficeDrama OfficeDrama_Horrified.png Horrified
53 OfficeDrama_Beautiful OfficeDrama OfficeDrama_Beautiful.png Beautiful
54 OfficeDrama_HighFive OfficeDrama OfficeDrama_HighFive.png High Five
55 OfficeDrama_CantThink OfficeDrama OfficeDrama_CantThink.png Cant Think
56 OfficeDrama_CutFeature OfficeDrama OfficeDrama_CutFeature.png Cut Feature
57 OfficeDrama_Plan OfficeDrama OfficeDrama_Plan.png Plan
58 OfficeDrama_Stapler OfficeDrama OfficeDrama_Stapler.png Stapler
59 OfficeDrama_Retirement OfficeDrama OfficeDrama_Retirement.png Retirement
60 OfficeDrama_ForgotSave OfficeDrama OfficeDrama_ForgotSave.png Forgot Save
61 OfficeDrama_DontLike OfficeDrama OfficeDrama_DontLike.png Dont Like
62 OfficeDrama_Cough OfficeDrama OfficeDrama_Cough.png Cough
63 Designers_Bigger Designers Designers_Bigger.png Bigger
64 Designers_Client_Taste Designers Designers_Client_Taste.png Client Taste
65 Designers_Cmyk_Or_Rgb Designers Designers_Cmyk_Or_Rgb.png Cmyk Or Rgb
66 Designers_Creative Designers Designers_Creative.png Creative
67 Designers_Design_Formal Designers Designers_Design_Formal.png Design Formal
68 Designers_Everyones_A_Critic Designers Designers_Everyones_A_Critic.png Everyones A Critic
69 Designers_Everyones_A_Designer Designers Designers_Everyones_A_Designer.png Everyones A Designer
70 Designers_Final Designers Designers_Final.png Final
71 Designers_Fix Designers Designers_Fix.png Fix
72 Designers_Focus Designers Designers_Focus.png Focus
73 Designers_Hotkey_Problems Designers Designers_Hotkey_Problems.png Hotkey Problems
74 Designers_I_Dont_Get_It Designers Designers_I_Dont_Get_It.png I Dont Get It
75 Designers_Just_A_Crit Designers Designers_Just_A_Crit.png Just A Crit
76 Designers_Layers_Flattened Designers Designers_Layers_Flattened.png Layers Flattened
77 Designers_Make_It_Cool Designers Designers_Make_It_Cool.png Make It Cool
78 Designers_My_Design Designers Designers_My_Design.png My Design
79 Designers_Need_More_Screen Designers Designers_Need_More_Screen.png Need More Screen
80 Designers_Negative_Space Designers Designers_Negative_Space.png Negative Space
81 Designers_Not_Green Designers Designers_Not_Green.png Not Green
82 Designers_Pixel_Perfect Designers Designers_Pixel_Perfect.png Pixel Perfect
83 Designers_Raise_Resolution Designers Designers_Raise_Resolution.png Raise Resolution
84 Designers_Simple Designers Designers_Simple.png Simple
85 Designers_Snap_To_Grid Designers Designers_Snap_To_Grid.png Snap To Grid
86 Designers_Think_Outside_The_Box Designers Designers_Think_Outside_The_Box.png Think Outside The Box
87 Designers_Work_For_Exposure Designers Designers_Work_For_Exposure.png Work For Exposure
88 Devs_500 Devs Devs_500_Internal_Error.png 500
89 Devs_Approved Devs Devs_Approved.png Approved
90 Devs_Big_Data Devs Devs_Big_Data.png Big Data
91 Devs_Broke_the_Build Devs Devs_Broke_the_Build.png Broke the Build
92 Devs_Bugs_Bugs_Bugs Devs Devs_Bugs_Bugs_Bugs.png Bugs Bugs Bugs
93 Devs_Multiplying Devs Devs_Bugs_Multiplying.png Multiplying
94 Devs_Can_You_Review Devs Devs_Can_You_Review.png Can You Review
95 Devs_Cloud Devs Devs_Cloud.png Cloud
96 Devs_Done Devs Devs_Done.png Done
97 Devs_Hacked Devs Devs_Hacked.png Hacked
98 Devs_Make_It_Better Devs Devs_Make_It_Better.png Make It Better
99 Devs_Merge_Conflict Devs Devs_Merge_Conflict.png Merge Conflict
100 Devs_No_Repro Devs Devs_No_repro.png No Repro
101 Devs_Not_A_Bug Devs Devs_Not_A_Bug.png Not A Bug
102 Devs_PR_Out Devs Devs_PR_Out.png PR Out
103 Devs_Smash Devs Devs_Smash.png Smash
104 Devs_Test_Fail Devs Devs_Test_Fail.png Test Fail
105 Devs_Uncodable Devs Devs_Uncodable.png Uncodable
106 Devs_Waiting_For_Compile Devs Devs_Waiting_For_Compile.png Waiting For Compile
107 Devs_Works_On_My_Machine Devs Devs_Works_On_My_Machine.png Works On My Machine
108 Legal_Another_Six Legal Legal_Another_Six.png Another Six
109 Legal_Billing_Code Legal Legal_Billing_Code.png Billing Code
110 Legal_Disbarred Legal Legal_Disbarred.png Disbarred
111 Legal_Doc_Review Legal Legal_Doc_Review.png Doc Review
112 Legal_Doctor Legal Legal_Doctor.png Doctor
113 Legal_Fair_Use Legal Legal_Fair_Use.png Fair Use
114 Legal_Fine_Print Legal Legal_Fine_Print.png Fine Print
115 Legal_Force_Majeure Legal Legal_Force_Majeure.png Force Majeure
116 Legal_Legalese Legal Legal_Legalese.png Legalese
117 Legal_NDA Legal Legal_NDA.png NDA
118 Legal_Non_Sequitur Legal Legal_Non_Sequitur.png Non Sequitur
119 Legal_Notary Legal Legal_Notary.png Notary
120 Legal_Objection Legal Legal_Objection.png Objection
121 Legal_Overruled Legal Legal_Overruled.png Overruled
122 Legal_Plead_The_Fifth Legal Legal_Plead_The_Fifth.png Plead The Fifth
123 Legal_Research_Time Legal Legal_Research_Time.png Research Time
124 Legal_Rule_11 Legal Legal_Rule_11.png Rule 11
125 Legal_Shark Legal Legal_Shark.png Shark
126 Legal_Sign Legal Legal_Sign.png Sign
127 Legal_Socratic_Method Legal Legal_Socratic_Method.png Socratic Method
128 Legal_Sustained Legal Legal_Sustained.png Sustained
129 Legal_Transcribe Legal Legal_Transcribe.png Transcribe
130 Legal_We_Got_Sued Legal Legal_We_Got_Sued.png We Got Sued
131 Legal_We_Need_A_Specialist Legal Legal_We_Need_A_Specialist.png We Need A Specialist
132 WordArt_Amazing WordArt WordArt_Amazing.png Amazing
133 WordArt_Awesome WordArt WordArt_Awesome.png Awesome
134 WordArt_BRB WordArt WordArt_BRB.png BRB
135 WordArt_Cool WordArt WordArt_Cool.png Cool
136 WordArt_FYI WordArt WordArt_FYI.png FYI
137 WordArt_Gross WordArt WordArt_Gross.png Gross
138 WordArt_Hello WordArt WordArt_Hello.png Hello
139 WordArt_JustASec WordArt WordArt_JustASec.png Just ASec
140 WordArt_LOL WordArt WordArt_LOL.png LOL
141 WordArt_Nice WordArt WordArt_Nice.png Nice
142 WordArt_NoWay WordArt WordArt_NoWay.png No Way
143 WordArt_Right WordArt WordArt_Right.png Right
144 WordArt_Sweet WordArt WordArt_Sweet.png Sweet
145 WordArt_Thanks WordArt WordArt_Thanks.png Thanks
146 WordArt_Totes WordArt WordArt_Totes.png Totes
147 WordArt_WhyNot WordArt WordArt_WhyNot.png Why Not
148 WordArt_Wow WordArt WordArt_Wow.png Wow
149 WordArt_YeahRight WordArt WordArt_YeahRight.png Yeah Right
150 WordArt_YesPlease WordArt WordArt_YesPlease.png Yes Please
151 Teamsquatch_BrokenMrCopy Teamsquatch Teamsquatch_BrokenMrCopy.png Broken Mr Copy
152 Teamsquatch_BugSquash Teamsquatch Teamsquatch_BugSquash.png Bug Squash
153 Teamsquatch_CoffeeBuzz Teamsquatch Teamsquatch_CoffeeBuzz.png Coffee Buzz
154 Teamsquatch_CoffeeCrew Teamsquatch Teamsquatch_CoffeeCrew.png Coffee Crew
155 Teamsquatch_DeskClutter Teamsquatch Teamsquatch_DeskClutter.png Desk Clutter
156 Teamsquatch_Elevator Teamsquatch Teamsquatch_Elevator.png Elevator
157 Teamsquatch_Email Teamsquatch Teamsquatch_Email.png Email
158 Teamsquatch_EmailOverload Teamsquatch Teamsquatch_EmailOverload.png Email Overload
159 Teamsquatch_FireDrill Teamsquatch Teamsquatch_FireDrill.png Fire Drill
160 Teamsquatch_Goodnuff Teamsquatch Teamsquatch_Goodnuff.png Goodnuff
161 Teamsquatch_KillIt Teamsquatch Teamsquatch_KillIt.png Kill It
162 Teamsquatch_LateNight Teamsquatch Teamsquatch_LateNight.png Late Night
163 Teamsquatch_LunchAlone Teamsquatch Teamsquatch_LunchAlone.png Lunch Alone
164 Teamsquatch_MobileCrew Teamsquatch Teamsquatch_MobileCrew.png Mobile Crew
165 Teamsquatch_MrCopy Teamsquatch Teamsquatch_MrCopy.png Mr Copy
166 Teamsquatch_Nap Teamsquatch Teamsquatch_Nap.png Nap
167 Teamsquatch_Nice Teamsquatch Teamsquatch_Nice.png Nice
168 Teamsquatch_Screenwatching Teamsquatch Teamsquatch_Screenwatching.png Screenwatching
169 Teamsquatch_StolenLunch Teamsquatch Teamsquatch_StolenLunch.png Stolen Lunch
170 Teamsquatch_Teamwork Teamsquatch Teamsquatch_Teamwork.png Teamwork
171 Teamsquatch_WeekendRide Teamsquatch Teamsquatch_WeekendRide.png Weekend Ride
172 Teamsquatch_WorkingHard Teamsquatch Teamsquatch_WorkingHard.png Working Hard
173 Teamsquatch_Yes Teamsquatch Teamsquatch_Yes.png Yes
174 BummerBert_AnotherBadDay BummerBert BummerBert_AnotherBadDay.png Another Bad Day
175 BummerBert_Corner BummerBert BummerBert_Corner.png Corner
176 BummerBert_Hopeless BummerBert BummerBert_Hopeless.png Hopeless
177 BummerBert_IGiveUp BummerBert BummerBert_IGiveUp.png IGive Up
178 BummerBert_IJustCant BummerBert BummerBert_IJustCant.png IJust Cant
179 BummerBert_IveMadeAHugeMistake BummerBert BummerBert_IveMadeAHugeMistake.png Ive Made AHuge Mistake
180 BummerBert_IWillNeverFinish BummerBert BummerBert_IWillNeverFinish.png IWill Never Finish
181 BummerBert_IWillTryAgainMaybe BummerBert BummerBert_IWillTryAgainMaybe.png IWill Try Again Maybe
182 BummerBert_Meh BummerBert BummerBert_Meh.png Meh
183 BummerBert_NobodyCares BummerBert BummerBert_NobodyCares.png Nobody Cares
184 BummerBert_NotMe BummerBert BummerBert_NotMe.png Not Me
185 BummerBert_NotSoFast BummerBert BummerBert_NotSoFast.png Not So Fast
186 BummerBert_Sigh BummerBert BummerBert_Sigh.png Sigh
187 BummerBert_Typical BummerBert BummerBert_Typical.png Typical
188 BummerBert_WellThatFailed BummerBert BummerBert_WellThatFailed.png Well That Failed
189 BummerBert_WhatIsHappiness BummerBert BummerBert_WhatIsHappiness.png What Is Happiness
190 BummerBert_WhyMe BummerBert BummerBert_WhyMe.png Why Me
191 BummerBert_WorkingLateAgain BummerBert BummerBert_WorkingLateAgain.png Working Late Again
192 BummerBert_WrongAgain BummerBert BummerBert_WrongAgain.png Wrong Again
193 CatsInSuits_Cat CatsInSuits CatsInSuits_Cat.png Cat
194 CatsInSuits_Coffee CatsInSuits CatsInSuits_Coffee.png Coffee
195 CatsInSuits_DogSuit CatsInSuits CatsInSuits_DogSuit.png Dog Suit
196 CatsInSuits_Eating CatsInSuits CatsInSuits_Eating.png Eating
197 CatsInSuits_Hairball CatsInSuits CatsInSuits_Hairball.png Hairball
198 CatsInSuits_Injured CatsInSuits CatsInSuits_Injured.png Injured
199 CatsInSuits_Jump CatsInSuits CatsInSuits_Jump.png Jump
200 CatsInSuits_Keyboard CatsInSuits CatsInSuits_Keyboard.png Keyboard
201 CatsInSuits_Lick CatsInSuits CatsInSuits_Lick.png Lick
202 CatsInSuits_Mouse CatsInSuits CatsInSuits_Mouse.png Mouse
203 CatsInSuits_OfficeChair CatsInSuits CatsInSuits_OfficeChair.png Office Chair
204 CatsInSuits_PassOut CatsInSuits CatsInSuits_PassOut.png Pass Out
205 CatsInSuits_Question CatsInSuits CatsInSuits_Question.png Question
206 CatsInSuits_RollOver CatsInSuits CatsInSuits_RollOver.png Roll Over
207 CatsInSuits_Scared CatsInSuits CatsInSuits_Scared.png Scared
208 CatsInSuits_Shy CatsInSuits CatsInSuits_Shy.png Shy
209 CatsInSuits_SleepInSun CatsInSuits CatsInSuits_SleepInSun.png Sleep In Sun
210 CatsInSuits_SleepOnDesk CatsInSuits CatsInSuits_SleepOnDesk.png Sleep On Desk
211 CatsInSuits_WaterSpill CatsInSuits CatsInSuits_WaterSpill.png Water Spill
212 CatsInSuits_Window CatsInSuits CatsInSuits_Window.png Window
213 CatsInSuits_Yarn CatsInSuits CatsInSuits_Yarn.png Yarn
214 Monkey_Attack Monkey Monkey_Attack.png Attack
215 Monkey_Banana Monkey Monkey_Banana.png Banana
216 Monkey_Basic Monkey Monkey_Basic.png Basic
217 Monkey_Bored Monkey Monkey_Bored.png Bored
218 Monkey_Cheer Monkey Monkey_Cheer.png Cheer
219 Monkey_Cool Monkey Monkey_Cool.png Cool
220 Monkey_Dance Monkey Monkey_Dance.png Dance
221 Monkey_Disguise Monkey Monkey_Disguise.png Disguise
222 Monkey_Dissed Monkey Monkey_Dissed.png Dissed
223 Monkey_Dumbstruck Monkey Monkey_Dumbstruck.png Dumbstruck
224 Monkey_Encourage Monkey Monkey_Encourage.png Encourage
225 Monkey_FaceDown Monkey Monkey_FaceDown.png Face Down
226 Monkey_Frustrated Monkey Monkey_Frustrated.png Frustrated
227 Monkey_Furious Monkey Monkey_Furious.png Furious
228 Monkey_HearNoEvil Monkey Monkey_HearNoEvil.png Hear No Evil
229 Monkey_Jump Monkey Monkey_Jump.png Jump
230 Monkey_Photo Monkey Monkey_Photo.png Photo
231 Monkey_Run Monkey Monkey_Run.png Run
232 Monkey_SeeNoEvil Monkey Monkey_SeeNoEvil.png See No Evil
233 Monkey_Shrug Monkey Monkey_Shrug.png Shrug
234 Monkey_Sleep Monkey Monkey_Sleep.png Sleep
235 Monkey_Sneak Monkey Monkey_Sneak.png Sneak
236 Monkey_SpeakNoEvil Monkey Monkey_SpeakNoEvil.png Speak No Evil
237 Monkey_Stressed Monkey Monkey_Stressed.png Stressed
238 Monkey_Tears Monkey Monkey_Tears.png Tears
239 Monkey_Think Monkey Monkey_Think.png Think
240 Monkey_ThumbsUp Monkey Monkey_ThumbsUp.png Thumbs Up
241 Monkey_WornOut Monkey Monkey_WornOut.png Worn Out
242 Octocorn_Amazed Octocorn Octocorn_Amazed.png Amazed
243 Octocorn_Awe Octocorn Octocorn_Awe.png Awe
244 Octocorn_Barf Octocorn Octocorn_Barf.png Barf
245 Octocorn_Coffee Octocorn Octocorn_Coffee.png Coffee
246 Octocorn_Cold Octocorn Octocorn_Cold.png Cold
247 Octocorn_Command Octocorn Octocorn_Command.png Command
248 Octocorn_Confident Octocorn Octocorn_Confident.png Confident
249 Octocorn_Confused Octocorn Octocorn_Confused.png Confused
250 Octocorn_Creepy Octocorn Octocorn_Creepy.png Creepy
251 Octocorn_Crosseye Octocorn Octocorn_Crosseye.png Crosseye
252 Octocorn_Cry Octocorn Octocorn_Cry.png Cry
253 Octocorn_Derp Octocorn Octocorn_Derp.png Derp
254 Octocorn_Devious Octocorn Octocorn_Devious.png Devious
255 Octocorn_Drunk Octocorn Octocorn_Drunk.png Drunk
256 Octocorn_Eager Octocorn Octocorn_Eager.png Eager
257 Octocorn_Enthused Octocorn Octocorn_Enthused.png Enthused
258 Octocorn_Excited Octocorn Octocorn_Excited.png Excited
259 Octocorn_FacePlant Octocorn Octocorn_FacePlant.png Face Plant
260 Octocorn_Fly Octocorn Octocorn_Fly.png Fly
261 Octocorn_Formal Octocorn Octocorn_Formal.png Formal
262 Octocorn_Giggle Octocorn Octocorn_Giggle.png Giggle
263 Octocorn_Goofy Octocorn Octocorn_Goofy.png Goofy
264 Octocorn_Happy Octocorn Octocorn_Happy.png Happy
265 Octocorn_Hot Octocorn Octocorn_Hot.png Hot
266 Octocorn_KnockedOver Octocorn Octocorn_KnockedOver.png Knocked Over
267 Octocorn_Laugh Octocorn Octocorn_Laugh.png Laugh
268 Octocorn_Ouch Octocorn Octocorn_Ouch.png Ouch
269 Octocorn_Proud Octocorn Octocorn_Proud.png Proud
270 Octocorn_Question Octocorn Octocorn_Question.png Question
271 Octocorn_Rage Octocorn Octocorn_Rage.png Rage
272 Octocorn_Sad Octocorn Octocorn_Sad.png Sad
273 Octocorn_Salute Octocorn Octocorn_Salute.png Salute
274 Octocorn_Scared Octocorn Octocorn_Scared.png Scared
275 Octocorn_Shy Octocorn Octocorn_Shy.png Shy
276 Octocorn_Sick Octocorn Octocorn_Sick.png Sick
277 Octocorn_Simple Octocorn Octocorn_Simple.png Simple
278 Octocorn_Sleep Octocorn Octocorn_Sleep.png Sleep
279 Octocorn_Slow Octocorn Octocorn_Slow.png Slow
280 Octocorn_Startled Octocorn Octocorn_Startled.png Startled
281 Octocorn_Stretch Octocorn Octocorn_Stretch.png Stretch
282 Octocorn_Study Octocorn Octocorn_Study.png Study
283 Octocorn_Stunned Octocorn Octocorn_Stunned.png Stunned
284 Octocorn_Stupified Octocorn Octocorn_Stupified.png Stupified
285 Octocorn_Suspicious Octocorn Octocorn_Suspicious.png Suspicious
286 Octocorn_Terror Octocorn Octocorn_Terror.png Terror
287 Octocorn_Thinking Octocorn Octocorn_Thinking.png Thinking
288 Octocorn_Tongue Octocorn Octocorn_Tongue.png Tongue
289 Octocorn_Tough Octocorn Octocorn_Tough.png Tough
290 Octocorn_Twitch Octocorn Octocorn_Twitch.png Twitch
291 Octocorn_Upset Octocorn Octocorn_Upset.png Upset
292 Broccoli_Angry Broccoli stickerbroccoliangry.png Angry
293 Broccoli_Confused Broccoli stickerbroccoliconfused.png Confused
294 Broccoli_FistBump Broccoli stickerbroccolifistbump.png Fist Bump
295 Broccoli_GreatJobTeam Broccoli stickerbroccoligreatjob.png Great Job Team
296 Broccoli_HiFive Broccoli stickerbroccolihifive.png Hi Five
297 Broccoli_Cool Broccoli stickerbroccolicool.png Cool
298 Broccoli_Like Broccoli stickerbroccolilike.png Like
299 Broccoli_NotMushroom Broccoli stickerbroccolinotmushroom.png Not Mushroom
300 Broccoli_WOW Broccoli stickerbroccoliwow.png WOW
301 Broccoli_Overwhelmed Broccoli stickerbroccolioverwhelmed.png Overwhelmed
302 Broccoli_Party Broccoli stickerbroccoliparty.png Party
303 Broccoli_Sad Broccoli stickerbroccolisad.png Sad
304 Broccoli_Cold Broccoli stickerbroccolicold.png Cold
305 Broccoli_OnMyWay Broccoli stickerbroccoliomw.png On My Way
306 Broccoli_TeamCheers Broccoli stickerbroccoliteamcheers.png Team Cheers
307 Broccoli_TeamHuddle Broccoli stickerbroccoliteamhuddle.png Team Huddle
308 Broccoli_Tired Broccoli stickerbroccolitired.png Tired
309 Broccoli_Trapped Broccoli stickerbroccolitrapped.png Trapped
310 Broccoli_Wave Broccoli stickerbroccoliwave.png Wave
311 Broccoli_WhereAreYou Broccoli stickerbroccoliwhereareyou.png Where Are You
312 Bee_Angry Bee stickerbeeangry.png Angry
313 Bee_Ashamed Bee stickerbeeashamed.png Ashamed
314 Bee_Bored Bee stckerbeebored.png Bored
315 Bee_Cheers Bee stickerbeecheers.png Cheers
316 Bee_Confused Bee stickerbeeconfused.png Confused
317 Bee_Happy Bee stickerbeehappy.png Happy
318 Bee_Hi Bee stickerbeehi.png Hi
319 Bee_HiFive Bee stickerbeehifive.png Hi Five
320 Bee_Laughing Bee stickerbeelaughing.png Laughing
321 Bee_Like Bee stickerbeelike.png Like
322 Bee_Love Bee stickerbeelove.png Love
323 Bee_MissingYou Bee stickerbeemissingyou.png Missing You
324 Bee_No Bee stickerbeeno.png No
325 Bee_WOW Bee stickerbeewow.png WOW
326 Bee_OMW Bee stickerbeeomw.png OMW
327 Bee_Party Bee stickerbeeparty.png Party
328 Bee_FistBump Bee stickerbeefistbump.png Fist Bump
329 Bee_Sad Bee stickerbeesad.png Sad
330 Bee_Sick Bee stickerbeesick.png Sick
331 Bee_Well Bee stickerbeewell.png Well
332 DonutFriends_begging DonutFriends DonutFriends_begging.png begging
333 DonutFriends_chagrin DonutFriends DonutFriends_chagrin.png chagrin
334 DonutFriends_cheering DonutFriends DonutFriends_cheering.png cheering
335 DonutFriends_crying DonutFriends DonutFriends_crying.png crying
336 DonutFriends_extremeshock DonutFriends DonutFriends_extremeshock.png extremeshock
337 DonutFriends_facepalm DonutFriends DonutFriends_facepalm.png facepalm
338 DonutFriends_impatient DonutFriends DonutFriends_impatient.png impatient
339 DonutFriends_lightbulb DonutFriends DonutFriends_lightbulb.png lightbulb
340 DonutFriends_rofl DonutFriends DonutFriends_rofl.png rofl
341 DonutFriends_searching DonutFriends DonutFriends_searching.png searching
342 DonutFriends_thinking DonutFriends DonutFriends_thinking.png thinking
343 DonutFriends_thumbsup DonutFriends DonutFriends_thumbsup.png thumbsup
344 UncleBlob_Angry UncleBlob UncleBlob_Angry.png Angry
345 UncleBlob_Cheer UncleBlob UncleBlob_Cheer.png Cheer
346 UncleBlob_EndOfTheWorld UncleBlob UncleBlob_EndOfTheWorld.png End Of The World
347 UncleBlob_HeartEyes UncleBlob UncleBlob_HeartEyes.png Heart Eyes
348 UncleBlob_Hungry UncleBlob UncleBlob_Hungry.png Hungry
349 UncleBlob_Laughing UncleBlob UncleBlob_Laughing.png Laughing
350 UncleBlob_Pleading UncleBlob UncleBlob_Pleading.png Pleading
351 UncleBlob_Shocked UncleBlob UncleBlob_Shocked.png Shocked
352 UncleBlob_Sleepy UncleBlob UncleBlob_Sleepy.png Sleepy
353 UncleBlob_Thinking UncleBlob UncleBlob_Thinking.png Thinking
354 UncleBlob_ThumbsUp UncleBlob UncleBlob_ThumbsUp.png Thumbs Up
355 UncleBlob_Unmotivated UncleBlob UncleBlob_Unmotivated.png Unmotivated
356 Animalopolis_cry_mouse Animalopolis Animalopolis_cry_mouse.png cry mouse
357 Animalopolis_cute_koala Animalopolis Animalopolis_cute_koala.png cute koala
358 Animalopolis_excited_bunny Animalopolis Animalopolis_excited_bunny.png excited bunny
359 Animalopolis_grumpy_goat Animalopolis Animalopolis_grumpy_goat.png grumpy goat
360 Animalopolis_hmm_fox Animalopolis Animalopolis_hmm_fox.png hmm fox
361 Animalopolis_hype_monkey Animalopolis Animalopolis_hype_monkey.png hype monkey
362 Animalopolis_laughing_donkey Animalopolis Animalopolis_laughing_donkey.png laughing donkey
363 Animalopolis_love_hedgehog Animalopolis Animalopolis_love_hedgehog.png love hedgehog
364 Animalopolis_mad_rhino Animalopolis Animalopolis_mad_rhino.png mad rhino
365 Animalopolis_oops_panda Animalopolis Animalopolis_oops_panda.png oops panda
366 Animalopolis_running_cheetah Animalopolis Animalopolis_running_cheetah.png running cheetah
367 Animalopolis_weird_lemur Animalopolis Animalopolis_weird_lemur.png weird lemur
368 stickers_BMac_idea BMac stickers_BMac_idea.png stickers BMac idea
369 stickers_BMac_like BMac stickers_BMac_like.png stickers BMac like
370 stickers_BMac_nosign BMac stickers_BMac_nosign.png stickers BMac nosign
371 stickers_BMac_hawaii BMac stickers_BMac_hawaii.png stickers BMac hawaii
372 stickers_BMac_surprised BMac stickers_BMac_surprised.png stickers BMac surprised
373 stickers_BMac_soda BMac stickers_BMac_soda.png stickers BMac soda
374 stickers_BMac_nobutton BMac stickers_BMac_nobutton.png stickers BMac nobutton
375 stickers_BMac_singing BMac stickers_BMac_singing.png stickers BMac singing
376 stickers_BMac_giraffe BMac stickers_BMac_giraffe.png stickers BMac giraffe
377 stickers_Bmac_nope BMac stickers_Bmac_nope.png stickers Bmac nope
378 stickers_Bmac_tacos BMac stickers_Bmac_tacos.png stickers Bmac tacos
379 Food_Beer Food Food_Beer.png Beer
380 Food_Burger Food Food_Burger.png Burger
381 Food_Burrito Food Food_Burrito.png Burrito
382 Food_Cake Food Food_Cake.png Cake
383 Food_Cocktail Food Food_Cocktail.png Cocktail
384 Food_Coffee Food Food_Coffee.png Coffee
385 Food_Cupcake Food Food_Cupcake.png Cupcake
386 Food_DimSum Food Food_DimSum.png Dim Sum
387 Food_Donut Food Food_Donut.png Donut
388 Food_Fries Food Food_Fries.png Fries
389 Food_GeneralTso Food Food_GeneralTso.png General Tso
390 Food_HotDog Food Food_HotDog.png Hot Dog
391 Food_IceCream Food Food_IceCream.png Ice Cream
392 Food_MixedDrink Food Food_MixedDrink.png Mixed Drink
393 Food_Pita Food Food_Pita.png Pita
394 Food_Pizza Food Food_Pizza.png Pizza
395 Food_Ramen Food Food_Ramen.png Ramen
396 Food_Salad Food Food_Salad.png Salad
397 Food_Sandwich Food Food_Sandwich.png Sandwich
398 Food_Sashimi Food Food_Sashimi.png Sashimi
399 Food_Soup Food Food_Soup.png Soup
400 Food_Spaghetti Food Food_Spaghetti.png Spaghetti
401 Food_StreetTaco Food Food_StreetTaco.png Street Taco
402 Food_Sushi Food Food_Sushi.png Sushi
403 Food_Taco Food Food_Taco.png Taco
404 Food_Tea Food Food_Tea.png Tea
@@ -0,0 +1,404 @@
1Clippy_Admire Clippy Clippy_Admire.gif Admire
2Clippy_AreYouThere Clippy Clippy_AreYouThere.gif Are You There
3Clippy_Bandaged Clippy Clippy_Bandaged.gif Bandaged
4Clippy_Bored Clippy Clippy_Bored.gif Bored
5Clippy_Brb Clippy Clippy_Brb.gif Brb
6Clippy_Coffee Clippy Clippy_Coffee.gif Coffee
7Clippy_CoffeeMug Clippy Clippy_CoffeeMug.gif Coffee Mug
8Clippy_HappyHour Clippy Clippy_HappyHour.gif Happy Hour
9Clippy_HelloThere Clippy Clippy_HelloThere.gif Hello There
10Clippy_ImHere Clippy Clippy_ImHere.gif Im Here
11Clippy_LooksGreat Clippy Clippy_LooksGreat.gif Looks Great
12Clippy_Love Clippy Clippy_Love.gif Love
13Clippy_Meeting Clippy Clippy_Meeting.gif Meeting
14Clippy_Nap Clippy Clippy_Nap.gif Nap
15Clippy_Nice Clippy Clippy_Nice.gif Nice
16Clippy_NoProbs Clippy Clippy_NoProbs.gif No Probs
17Clippy_Normal Clippy Clippy_Normal.gif Normal
18Clippy_Ok Clippy Clippy_Ok.gif Ok
19Clippy_Oof Clippy Clippy_Oof.gif Oof
20Clippy_Payday Clippy Clippy_Payday.gif Payday
21Clippy_Presentation Clippy Clippy_Presentation.gif Presentation
22Clippy_Sad Clippy Clippy_Sad.gif Sad
23Clippy_ShipIt Clippy Clippy_ShipIt.gif Ship It
24Clippy_Sick Clippy Clippy_Sick.gif Sick
25Clippy_Spy Clippy Clippy_Spy.gif Spy
26Clippy_StocksDown Clippy Clippy_StocksDown.gif Stocks Down
27Clippy_Sun Clippy Clippy_Sun.gif Sun
28Clippy_Sunglasses Clippy Clippy_Sunglasses.gif Sunglasses
29Clippy_Surprise Clippy Clippy_Surprise.gif Surprise
30Clippy_ThankYou Clippy Clippy_ThankYou.gif Thank You
31Clippy_Traffic Clippy Clippy_Traffic.gif Traffic
32Clippy_What Clippy Clippy_What.gif What
33Clippy_WriteLetter Clippy Clippy_WriteLetter.gif Write Letter
34Clippy_Yeah Clippy Clippy_Yeah.gif Yeah
35OfficeDrama_SoCool OfficeDrama OfficeDrama_SoCool_New.png So Cool
36OfficeDrama_Hahaha OfficeDrama OfficeDrama_Hahaha.png Hahaha
37OfficeDrama_Hey OfficeDrama OfficeDrama_Hey.png Hey
38OfficeDrama_Interesting OfficeDrama OfficeDrama_Interesting.png Interesting
39OfficeDrama_Grrr OfficeDrama OfficeDrama_Grrr.png Grrr
40OfficeDrama_TellMeMore OfficeDrama OfficeDrama_TellMeMore.png Tell Me More
41OfficeDrama_Oops OfficeDrama OfficeDrama_Oops.png Oops
42OfficeDrama_Yes OfficeDrama OfficeDrama_Yes.png Yes
43OfficeDrama_OhYeah OfficeDrama OfficeDrama_OhYeah.png Oh Yeah
44OfficeDrama_GotThis OfficeDrama OfficeDrama_GotThis.png Got This
45OfficeDrama_Coffee OfficeDrama OfficeDrama_Coffee.png Coffee
46OfficeDrama_NotAgain OfficeDrama OfficeDrama_NotAgain.png Not Again
47OfficeDrama_Hmm OfficeDrama OfficeDrama_Hmm.png Hmm
48OfficeDrama_DonutShame OfficeDrama OfficeDrama_DonutShame.png Donut Shame
49OfficeDrama_Swell OfficeDrama OfficeDrama_Swell.png Swell
50OfficeDrama_Eew OfficeDrama OfficeDrama_Eew.png Eew
51OfficeDrama_Meeting OfficeDrama OfficeDrama_Meeting.png Meeting
52OfficeDrama_Horrified OfficeDrama OfficeDrama_Horrified.png Horrified
53OfficeDrama_Beautiful OfficeDrama OfficeDrama_Beautiful.png Beautiful
54OfficeDrama_HighFive OfficeDrama OfficeDrama_HighFive.png High Five
55OfficeDrama_CantThink OfficeDrama OfficeDrama_CantThink.png Cant Think
56OfficeDrama_CutFeature OfficeDrama OfficeDrama_CutFeature.png Cut Feature
57OfficeDrama_Plan OfficeDrama OfficeDrama_Plan.png Plan
58OfficeDrama_Stapler OfficeDrama OfficeDrama_Stapler.png Stapler
59OfficeDrama_Retirement OfficeDrama OfficeDrama_Retirement.png Retirement
60OfficeDrama_ForgotSave OfficeDrama OfficeDrama_ForgotSave.png Forgot Save
61OfficeDrama_DontLike OfficeDrama OfficeDrama_DontLike.png Dont Like
62OfficeDrama_Cough OfficeDrama OfficeDrama_Cough.png Cough
63Designers_Bigger Designers Designers_Bigger.png Bigger
64Designers_Client_Taste Designers Designers_Client_Taste.png Client Taste
65Designers_Cmyk_Or_Rgb Designers Designers_Cmyk_Or_Rgb.png Cmyk Or Rgb
66Designers_Creative Designers Designers_Creative.png Creative
67Designers_Design_Formal Designers Designers_Design_Formal.png Design Formal
68Designers_Everyones_A_Critic Designers Designers_Everyones_A_Critic.png Everyones A Critic
69Designers_Everyones_A_Designer Designers Designers_Everyones_A_Designer.png Everyones A Designer
70Designers_Final Designers Designers_Final.png Final
71Designers_Fix Designers Designers_Fix.png Fix
72Designers_Focus Designers Designers_Focus.png Focus
73Designers_Hotkey_Problems Designers Designers_Hotkey_Problems.png Hotkey Problems
74Designers_I_Dont_Get_It Designers Designers_I_Dont_Get_It.png I Dont Get It
75Designers_Just_A_Crit Designers Designers_Just_A_Crit.png Just A Crit
76Designers_Layers_Flattened Designers Designers_Layers_Flattened.png Layers Flattened
77Designers_Make_It_Cool Designers Designers_Make_It_Cool.png Make It Cool
78Designers_My_Design Designers Designers_My_Design.png My Design
79Designers_Need_More_Screen Designers Designers_Need_More_Screen.png Need More Screen
80Designers_Negative_Space Designers Designers_Negative_Space.png Negative Space
81Designers_Not_Green Designers Designers_Not_Green.png Not Green
82Designers_Pixel_Perfect Designers Designers_Pixel_Perfect.png Pixel Perfect
83Designers_Raise_Resolution Designers Designers_Raise_Resolution.png Raise Resolution
84Designers_Simple Designers Designers_Simple.png Simple
85Designers_Snap_To_Grid Designers Designers_Snap_To_Grid.png Snap To Grid
86Designers_Think_Outside_The_Box Designers Designers_Think_Outside_The_Box.png Think Outside The Box
87Designers_Work_For_Exposure Designers Designers_Work_For_Exposure.png Work For Exposure
88Devs_500 Devs Devs_500_Internal_Error.png 500
89Devs_Approved Devs Devs_Approved.png Approved
90Devs_Big_Data Devs Devs_Big_Data.png Big Data
91Devs_Broke_the_Build Devs Devs_Broke_the_Build.png Broke the Build
92Devs_Bugs_Bugs_Bugs Devs Devs_Bugs_Bugs_Bugs.png Bugs Bugs Bugs
93Devs_Multiplying Devs Devs_Bugs_Multiplying.png Multiplying
94Devs_Can_You_Review Devs Devs_Can_You_Review.png Can You Review
95Devs_Cloud Devs Devs_Cloud.png Cloud
96Devs_Done Devs Devs_Done.png Done
97Devs_Hacked Devs Devs_Hacked.png Hacked
98Devs_Make_It_Better Devs Devs_Make_It_Better.png Make It Better
99Devs_Merge_Conflict Devs Devs_Merge_Conflict.png Merge Conflict
100Devs_No_Repro Devs Devs_No_repro.png No Repro
101Devs_Not_A_Bug Devs Devs_Not_A_Bug.png Not A Bug
102Devs_PR_Out Devs Devs_PR_Out.png PR Out
103Devs_Smash Devs Devs_Smash.png Smash
104Devs_Test_Fail Devs Devs_Test_Fail.png Test Fail
105Devs_Uncodable Devs Devs_Uncodable.png Uncodable
106Devs_Waiting_For_Compile Devs Devs_Waiting_For_Compile.png Waiting For Compile
107Devs_Works_On_My_Machine Devs Devs_Works_On_My_Machine.png Works On My Machine
108Legal_Another_Six Legal Legal_Another_Six.png Another Six
109Legal_Billing_Code Legal Legal_Billing_Code.png Billing Code
110Legal_Disbarred Legal Legal_Disbarred.png Disbarred
111Legal_Doc_Review Legal Legal_Doc_Review.png Doc Review
112Legal_Doctor Legal Legal_Doctor.png Doctor
113Legal_Fair_Use Legal Legal_Fair_Use.png Fair Use
114Legal_Fine_Print Legal Legal_Fine_Print.png Fine Print
115Legal_Force_Majeure Legal Legal_Force_Majeure.png Force Majeure
116Legal_Legalese Legal Legal_Legalese.png Legalese
117Legal_NDA Legal Legal_NDA.png NDA
118Legal_Non_Sequitur Legal Legal_Non_Sequitur.png Non Sequitur
119Legal_Notary Legal Legal_Notary.png Notary
120Legal_Objection Legal Legal_Objection.png Objection
121Legal_Overruled Legal Legal_Overruled.png Overruled
122Legal_Plead_The_Fifth Legal Legal_Plead_The_Fifth.png Plead The Fifth
123Legal_Research_Time Legal Legal_Research_Time.png Research Time
124Legal_Rule_11 Legal Legal_Rule_11.png Rule 11
125Legal_Shark Legal Legal_Shark.png Shark
126Legal_Sign Legal Legal_Sign.png Sign
127Legal_Socratic_Method Legal Legal_Socratic_Method.png Socratic Method
128Legal_Sustained Legal Legal_Sustained.png Sustained
129Legal_Transcribe Legal Legal_Transcribe.png Transcribe
130Legal_We_Got_Sued Legal Legal_We_Got_Sued.png We Got Sued
131Legal_We_Need_A_Specialist Legal Legal_We_Need_A_Specialist.png We Need A Specialist
132WordArt_Amazing WordArt WordArt_Amazing.png Amazing
133WordArt_Awesome WordArt WordArt_Awesome.png Awesome
134WordArt_BRB WordArt WordArt_BRB.png BRB
135WordArt_Cool WordArt WordArt_Cool.png Cool
136WordArt_FYI WordArt WordArt_FYI.png FYI
137WordArt_Gross WordArt WordArt_Gross.png Gross
138WordArt_Hello WordArt WordArt_Hello.png Hello
139WordArt_JustASec WordArt WordArt_JustASec.png Just ASec
140WordArt_LOL WordArt WordArt_LOL.png LOL
141WordArt_Nice WordArt WordArt_Nice.png Nice
142WordArt_NoWay WordArt WordArt_NoWay.png No Way
143WordArt_Right WordArt WordArt_Right.png Right
144WordArt_Sweet WordArt WordArt_Sweet.png Sweet
145WordArt_Thanks WordArt WordArt_Thanks.png Thanks
146WordArt_Totes WordArt WordArt_Totes.png Totes
147WordArt_WhyNot WordArt WordArt_WhyNot.png Why Not
148WordArt_Wow WordArt WordArt_Wow.png Wow
149WordArt_YeahRight WordArt WordArt_YeahRight.png Yeah Right
150WordArt_YesPlease WordArt WordArt_YesPlease.png Yes Please
151Teamsquatch_BrokenMrCopy Teamsquatch Teamsquatch_BrokenMrCopy.png Broken Mr Copy
152Teamsquatch_BugSquash Teamsquatch Teamsquatch_BugSquash.png Bug Squash
153Teamsquatch_CoffeeBuzz Teamsquatch Teamsquatch_CoffeeBuzz.png Coffee Buzz
154Teamsquatch_CoffeeCrew Teamsquatch Teamsquatch_CoffeeCrew.png Coffee Crew
155Teamsquatch_DeskClutter Teamsquatch Teamsquatch_DeskClutter.png Desk Clutter
156Teamsquatch_Elevator Teamsquatch Teamsquatch_Elevator.png Elevator
157Teamsquatch_Email Teamsquatch Teamsquatch_Email.png Email
158Teamsquatch_EmailOverload Teamsquatch Teamsquatch_EmailOverload.png Email Overload
159Teamsquatch_FireDrill Teamsquatch Teamsquatch_FireDrill.png Fire Drill
160Teamsquatch_Goodnuff Teamsquatch Teamsquatch_Goodnuff.png Goodnuff
161Teamsquatch_KillIt Teamsquatch Teamsquatch_KillIt.png Kill It
162Teamsquatch_LateNight Teamsquatch Teamsquatch_LateNight.png Late Night
163Teamsquatch_LunchAlone Teamsquatch Teamsquatch_LunchAlone.png Lunch Alone
164Teamsquatch_MobileCrew Teamsquatch Teamsquatch_MobileCrew.png Mobile Crew
165Teamsquatch_MrCopy Teamsquatch Teamsquatch_MrCopy.png Mr Copy
166Teamsquatch_Nap Teamsquatch Teamsquatch_Nap.png Nap
167Teamsquatch_Nice Teamsquatch Teamsquatch_Nice.png Nice
168Teamsquatch_Screenwatching Teamsquatch Teamsquatch_Screenwatching.png Screenwatching
169Teamsquatch_StolenLunch Teamsquatch Teamsquatch_StolenLunch.png Stolen Lunch
170Teamsquatch_Teamwork Teamsquatch Teamsquatch_Teamwork.png Teamwork
171Teamsquatch_WeekendRide Teamsquatch Teamsquatch_WeekendRide.png Weekend Ride
172Teamsquatch_WorkingHard Teamsquatch Teamsquatch_WorkingHard.png Working Hard
173Teamsquatch_Yes Teamsquatch Teamsquatch_Yes.png Yes
174BummerBert_AnotherBadDay BummerBert BummerBert_AnotherBadDay.png Another Bad Day
175BummerBert_Corner BummerBert BummerBert_Corner.png Corner
176BummerBert_Hopeless BummerBert BummerBert_Hopeless.png Hopeless
177BummerBert_IGiveUp BummerBert BummerBert_IGiveUp.png IGive Up
178BummerBert_IJustCant BummerBert BummerBert_IJustCant.png IJust Cant
179BummerBert_IveMadeAHugeMistake BummerBert BummerBert_IveMadeAHugeMistake.png Ive Made AHuge Mistake
180BummerBert_IWillNeverFinish BummerBert BummerBert_IWillNeverFinish.png IWill Never Finish
181BummerBert_IWillTryAgainMaybe BummerBert BummerBert_IWillTryAgainMaybe.png IWill Try Again Maybe
182BummerBert_Meh BummerBert BummerBert_Meh.png Meh
183BummerBert_NobodyCares BummerBert BummerBert_NobodyCares.png Nobody Cares
184BummerBert_NotMe BummerBert BummerBert_NotMe.png Not Me
185BummerBert_NotSoFast BummerBert BummerBert_NotSoFast.png Not So Fast
186BummerBert_Sigh BummerBert BummerBert_Sigh.png Sigh
187BummerBert_Typical BummerBert BummerBert_Typical.png Typical
188BummerBert_WellThatFailed BummerBert BummerBert_WellThatFailed.png Well That Failed
189BummerBert_WhatIsHappiness BummerBert BummerBert_WhatIsHappiness.png What Is Happiness
190BummerBert_WhyMe BummerBert BummerBert_WhyMe.png Why Me
191BummerBert_WorkingLateAgain BummerBert BummerBert_WorkingLateAgain.png Working Late Again
192BummerBert_WrongAgain BummerBert BummerBert_WrongAgain.png Wrong Again
193CatsInSuits_Cat CatsInSuits CatsInSuits_Cat.png Cat
194CatsInSuits_Coffee CatsInSuits CatsInSuits_Coffee.png Coffee
195CatsInSuits_DogSuit CatsInSuits CatsInSuits_DogSuit.png Dog Suit
196CatsInSuits_Eating CatsInSuits CatsInSuits_Eating.png Eating
197CatsInSuits_Hairball CatsInSuits CatsInSuits_Hairball.png Hairball
198CatsInSuits_Injured CatsInSuits CatsInSuits_Injured.png Injured
199CatsInSuits_Jump CatsInSuits CatsInSuits_Jump.png Jump
200CatsInSuits_Keyboard CatsInSuits CatsInSuits_Keyboard.png Keyboard
201CatsInSuits_Lick CatsInSuits CatsInSuits_Lick.png Lick
202CatsInSuits_Mouse CatsInSuits CatsInSuits_Mouse.png Mouse
203CatsInSuits_OfficeChair CatsInSuits CatsInSuits_OfficeChair.png Office Chair
204CatsInSuits_PassOut CatsInSuits CatsInSuits_PassOut.png Pass Out
205CatsInSuits_Question CatsInSuits CatsInSuits_Question.png Question
206CatsInSuits_RollOver CatsInSuits CatsInSuits_RollOver.png Roll Over
207CatsInSuits_Scared CatsInSuits CatsInSuits_Scared.png Scared
208CatsInSuits_Shy CatsInSuits CatsInSuits_Shy.png Shy
209CatsInSuits_SleepInSun CatsInSuits CatsInSuits_SleepInSun.png Sleep In Sun
210CatsInSuits_SleepOnDesk CatsInSuits CatsInSuits_SleepOnDesk.png Sleep On Desk
211CatsInSuits_WaterSpill CatsInSuits CatsInSuits_WaterSpill.png Water Spill
212CatsInSuits_Window CatsInSuits CatsInSuits_Window.png Window
213CatsInSuits_Yarn CatsInSuits CatsInSuits_Yarn.png Yarn
214Monkey_Attack Monkey Monkey_Attack.png Attack
215Monkey_Banana Monkey Monkey_Banana.png Banana
216Monkey_Basic Monkey Monkey_Basic.png Basic
217Monkey_Bored Monkey Monkey_Bored.png Bored
218Monkey_Cheer Monkey Monkey_Cheer.png Cheer
219Monkey_Cool Monkey Monkey_Cool.png Cool
220Monkey_Dance Monkey Monkey_Dance.png Dance
221Monkey_Disguise Monkey Monkey_Disguise.png Disguise
222Monkey_Dissed Monkey Monkey_Dissed.png Dissed
223Monkey_Dumbstruck Monkey Monkey_Dumbstruck.png Dumbstruck
224Monkey_Encourage Monkey Monkey_Encourage.png Encourage
225Monkey_FaceDown Monkey Monkey_FaceDown.png Face Down
226Monkey_Frustrated Monkey Monkey_Frustrated.png Frustrated
227Monkey_Furious Monkey Monkey_Furious.png Furious
228Monkey_HearNoEvil Monkey Monkey_HearNoEvil.png Hear No Evil
229Monkey_Jump Monkey Monkey_Jump.png Jump
230Monkey_Photo Monkey Monkey_Photo.png Photo
231Monkey_Run Monkey Monkey_Run.png Run
232Monkey_SeeNoEvil Monkey Monkey_SeeNoEvil.png See No Evil
233Monkey_Shrug Monkey Monkey_Shrug.png Shrug
234Monkey_Sleep Monkey Monkey_Sleep.png Sleep
235Monkey_Sneak Monkey Monkey_Sneak.png Sneak
236Monkey_SpeakNoEvil Monkey Monkey_SpeakNoEvil.png Speak No Evil
237Monkey_Stressed Monkey Monkey_Stressed.png Stressed
238Monkey_Tears Monkey Monkey_Tears.png Tears
239Monkey_Think Monkey Monkey_Think.png Think
240Monkey_ThumbsUp Monkey Monkey_ThumbsUp.png Thumbs Up
241Monkey_WornOut Monkey Monkey_WornOut.png Worn Out
242Octocorn_Amazed Octocorn Octocorn_Amazed.png Amazed
243Octocorn_Awe Octocorn Octocorn_Awe.png Awe
244Octocorn_Barf Octocorn Octocorn_Barf.png Barf
245Octocorn_Coffee Octocorn Octocorn_Coffee.png Coffee
246Octocorn_Cold Octocorn Octocorn_Cold.png Cold
247Octocorn_Command Octocorn Octocorn_Command.png Command
248Octocorn_Confident Octocorn Octocorn_Confident.png Confident
249Octocorn_Confused Octocorn Octocorn_Confused.png Confused
250Octocorn_Creepy Octocorn Octocorn_Creepy.png Creepy
251Octocorn_Crosseye Octocorn Octocorn_Crosseye.png Crosseye
252Octocorn_Cry Octocorn Octocorn_Cry.png Cry
253Octocorn_Derp Octocorn Octocorn_Derp.png Derp
254Octocorn_Devious Octocorn Octocorn_Devious.png Devious
255Octocorn_Drunk Octocorn Octocorn_Drunk.png Drunk
256Octocorn_Eager Octocorn Octocorn_Eager.png Eager
257Octocorn_Enthused Octocorn Octocorn_Enthused.png Enthused
258Octocorn_Excited Octocorn Octocorn_Excited.png Excited
259Octocorn_FacePlant Octocorn Octocorn_FacePlant.png Face Plant
260Octocorn_Fly Octocorn Octocorn_Fly.png Fly
261Octocorn_Formal Octocorn Octocorn_Formal.png Formal
262Octocorn_Giggle Octocorn Octocorn_Giggle.png Giggle
263Octocorn_Goofy Octocorn Octocorn_Goofy.png Goofy
264Octocorn_Happy Octocorn Octocorn_Happy.png Happy
265Octocorn_Hot Octocorn Octocorn_Hot.png Hot
266Octocorn_KnockedOver Octocorn Octocorn_KnockedOver.png Knocked Over
267Octocorn_Laugh Octocorn Octocorn_Laugh.png Laugh
268Octocorn_Ouch Octocorn Octocorn_Ouch.png Ouch
269Octocorn_Proud Octocorn Octocorn_Proud.png Proud
270Octocorn_Question Octocorn Octocorn_Question.png Question
271Octocorn_Rage Octocorn Octocorn_Rage.png Rage
272Octocorn_Sad Octocorn Octocorn_Sad.png Sad
273Octocorn_Salute Octocorn Octocorn_Salute.png Salute
274Octocorn_Scared Octocorn Octocorn_Scared.png Scared
275Octocorn_Shy Octocorn Octocorn_Shy.png Shy
276Octocorn_Sick Octocorn Octocorn_Sick.png Sick
277Octocorn_Simple Octocorn Octocorn_Simple.png Simple
278Octocorn_Sleep Octocorn Octocorn_Sleep.png Sleep
279Octocorn_Slow Octocorn Octocorn_Slow.png Slow
280Octocorn_Startled Octocorn Octocorn_Startled.png Startled
281Octocorn_Stretch Octocorn Octocorn_Stretch.png Stretch
282Octocorn_Study Octocorn Octocorn_Study.png Study
283Octocorn_Stunned Octocorn Octocorn_Stunned.png Stunned
284Octocorn_Stupified Octocorn Octocorn_Stupified.png Stupified
285Octocorn_Suspicious Octocorn Octocorn_Suspicious.png Suspicious
286Octocorn_Terror Octocorn Octocorn_Terror.png Terror
287Octocorn_Thinking Octocorn Octocorn_Thinking.png Thinking
288Octocorn_Tongue Octocorn Octocorn_Tongue.png Tongue
289Octocorn_Tough Octocorn Octocorn_Tough.png Tough
290Octocorn_Twitch Octocorn Octocorn_Twitch.png Twitch
291Octocorn_Upset Octocorn Octocorn_Upset.png Upset
292Broccoli_Angry Broccoli stickerbroccoliangry.png Angry
293Broccoli_Confused Broccoli stickerbroccoliconfused.png Confused
294Broccoli_FistBump Broccoli stickerbroccolifistbump.png Fist Bump
295Broccoli_GreatJobTeam Broccoli stickerbroccoligreatjob.png Great Job Team
296Broccoli_HiFive Broccoli stickerbroccolihifive.png Hi Five
297Broccoli_Cool Broccoli stickerbroccolicool.png Cool
298Broccoli_Like Broccoli stickerbroccolilike.png Like
299Broccoli_NotMushroom Broccoli stickerbroccolinotmushroom.png Not Mushroom
300Broccoli_WOW Broccoli stickerbroccoliwow.png WOW
301Broccoli_Overwhelmed Broccoli stickerbroccolioverwhelmed.png Overwhelmed
302Broccoli_Party Broccoli stickerbroccoliparty.png Party
303Broccoli_Sad Broccoli stickerbroccolisad.png Sad
304Broccoli_Cold Broccoli stickerbroccolicold.png Cold
305Broccoli_OnMyWay Broccoli stickerbroccoliomw.png On My Way
306Broccoli_TeamCheers Broccoli stickerbroccoliteamcheers.png Team Cheers
307Broccoli_TeamHuddle Broccoli stickerbroccoliteamhuddle.png Team Huddle
308Broccoli_Tired Broccoli stickerbroccolitired.png Tired
309Broccoli_Trapped Broccoli stickerbroccolitrapped.png Trapped
310Broccoli_Wave Broccoli stickerbroccoliwave.png Wave
311Broccoli_WhereAreYou Broccoli stickerbroccoliwhereareyou.png Where Are You
312Bee_Angry Bee stickerbeeangry.png Angry
313Bee_Ashamed Bee stickerbeeashamed.png Ashamed
314Bee_Bored Bee stckerbeebored.png Bored
315Bee_Cheers Bee stickerbeecheers.png Cheers
316Bee_Confused Bee stickerbeeconfused.png Confused
317Bee_Happy Bee stickerbeehappy.png Happy
318Bee_Hi Bee stickerbeehi.png Hi
319Bee_HiFive Bee stickerbeehifive.png Hi Five
320Bee_Laughing Bee stickerbeelaughing.png Laughing
321Bee_Like Bee stickerbeelike.png Like
322Bee_Love Bee stickerbeelove.png Love
323Bee_MissingYou Bee stickerbeemissingyou.png Missing You
324Bee_No Bee stickerbeeno.png No
325Bee_WOW Bee stickerbeewow.png WOW
326Bee_OMW Bee stickerbeeomw.png OMW
327Bee_Party Bee stickerbeeparty.png Party
328Bee_FistBump Bee stickerbeefistbump.png Fist Bump
329Bee_Sad Bee stickerbeesad.png Sad
330Bee_Sick Bee stickerbeesick.png Sick
331Bee_Well Bee stickerbeewell.png Well
332DonutFriends_begging DonutFriends DonutFriends_begging.png begging
333DonutFriends_chagrin DonutFriends DonutFriends_chagrin.png chagrin
334DonutFriends_cheering DonutFriends DonutFriends_cheering.png cheering
335DonutFriends_crying DonutFriends DonutFriends_crying.png crying
336DonutFriends_extremeshock DonutFriends DonutFriends_extremeshock.png extremeshock
337DonutFriends_facepalm DonutFriends DonutFriends_facepalm.png facepalm
338DonutFriends_impatient DonutFriends DonutFriends_impatient.png impatient
339DonutFriends_lightbulb DonutFriends DonutFriends_lightbulb.png lightbulb
340DonutFriends_rofl DonutFriends DonutFriends_rofl.png rofl
341DonutFriends_searching DonutFriends DonutFriends_searching.png searching
342DonutFriends_thinking DonutFriends DonutFriends_thinking.png thinking
343DonutFriends_thumbsup DonutFriends DonutFriends_thumbsup.png thumbsup
344UncleBlob_Angry UncleBlob UncleBlob_Angry.png Angry
345UncleBlob_Cheer UncleBlob UncleBlob_Cheer.png Cheer
346UncleBlob_EndOfTheWorld UncleBlob UncleBlob_EndOfTheWorld.png End Of The World
347UncleBlob_HeartEyes UncleBlob UncleBlob_HeartEyes.png Heart Eyes
348UncleBlob_Hungry UncleBlob UncleBlob_Hungry.png Hungry
349UncleBlob_Laughing UncleBlob UncleBlob_Laughing.png Laughing
350UncleBlob_Pleading UncleBlob UncleBlob_Pleading.png Pleading
351UncleBlob_Shocked UncleBlob UncleBlob_Shocked.png Shocked
352UncleBlob_Sleepy UncleBlob UncleBlob_Sleepy.png Sleepy
353UncleBlob_Thinking UncleBlob UncleBlob_Thinking.png Thinking
354UncleBlob_ThumbsUp UncleBlob UncleBlob_ThumbsUp.png Thumbs Up
355UncleBlob_Unmotivated UncleBlob UncleBlob_Unmotivated.png Unmotivated
356Animalopolis_cry_mouse Animalopolis Animalopolis_cry_mouse.png cry mouse
357Animalopolis_cute_koala Animalopolis Animalopolis_cute_koala.png cute koala
358Animalopolis_excited_bunny Animalopolis Animalopolis_excited_bunny.png excited bunny
359Animalopolis_grumpy_goat Animalopolis Animalopolis_grumpy_goat.png grumpy goat
360Animalopolis_hmm_fox Animalopolis Animalopolis_hmm_fox.png hmm fox
361Animalopolis_hype_monkey Animalopolis Animalopolis_hype_monkey.png hype monkey
362Animalopolis_laughing_donkey Animalopolis Animalopolis_laughing_donkey.png laughing donkey
363Animalopolis_love_hedgehog Animalopolis Animalopolis_love_hedgehog.png love hedgehog
364Animalopolis_mad_rhino Animalopolis Animalopolis_mad_rhino.png mad rhino
365Animalopolis_oops_panda Animalopolis Animalopolis_oops_panda.png oops panda
366Animalopolis_running_cheetah Animalopolis Animalopolis_running_cheetah.png running cheetah
367Animalopolis_weird_lemur Animalopolis Animalopolis_weird_lemur.png weird lemur
368stickers_BMac_idea BMac stickers_BMac_idea.png stickers BMac idea
369stickers_BMac_like BMac stickers_BMac_like.png stickers BMac like
370stickers_BMac_nosign BMac stickers_BMac_nosign.png stickers BMac nosign
371stickers_BMac_hawaii BMac stickers_BMac_hawaii.png stickers BMac hawaii
372stickers_BMac_surprised BMac stickers_BMac_surprised.png stickers BMac surprised
373stickers_BMac_soda BMac stickers_BMac_soda.png stickers BMac soda
374stickers_BMac_nobutton BMac stickers_BMac_nobutton.png stickers BMac nobutton
375stickers_BMac_singing BMac stickers_BMac_singing.png stickers BMac singing
376stickers_BMac_giraffe BMac stickers_BMac_giraffe.png stickers BMac giraffe
377stickers_Bmac_nope BMac stickers_Bmac_nope.png stickers Bmac nope
378stickers_Bmac_tacos BMac stickers_Bmac_tacos.png stickers Bmac tacos
379Food_Beer Food Food_Beer.png Beer
380Food_Burger Food Food_Burger.png Burger
381Food_Burrito Food Food_Burrito.png Burrito
382Food_Cake Food Food_Cake.png Cake
383Food_Cocktail Food Food_Cocktail.png Cocktail
384Food_Coffee Food Food_Coffee.png Coffee
385Food_Cupcake Food Food_Cupcake.png Cupcake
386Food_DimSum Food Food_DimSum.png Dim Sum
387Food_Donut Food Food_Donut.png Donut
388Food_Fries Food Food_Fries.png Fries
389Food_GeneralTso Food Food_GeneralTso.png General Tso
390Food_HotDog Food Food_HotDog.png Hot Dog
391Food_IceCream Food Food_IceCream.png Ice Cream
392Food_MixedDrink Food Food_MixedDrink.png Mixed Drink
393Food_Pita Food Food_Pita.png Pita
394Food_Pizza Food Food_Pizza.png Pizza
395Food_Ramen Food Food_Ramen.png Ramen
396Food_Salad Food Food_Salad.png Salad
397Food_Sandwich Food Food_Sandwich.png Sandwich
398Food_Sashimi Food Food_Sashimi.png Sashimi
399Food_Soup Food Food_Soup.png Soup
400Food_Spaghetti Food Food_Spaghetti.png Spaghetti
401Food_StreetTaco Food Food_StreetTaco.png Street Taco
402Food_Sushi Food Food_Sushi.png Sushi
403Food_Taco Food Food_Taco.png Taco
404Food_Tea Food Food_Tea.png Tea
crates/app/assets/symbols/mood.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" x2="9.01" y1="9" y2="9"/><line x1="15" x2="15.01" y1="9" y2="9"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" x2="9.01" y1="9" y2="9"/><line x1="15" x2="15.01" y1="9" y2="9"/></svg>
crates/app/src/assets.rs +2 −1
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 23] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 24] = symbols![
12 12 "done",
13 13 "done_all",
14 14 "keyboard_return",
@@ -32,6 +32,7 @@ const SYMBOLS: [(&str, &[u8]); 23] = symbols![
32 32 "format_list_bulleted",
33 33 "format_list_numbered",
34 34 "format_quote",
35 "mood",
35 36 ];
36 37
37 38 pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 23] = symbols![
11const SYMBOLS: [(&str, &[u8]); 24] = symbols![
12 "done",
12 "done",
13 "done_all",
13 "done_all",
14 "keyboard_return",
14 "keyboard_return",
@@ -32,6 +32,7 @@ const SYMBOLS: [(&str, &[u8]); 23] = symbols![
32 "format_list_bulleted",
32 "format_list_bulleted",
33 "format_list_numbered",
33 "format_list_numbered",
34 "format_quote",
34 "format_quote",
35 "mood",
35];
36];
36
37
37pub struct AppAssets;
38pub struct AppAssets;
crates/app/src/demo.rs +36 −2
@@ -1,5 +1,5 @@
1 1 use std::path::PathBuf;
2 use std::sync::Arc;
2 use std::sync::{Arc, OnceLock};
3 3 use std::time::Instant;
4 4
5 5 use chrono::{DateTime, Duration, Local, TimeZone, Utc};
@@ -9,7 +9,7 @@ use store::{
9 9 TeamLayoutRecord, TeamRecord,
10 10 };
11 11 use teams_core::{
12 CardActionOutcome, ChatApp, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
12 CardActionOutcome, ChatApp, Gif, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
13 13 TaskDialog,
14 14 TaskDialogKind,
15 15 };
@@ -18,6 +18,9 @@ use crate::activity::{Actor, Entry, Kind};
18 18 use crate::app_state::{AppState, Selection};
19 19 use crate::card_actions::{CardAnswer, CardTask};
20 20 use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
21 use crate::demo_gifs;
22
23 static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
21 24
22 25 pub const DEMO_USER_ID: &str = "demo-me";
23 26 const DEMO_USER_NAME: &str = "Dana Demo";
@@ -424,6 +427,17 @@ fn image_directory() -> PathBuf {
424 427 std::env::temp_dir().join("rusty-teams-demo")
425 428 }
426 429
430 pub fn search_gifs(query: &str) -> Vec<Gif> {
431 let query = query.trim().to_lowercase();
432 SEARCHABLE_GIFS
433 .get()
434 .into_iter()
435 .flatten()
436 .filter(|gif| gif.title.to_lowercase().contains(&query))
437 .cloned()
438 .collect()
439 }
440
427 441 pub fn first_unread(conversation_id: &str) -> Option<String> {
428 442 (conversation_id == UNREAD_CHAT).then(|| "u3".to_owned())
429 443 }
@@ -655,6 +669,11 @@ pub fn seed_directory(state: &mut AppState) {
655 669 state.directory.set_image(STAGING_IMAGE_KEY, &path);
656 670 state.directory.set_image(LINK_IMAGE_KEY, &path);
657 671 }
672 let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
673 state.directory.set_image(
674 demo_gifs::RECEIVED_GIF_KEY,
675 &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
676 );
658 677 }
659 678 state.typing.start(
660 679 "demo-chat-mara",
@@ -1142,6 +1161,21 @@ fn release_messages() -> Vec<MessageRecord> {
1142 1161 "[]",
1143 1162 false,
1144 1163 ),
1164 message(
1165 chat,
1166 "m9",
1167 None,
1168 (PRIYA_ID, priya_name),
1169 at(0, 13, 45),
1170 &format!(
1171 "<p>Ship it!</p><img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"Party\" itemtype=\"http://schema.skype.com/Giphy\">",
1172 demo_gifs::RECEIVED_GIF_KEY,
1173 demo_gifs::RECEIVED_GIF_SIZE.0,
1174 demo_gifs::RECEIVED_GIF_SIZE.1
1175 ),
1176 "[]",
1177 false,
1178 ),
1145 1179 ]
1146 1180 }
1147 1181
@@ -1,5 +1,5 @@
1use std::path::PathBuf;
1use std::path::PathBuf;
2use std::sync::Arc;
2use std::sync::{Arc, OnceLock};
3use std::time::Instant;
3use std::time::Instant;
4
4
5use chrono::{DateTime, Duration, Local, TimeZone, Utc};
5use chrono::{DateTime, Duration, Local, TimeZone, Utc};
@@ -9,7 +9,7 @@ use store::{
9 TeamLayoutRecord, TeamRecord,
9 TeamLayoutRecord, TeamRecord,
10};
10};
11use teams_core::{
11use teams_core::{
12 CardActionOutcome, ChatApp, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
12 CardActionOutcome, ChatApp, Gif, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
13 TaskDialog,
13 TaskDialog,
14 TaskDialogKind,
14 TaskDialogKind,
15};
15};
@@ -18,6 +18,9 @@ use crate::activity::{Actor, Entry, Kind};
18use crate::app_state::{AppState, Selection};
18use crate::app_state::{AppState, Selection};
19use crate::card_actions::{CardAnswer, CardTask};
19use crate::card_actions::{CardAnswer, CardTask};
20use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
20use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
21use crate::demo_gifs;
22
23static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
21
24
22pub const DEMO_USER_ID: &str = "demo-me";
25pub const DEMO_USER_ID: &str = "demo-me";
23const DEMO_USER_NAME: &str = "Dana Demo";
26const DEMO_USER_NAME: &str = "Dana Demo";
@@ -424,6 +427,17 @@ fn image_directory() -> PathBuf {
424 std::env::temp_dir().join("rusty-teams-demo")
427 std::env::temp_dir().join("rusty-teams-demo")
425}
428}
426
429
430pub fn search_gifs(query: &str) -> Vec<Gif> {
431 let query = query.trim().to_lowercase();
432 SEARCHABLE_GIFS
433 .get()
434 .into_iter()
435 .flatten()
436 .filter(|gif| gif.title.to_lowercase().contains(&query))
437 .cloned()
438 .collect()
439}
440
427pub fn first_unread(conversation_id: &str) -> Option<String> {
441pub fn first_unread(conversation_id: &str) -> Option<String> {
428 (conversation_id == UNREAD_CHAT).then(|| "u3".to_owned())
442 (conversation_id == UNREAD_CHAT).then(|| "u3".to_owned())
429}
443}
@@ -655,6 +669,11 @@ pub fn seed_directory(state: &mut AppState) {
655 state.directory.set_image(STAGING_IMAGE_KEY, &path);
669 state.directory.set_image(STAGING_IMAGE_KEY, &path);
656 state.directory.set_image(LINK_IMAGE_KEY, &path);
670 state.directory.set_image(LINK_IMAGE_KEY, &path);
657 }
671 }
672 let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
673 state.directory.set_image(
674 demo_gifs::RECEIVED_GIF_KEY,
675 &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
676 );
658 }
677 }
659 state.typing.start(
678 state.typing.start(
660 "demo-chat-mara",
679 "demo-chat-mara",
@@ -1142,6 +1161,21 @@ fn release_messages() -> Vec<MessageRecord> {
1142 "[]",
1161 "[]",
1143 false,
1162 false,
1144 ),
1163 ),
1164 message(
1165 chat,
1166 "m9",
1167 None,
1168 (PRIYA_ID, priya_name),
1169 at(0, 13, 45),
1170 &format!(
1171 "<p>Ship it!</p><img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"Party\" itemtype=\"http://schema.skype.com/Giphy\">",
1172 demo_gifs::RECEIVED_GIF_KEY,
1173 demo_gifs::RECEIVED_GIF_SIZE.0,
1174 demo_gifs::RECEIVED_GIF_SIZE.1
1175 ),
1176 "[]",
1177 false,
1178 ),
1145 ]
1179 ]
1146}
1180}
1147
1181
crates/app/src/demo_gifs.rs added +169 −0
@@ -0,0 +1,169 @@
1 use std::path::Path;
2
3 use image::codecs::gif::{GifEncoder, Repeat};
4 use image::{Delay, Frame, Rgba, RgbaImage};
5 use teams_core::Gif;
6
7 pub const RECEIVED_GIF_KEY: &str = "demo://party-gif";
8 pub const RECEIVED_GIF_NAME: &str = "party";
9 pub const RECEIVED_GIF_SIZE: (u32, u32) = (200, 150);
10 const FRAME_COUNT: u32 = 10;
11 const FRAME_DELAY_MILLIS: u32 = 90;
12
13 struct DemoGif {
14 name: &'static str,
15 title: &'static str,
16 size: (u32, u32),
17 hue: f32,
18 }
19
20 const DEMO_GIFS: [DemoGif; 9] = [
21 DemoGif {
22 name: "thumbs-up",
23 title: "Thumbs up",
24 size: (160, 160),
25 hue: 210.,
26 },
27 DemoGif {
28 name: "applause",
29 title: "Applause",
30 size: (200, 112),
31 hue: 30.,
32 },
33 DemoGif {
34 name: RECEIVED_GIF_NAME,
35 title: "Party",
36 size: RECEIVED_GIF_SIZE,
37 hue: 320.,
38 },
39 DemoGif {
40 name: "wave",
41 title: "Wave",
42 size: (150, 200),
43 hue: 150.,
44 },
45 DemoGif {
46 name: "laughing",
47 title: "Laughing",
48 size: (180, 135),
49 hue: 50.,
50 },
51 DemoGif {
52 name: "thank-you",
53 title: "Thank you",
54 size: (200, 100),
55 hue: 0.,
56 },
57 DemoGif {
58 name: "coffee",
59 title: "Coffee",
60 size: (140, 140),
61 hue: 20.,
62 },
63 DemoGif {
64 name: "dancing",
65 title: "Dancing",
66 size: (160, 200),
67 hue: 270.,
68 },
69 DemoGif {
70 name: "well-done",
71 title: "Well done",
72 size: (200, 120),
73 hue: 180.,
74 },
75 ];
76
77 pub fn file_name(name: &str) -> String {
78 format!("{name}.gif")
79 }
80
81 /// Writes the demo GIFs into `directory` and describes them like search results, with file paths as URLs.
82 pub fn generate(directory: &Path) -> Vec<Gif> {
83 DEMO_GIFS
84 .iter()
85 .filter_map(|demo| {
86 let path = directory.join(file_name(demo.name));
87 std::fs::write(&path, encode(demo)).ok()?;
88 let location = path.to_string_lossy().into_owned();
89 Some(Gif {
90 url: location.clone(),
91 preview_url: location,
92 title: demo.title.to_owned(),
93 width: demo.size.0,
94 height: demo.size.1,
95 preview_width: demo.size.0,
96 preview_height: demo.size.1,
97 })
98 })
99 .collect()
100 }
101
102 fn encode(demo: &DemoGif) -> Vec<u8> {
103 let mut bytes = Vec::new();
104 {
105 let mut encoder = GifEncoder::new_with_speed(&mut bytes, 30);
106 let _ = encoder.set_repeat(Repeat::Infinite);
107 for index in 0..FRAME_COUNT {
108 let frame = Frame::from_parts(
109 frame_image(demo, index),
110 0,
111 0,
112 Delay::from_numer_denom_ms(FRAME_DELAY_MILLIS, 1),
113 );
114 let _ = encoder.encode_frame(frame);
115 }
116 }
117 bytes
118 }
119
120 fn frame_image(demo: &DemoGif, index: u32) -> RgbaImage {
121 let (width, height) = demo.size;
122 let progress = index as f32 / FRAME_COUNT as f32;
123 let center_x = width as f32 * (0.5 + 0.3 * (progress * std::f32::consts::TAU).sin());
124 let center_y = height as f32 * (0.5 + 0.2 * (progress * std::f32::consts::TAU).cos());
125 let radius = width.min(height) as f32 * 0.22;
126 RgbaImage::from_fn(width, height, |x, y| {
127 let distance = ((x as f32 - center_x).powi(2) + (y as f32 - center_y).powi(2)).sqrt();
128 if distance < radius {
129 return Rgba([255, 255, 255, 255]);
130 }
131 let shade = 0.35 + 0.35 * (y as f32 / height as f32);
132 let [red, green, blue] = hsv(demo.hue + progress * 40., 0.6, shade + 0.15);
133 Rgba([red, green, blue, 255])
134 })
135 }
136
137 fn hsv(hue: f32, saturation: f32, value: f32) -> [u8; 3] {
138 let hue = hue.rem_euclid(360.) / 60.;
139 let chroma = value * saturation;
140 let second = chroma * (1. - (hue % 2. - 1.).abs());
141 let (red, green, blue) = match hue as u32 {
142 0 => (chroma, second, 0.),
143 1 => (second, chroma, 0.),
144 2 => (0., chroma, second),
145 3 => (0., second, chroma),
146 4 => (second, 0., chroma),
147 _ => (chroma, 0., second),
148 };
149 let offset = value - chroma;
150 [red, green, blue].map(|channel| ((channel + offset) * 255.).round() as u8)
151 }
152
153 #[cfg(test)]
154 mod tests {
155 use super::*;
156
157 #[test]
158 fn generated_gifs_are_animated_files_with_their_declared_size() {
159 let directory = tempfile::tempdir().unwrap();
160 let gifs = generate(directory.path());
161 assert_eq!(gifs.len(), DEMO_GIFS.len());
162 let first = std::fs::read(&gifs[0].url).unwrap();
163 assert!(first.starts_with(b"GIF89a"));
164 assert_eq!(
165 image::image_dimensions(&gifs[0].url).unwrap(),
166 (gifs[0].width, gifs[0].height)
167 );
168 }
169 }
@@ -0,0 +1,169 @@
1use std::path::Path;
2
3use image::codecs::gif::{GifEncoder, Repeat};
4use image::{Delay, Frame, Rgba, RgbaImage};
5use teams_core::Gif;
6
7pub const RECEIVED_GIF_KEY: &str = "demo://party-gif";
8pub const RECEIVED_GIF_NAME: &str = "party";
9pub const RECEIVED_GIF_SIZE: (u32, u32) = (200, 150);
10const FRAME_COUNT: u32 = 10;
11const FRAME_DELAY_MILLIS: u32 = 90;
12
13struct DemoGif {
14 name: &'static str,
15 title: &'static str,
16 size: (u32, u32),
17 hue: f32,
18}
19
20const DEMO_GIFS: [DemoGif; 9] = [
21 DemoGif {
22 name: "thumbs-up",
23 title: "Thumbs up",
24 size: (160, 160),
25 hue: 210.,
26 },
27 DemoGif {
28 name: "applause",
29 title: "Applause",
30 size: (200, 112),
31 hue: 30.,
32 },
33 DemoGif {
34 name: RECEIVED_GIF_NAME,
35 title: "Party",
36 size: RECEIVED_GIF_SIZE,
37 hue: 320.,
38 },
39 DemoGif {
40 name: "wave",
41 title: "Wave",
42 size: (150, 200),
43 hue: 150.,
44 },
45 DemoGif {
46 name: "laughing",
47 title: "Laughing",
48 size: (180, 135),
49 hue: 50.,
50 },
51 DemoGif {
52 name: "thank-you",
53 title: "Thank you",
54 size: (200, 100),
55 hue: 0.,
56 },
57 DemoGif {
58 name: "coffee",
59 title: "Coffee",
60 size: (140, 140),
61 hue: 20.,
62 },
63 DemoGif {
64 name: "dancing",
65 title: "Dancing",
66 size: (160, 200),
67 hue: 270.,
68 },
69 DemoGif {
70 name: "well-done",
71 title: "Well done",
72 size: (200, 120),
73 hue: 180.,
74 },
75];
76
77pub fn file_name(name: &str) -> String {
78 format!("{name}.gif")
79}
80
81/// Writes the demo GIFs into `directory` and describes them like search results, with file paths as URLs.
82pub fn generate(directory: &Path) -> Vec<Gif> {
83 DEMO_GIFS
84 .iter()
85 .filter_map(|demo| {
86 let path = directory.join(file_name(demo.name));
87 std::fs::write(&path, encode(demo)).ok()?;
88 let location = path.to_string_lossy().into_owned();
89 Some(Gif {
90 url: location.clone(),
91 preview_url: location,
92 title: demo.title.to_owned(),
93 width: demo.size.0,
94 height: demo.size.1,
95 preview_width: demo.size.0,
96 preview_height: demo.size.1,
97 })
98 })
99 .collect()
100}
101
102fn encode(demo: &DemoGif) -> Vec<u8> {
103 let mut bytes = Vec::new();
104 {
105 let mut encoder = GifEncoder::new_with_speed(&mut bytes, 30);
106 let _ = encoder.set_repeat(Repeat::Infinite);
107 for index in 0..FRAME_COUNT {
108 let frame = Frame::from_parts(
109 frame_image(demo, index),
110 0,
111 0,
112 Delay::from_numer_denom_ms(FRAME_DELAY_MILLIS, 1),
113 );
114 let _ = encoder.encode_frame(frame);
115 }
116 }
117 bytes
118}
119
120fn frame_image(demo: &DemoGif, index: u32) -> RgbaImage {
121 let (width, height) = demo.size;
122 let progress = index as f32 / FRAME_COUNT as f32;
123 let center_x = width as f32 * (0.5 + 0.3 * (progress * std::f32::consts::TAU).sin());
124 let center_y = height as f32 * (0.5 + 0.2 * (progress * std::f32::consts::TAU).cos());
125 let radius = width.min(height) as f32 * 0.22;
126 RgbaImage::from_fn(width, height, |x, y| {
127 let distance = ((x as f32 - center_x).powi(2) + (y as f32 - center_y).powi(2)).sqrt();
128 if distance < radius {
129 return Rgba([255, 255, 255, 255]);
130 }
131 let shade = 0.35 + 0.35 * (y as f32 / height as f32);
132 let [red, green, blue] = hsv(demo.hue + progress * 40., 0.6, shade + 0.15);
133 Rgba([red, green, blue, 255])
134 })
135}
136
137fn hsv(hue: f32, saturation: f32, value: f32) -> [u8; 3] {
138 let hue = hue.rem_euclid(360.) / 60.;
139 let chroma = value * saturation;
140 let second = chroma * (1. - (hue % 2. - 1.).abs());
141 let (red, green, blue) = match hue as u32 {
142 0 => (chroma, second, 0.),
143 1 => (second, chroma, 0.),
144 2 => (0., chroma, second),
145 3 => (0., second, chroma),
146 4 => (second, 0., chroma),
147 _ => (chroma, 0., second),
148 };
149 let offset = value - chroma;
150 [red, green, blue].map(|channel| ((channel + offset) * 255.).round() as u8)
151}
152
153#[cfg(test)]
154mod tests {
155 use super::*;
156
157 #[test]
158 fn generated_gifs_are_animated_files_with_their_declared_size() {
159 let directory = tempfile::tempdir().unwrap();
160 let gifs = generate(directory.path());
161 assert_eq!(gifs.len(), DEMO_GIFS.len());
162 let first = std::fs::read(&gifs[0].url).unwrap();
163 assert!(first.starts_with(b"GIF89a"));
164 assert_eq!(
165 image::image_dimensions(&gifs[0].url).unwrap(),
166 (gifs[0].width, gifs[0].height)
167 );
168 }
169}
crates/app/src/emoji/mod.rs +4 −0
@@ -141,6 +141,10 @@ fn best_match(emoji: &'static Emoji, query: &str) -> Option<(Tier, usize, Match)
141 141 ))
142 142 }
143 143
144 pub fn glyphs() -> impl Iterator<Item = &'static str> {
145 index().iter().map(|emoji| emoji.glyph)
146 }
147
144 148 /// Ranked by: recent, exact, English prefix, German prefix, word start, contains, emoji order.
145 149 pub fn search(query: &str, recent: &[String], limit: usize) -> Vec<Match> {
146 150 let query = query.to_lowercase();
@@ -141,6 +141,10 @@ fn best_match(emoji: &'static Emoji, query: &str) -> Option<(Tier, usize, Match)
141 ))
141 ))
142}
142}
143
143
144pub fn glyphs() -> impl Iterator<Item = &'static str> {
145 index().iter().map(|emoji| emoji.glyph)
146}
147
144/// Ranked by: recent, exact, English prefix, German prefix, word start, contains, emoji order.
148/// Ranked by: recent, exact, English prefix, German prefix, word start, contains, emoji order.
145pub fn search(query: &str, recent: &[String], limit: usize) -> Vec<Match> {
149pub fn search(query: &str, recent: &[String], limit: usize) -> Vec<Match> {
146 let query = query.to_lowercase();
150 let query = query.to_lowercase();
crates/app/src/gifs.rs added +36 −0
@@ -0,0 +1,36 @@
1 use std::sync::Arc;
2
3 use teams_core::{Error, Gif};
4 use tokio::sync::oneshot;
5
6 use crate::backend::Engine;
7 use crate::{demo, runtime};
8
9 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
10 pub enum GifError {
11 Disabled,
12 Failed,
13 }
14
15 pub type GifSearch = oneshot::Receiver<Result<Vec<Gif>, GifError>>;
16
17 /// An empty query returns the trending GIFs. Demo mode answers from generated local files.
18 pub fn search(engine: Option<Arc<Engine>>, demo_mode: bool, query: String) -> GifSearch {
19 if demo_mode {
20 return runtime::spawn(async move { Ok(demo::search_gifs(&query)) });
21 }
22 let Some(engine) = engine else {
23 let (sender, receiver) = oneshot::channel();
24 let _ = sender.send(Err(GifError::Failed));
25 return receiver;
26 };
27 runtime::spawn(async move {
28 engine
29 .search_gifs(&query)
30 .await
31 .map_err(|error| match error {
32 Error::GifsDisabled => GifError::Disabled,
33 _ => GifError::Failed,
34 })
35 })
36 }
@@ -0,0 +1,36 @@
1use std::sync::Arc;
2
3use teams_core::{Error, Gif};
4use tokio::sync::oneshot;
5
6use crate::backend::Engine;
7use crate::{demo, runtime};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum GifError {
11 Disabled,
12 Failed,
13}
14
15pub type GifSearch = oneshot::Receiver<Result<Vec<Gif>, GifError>>;
16
17/// An empty query returns the trending GIFs. Demo mode answers from generated local files.
18pub fn search(engine: Option<Arc<Engine>>, demo_mode: bool, query: String) -> GifSearch {
19 if demo_mode {
20 return runtime::spawn(async move { Ok(demo::search_gifs(&query)) });
21 }
22 let Some(engine) = engine else {
23 let (sender, receiver) = oneshot::channel();
24 let _ = sender.send(Err(GifError::Failed));
25 return receiver;
26 };
27 runtime::spawn(async move {
28 engine
29 .search_gifs(&query)
30 .await
31 .map_err(|error| match error {
32 Error::GifsDisabled => GifError::Disabled,
33 _ => GifError::Failed,
34 })
35 })
36}
crates/app/src/main.rs +4 −0
@@ -15,21 +15,25 @@ mod crash_log;
15 15 mod card_state;
16 16 mod data;
17 17 mod demo;
18 mod demo_gifs;
18 19 mod downloads;
19 20 mod emoji;
20 21 mod format;
21 22 mod frame_log;
22 23 mod fuzzy;
24 mod gifs;
23 25 mod notice;
24 26 mod notify;
25 27 mod people;
26 28 mod reaction_model;
27 29 mod read_state;
30 mod remote_image;
28 31 mod render;
29 32 mod rows;
30 33 mod runtime;
31 34 mod single_instance;
32 35 mod sidebar_model;
36 mod stickers;
33 37 mod task_dialog;
34 38 mod theme;
35 39 mod typing;
@@ -15,21 +15,25 @@ mod crash_log;
15mod card_state;
15mod card_state;
16mod data;
16mod data;
17mod demo;
17mod demo;
18mod demo_gifs;
18mod downloads;
19mod downloads;
19mod emoji;
20mod emoji;
20mod format;
21mod format;
21mod frame_log;
22mod frame_log;
22mod fuzzy;
23mod fuzzy;
24mod gifs;
23mod notice;
25mod notice;
24mod notify;
26mod notify;
25mod people;
27mod people;
26mod reaction_model;
28mod reaction_model;
27mod read_state;
29mod read_state;
30mod remote_image;
28mod render;
31mod render;
29mod rows;
32mod rows;
30mod runtime;
33mod runtime;
31mod single_instance;
34mod single_instance;
32mod sidebar_model;
35mod sidebar_model;
36mod stickers;
33mod task_dialog;
37mod task_dialog;
34mod theme;
38mod theme;
35mod typing;
39mod typing;
crates/app/src/remote_image.rs added +133 −0
@@ -0,0 +1,133 @@
1 use gpui_kit::{ImageSource, SharedString};
2 use teams_core::{Gif, ImageRef};
3
4 use crate::stickers::Sticker;
5
6 pub const MAX_HEIGHT: u32 = 250;
7 const STICKER_SIZE: u32 = 250;
8 const GIF_ITEMTYPE: &str = "http://schema.skype.com/Giphy";
9 const STICKER_ITEMTYPE: &str = "http://schema.skype.com/Sticker";
10
11 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
12 pub enum RemoteKind {
13 Gif,
14 Sticker,
15 }
16
17 /// A GIF or sticker the message points at by URL; nothing is uploaded.
18 #[derive(Debug, Clone, PartialEq, Eq)]
19 pub struct RemoteImage {
20 pub kind: RemoteKind,
21 pub url: String,
22 pub title: String,
23 pub width: u32,
24 pub height: u32,
25 }
26
27 impl RemoteImage {
28 pub fn gif(gif: &Gif) -> Self {
29 let (width, height) = capped(gif.width, gif.height);
30 RemoteImage {
31 kind: RemoteKind::Gif,
32 url: gif.url.clone(),
33 title: gif.title.clone(),
34 width,
35 height,
36 }
37 }
38
39 pub fn sticker(sticker: &Sticker) -> Self {
40 RemoteImage {
41 kind: RemoteKind::Sticker,
42 url: sticker.url(),
43 title: sticker.name.to_owned(),
44 width: STICKER_SIZE,
45 height: STICKER_SIZE,
46 }
47 }
48
49 pub fn html(&self) -> String {
50 let itemtype = match self.kind {
51 RemoteKind::Gif => GIF_ITEMTYPE,
52 RemoteKind::Sticker => STICKER_ITEMTYPE,
53 };
54 format!(
55 "<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{itemtype}\">",
56 teams_core::escape_html(&self.url),
57 self.width,
58 self.height,
59 teams_core::escape_html(&self.title),
60 )
61 }
62
63 pub fn image_ref(&self) -> ImageRef {
64 ImageRef {
65 id: self.url.clone(),
66 url: self.url.clone(),
67 width: Some(self.width),
68 height: Some(self.height),
69 }
70 }
71 }
72
73 /// Height capped at `MAX_HEIGHT`, aspect ratio kept.
74 pub fn capped(width: u32, height: u32) -> (u32, u32) {
75 if height <= MAX_HEIGHT || height == 0 {
76 return (width, height);
77 }
78 let scaled =
79 (u64::from(width) * u64::from(MAX_HEIGHT) + u64::from(height) / 2) / u64::from(height);
80 ((scaled as u32).max(1), MAX_HEIGHT)
81 }
82
83 /// Web URLs load through the app's HTTP client, anything else is a local file (demo mode).
84 pub fn image_source(location: &str) -> ImageSource {
85 if location.starts_with("https://") {
86 ImageSource::from(SharedString::from(location.to_owned()))
87 } else {
88 ImageSource::from(std::path::PathBuf::from(location))
89 }
90 }
91
92 #[cfg(test)]
93 mod tests {
94 use super::*;
95
96 fn gif(width: u32, height: u32) -> Gif {
97 Gif {
98 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
99 preview_url: "https://media0.giphy.com/media/a/200w.gif".into(),
100 title: "Say \"hi\" & <wave>".into(),
101 width,
102 height,
103 preview_width: 200,
104 preview_height: 200,
105 }
106 }
107
108 #[test]
109 fn tall_gifs_are_capped_keeping_the_aspect_ratio() {
110 let image = RemoteImage::gif(&gif(500, 1000));
111 assert_eq!((image.width, image.height), (125, 250));
112 let small = RemoteImage::gif(&gif(200, 100));
113 assert_eq!((small.width, small.height), (200, 100));
114 }
115
116 #[test]
117 fn gif_html_escapes_the_title_and_names_the_giphy_itemtype() {
118 let html = RemoteImage::gif(&gif(358, 360)).html();
119 assert_eq!(
120 html,
121 "<img src=\"https://media0.giphy.com/media/a/giphy.gif\" width=\"249\" height=\"250\" alt=\"Say &quot;hi&quot; &amp; &lt;wave&gt;\" itemtype=\"http://schema.skype.com/Giphy\">"
122 );
123 }
124
125 #[test]
126 fn stickers_are_square_250() {
127 let sticker = crate::stickers::popular()[0];
128 let html = RemoteImage::sticker(sticker).html();
129 assert!(html.contains("width=\"250\" height=\"250\""));
130 assert!(html.ends_with("itemtype=\"http://schema.skype.com/Sticker\">"));
131 assert!(html.contains("clippy-250x250"));
132 }
133 }
@@ -0,0 +1,133 @@
1use gpui_kit::{ImageSource, SharedString};
2use teams_core::{Gif, ImageRef};
3
4use crate::stickers::Sticker;
5
6pub const MAX_HEIGHT: u32 = 250;
7const STICKER_SIZE: u32 = 250;
8const GIF_ITEMTYPE: &str = "http://schema.skype.com/Giphy";
9const STICKER_ITEMTYPE: &str = "http://schema.skype.com/Sticker";
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum RemoteKind {
13 Gif,
14 Sticker,
15}
16
17/// A GIF or sticker the message points at by URL; nothing is uploaded.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct RemoteImage {
20 pub kind: RemoteKind,
21 pub url: String,
22 pub title: String,
23 pub width: u32,
24 pub height: u32,
25}
26
27impl RemoteImage {
28 pub fn gif(gif: &Gif) -> Self {
29 let (width, height) = capped(gif.width, gif.height);
30 RemoteImage {
31 kind: RemoteKind::Gif,
32 url: gif.url.clone(),
33 title: gif.title.clone(),
34 width,
35 height,
36 }
37 }
38
39 pub fn sticker(sticker: &Sticker) -> Self {
40 RemoteImage {
41 kind: RemoteKind::Sticker,
42 url: sticker.url(),
43 title: sticker.name.to_owned(),
44 width: STICKER_SIZE,
45 height: STICKER_SIZE,
46 }
47 }
48
49 pub fn html(&self) -> String {
50 let itemtype = match self.kind {
51 RemoteKind::Gif => GIF_ITEMTYPE,
52 RemoteKind::Sticker => STICKER_ITEMTYPE,
53 };
54 format!(
55 "<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{itemtype}\">",
56 teams_core::escape_html(&self.url),
57 self.width,
58 self.height,
59 teams_core::escape_html(&self.title),
60 )
61 }
62
63 pub fn image_ref(&self) -> ImageRef {
64 ImageRef {
65 id: self.url.clone(),
66 url: self.url.clone(),
67 width: Some(self.width),
68 height: Some(self.height),
69 }
70 }
71}
72
73/// Height capped at `MAX_HEIGHT`, aspect ratio kept.
74pub fn capped(width: u32, height: u32) -> (u32, u32) {
75 if height <= MAX_HEIGHT || height == 0 {
76 return (width, height);
77 }
78 let scaled =
79 (u64::from(width) * u64::from(MAX_HEIGHT) + u64::from(height) / 2) / u64::from(height);
80 ((scaled as u32).max(1), MAX_HEIGHT)
81}
82
83/// Web URLs load through the app's HTTP client, anything else is a local file (demo mode).
84pub fn image_source(location: &str) -> ImageSource {
85 if location.starts_with("https://") {
86 ImageSource::from(SharedString::from(location.to_owned()))
87 } else {
88 ImageSource::from(std::path::PathBuf::from(location))
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 fn gif(width: u32, height: u32) -> Gif {
97 Gif {
98 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
99 preview_url: "https://media0.giphy.com/media/a/200w.gif".into(),
100 title: "Say \"hi\" & <wave>".into(),
101 width,
102 height,
103 preview_width: 200,
104 preview_height: 200,
105 }
106 }
107
108 #[test]
109 fn tall_gifs_are_capped_keeping_the_aspect_ratio() {
110 let image = RemoteImage::gif(&gif(500, 1000));
111 assert_eq!((image.width, image.height), (125, 250));
112 let small = RemoteImage::gif(&gif(200, 100));
113 assert_eq!((small.width, small.height), (200, 100));
114 }
115
116 #[test]
117 fn gif_html_escapes_the_title_and_names_the_giphy_itemtype() {
118 let html = RemoteImage::gif(&gif(358, 360)).html();
119 assert_eq!(
120 html,
121 "<img src=\"https://media0.giphy.com/media/a/giphy.gif\" width=\"249\" height=\"250\" alt=\"Say &quot;hi&quot; &amp; &lt;wave&gt;\" itemtype=\"http://schema.skype.com/Giphy\">"
122 );
123 }
124
125 #[test]
126 fn stickers_are_square_250() {
127 let sticker = crate::stickers::popular()[0];
128 let html = RemoteImage::sticker(sticker).html();
129 assert!(html.contains("width=\"250\" height=\"250\""));
130 assert!(html.ends_with("itemtype=\"http://schema.skype.com/Sticker\">"));
131 assert!(html.contains("clippy-250x250"));
132 }
133}
crates/app/src/stickers.rs added +174 −0
@@ -0,0 +1,174 @@
1 use std::sync::OnceLock;
2
3 const CATALOG: &str = include_str!("../assets/stickers.tsv");
4 const IMAGE_BASE: &str = "https://statics.teams.cdn.office.net/evergreen-assets/stickerassets";
5 const IMAGE_VERSION: u32 = 5;
6 const POPULAR_IDS: [&str; 6] = [
7 "Clippy_HelloThere",
8 "OfficeDrama_HighFive",
9 "WordArt_Awesome",
10 "Octocorn_Coffee",
11 "Teamsquatch_Yes",
12 "Bee_Angry",
13 ];
14
15 #[derive(Debug, PartialEq, Eq)]
16 pub struct Sticker {
17 pub id: &'static str,
18 pub category: &'static str,
19 pub file: &'static str,
20 pub name: &'static str,
21 }
22
23 impl Sticker {
24 pub fn url(&self) -> String {
25 format!(
26 "{IMAGE_BASE}/{}-250x250/{}?v={IMAGE_VERSION}",
27 self.category.to_lowercase(),
28 self.file
29 )
30 }
31 }
32
33 fn catalog() -> &'static [Sticker] {
34 static PARSED: OnceLock<Vec<Sticker>> = OnceLock::new();
35 PARSED.get_or_init(|| {
36 CATALOG
37 .lines()
38 .filter_map(|line| {
39 let mut fields = line.split('\t');
40 Some(Sticker {
41 id: fields.next()?,
42 category: fields.next()?,
43 file: fields.next()?,
44 name: fields.next()?,
45 })
46 })
47 .collect()
48 })
49 }
50
51 pub fn popular() -> Vec<&'static Sticker> {
52 POPULAR_IDS
53 .iter()
54 .filter_map(|id| catalog().iter().find(|sticker| sticker.id == *id))
55 .collect()
56 }
57
58 pub fn categories() -> Vec<&'static str> {
59 let mut found: Vec<&'static str> = Vec::new();
60 for sticker in catalog() {
61 if !found.contains(&sticker.category) {
62 found.push(sticker.category);
63 }
64 }
65 found
66 }
67
68 pub fn in_category(category: &str) -> Vec<&'static Sticker> {
69 catalog()
70 .iter()
71 .filter(|sticker| sticker.category == category)
72 .collect()
73 }
74
75 /// `OfficeDrama` becomes "Office Drama", `CatsInSuits` becomes "Cats in Suits", `BMac` stays.
76 pub fn category_label(category: &str) -> String {
77 let mut label = String::new();
78 let mut previous: Option<char> = None;
79 for character in category.chars() {
80 if character.is_uppercase() && previous.is_some_and(char::is_lowercase) {
81 label.push(' ');
82 }
83 label.push(character);
84 previous = Some(character);
85 }
86 label
87 .split(' ')
88 .enumerate()
89 .map(|(index, word)| match word {
90 "In" | "Of" | "And" if index > 0 => word.to_lowercase(),
91 other => other.to_owned(),
92 })
93 .collect::<Vec<_>>()
94 .join(" ")
95 }
96
97 pub fn search(query: &str) -> Vec<&'static Sticker> {
98 let query = query.trim().to_lowercase();
99 catalog()
100 .iter()
101 .filter(|sticker| {
102 [sticker.name, sticker.id, sticker.category]
103 .iter()
104 .any(|field| field.to_lowercase().contains(&query))
105 })
106 .collect()
107 }
108
109 #[cfg(test)]
110 mod tests {
111 use super::*;
112
113 #[test]
114 fn the_catalog_parses_every_row() {
115 assert_eq!(catalog().len(), CATALOG.lines().count());
116 assert!(catalog().iter().all(|sticker| !sticker.file.is_empty()));
117 }
118
119 #[test]
120 fn urls_use_the_lowercase_category_folder() {
121 let sticker = catalog()
122 .iter()
123 .find(|sticker| sticker.id == "Clippy_HelloThere")
124 .unwrap();
125 assert_eq!(
126 sticker.url(),
127 "https://statics.teams.cdn.office.net/evergreen-assets/stickerassets/clippy-250x250/Clippy_HelloThere.gif?v=5"
128 );
129 }
130
131 #[test]
132 fn categories_keep_the_catalog_order() {
133 let found = categories();
134 assert_eq!(found.first(), Some(&"Clippy"));
135 assert_eq!(found.len(), 18);
136 }
137
138 #[test]
139 fn labels_split_camel_case() {
140 assert_eq!(category_label("OfficeDrama"), "Office Drama");
141 assert_eq!(category_label("CatsInSuits"), "Cats in Suits");
142 assert_eq!(category_label("BMac"), "BMac");
143 assert_eq!(category_label("Clippy"), "Clippy");
144 }
145
146 #[test]
147 fn popular_follows_the_given_order() {
148 let ids: Vec<&str> = popular().iter().map(|sticker| sticker.id).collect();
149 assert_eq!(ids[0], "Clippy_HelloThere");
150 assert_eq!(ids.len(), 6);
151 }
152
153 #[test]
154 fn search_ignores_case_and_covers_name_id_and_category() {
155 assert!(
156 search("hello there")
157 .iter()
158 .any(|sticker| sticker.id == "Clippy_HelloThere")
159 );
160 assert!(
161 search("OCTOCORN_COFFEE")
162 .iter()
163 .any(|sticker| sticker.id == "Octocorn_Coffee")
164 );
165 assert!(
166 search("wordart")
167 .iter()
168 .all(|sticker| sticker.category == "WordArt"
169 || sticker.name.to_lowercase().contains("wordart")
170 || sticker.id.to_lowercase().contains("wordart"))
171 );
172 assert!(search("zzzzqqq").is_empty());
173 }
174 }
@@ -0,0 +1,174 @@
1use std::sync::OnceLock;
2
3const CATALOG: &str = include_str!("../assets/stickers.tsv");
4const IMAGE_BASE: &str = "https://statics.teams.cdn.office.net/evergreen-assets/stickerassets";
5const IMAGE_VERSION: u32 = 5;
6const POPULAR_IDS: [&str; 6] = [
7 "Clippy_HelloThere",
8 "OfficeDrama_HighFive",
9 "WordArt_Awesome",
10 "Octocorn_Coffee",
11 "Teamsquatch_Yes",
12 "Bee_Angry",
13];
14
15#[derive(Debug, PartialEq, Eq)]
16pub struct Sticker {
17 pub id: &'static str,
18 pub category: &'static str,
19 pub file: &'static str,
20 pub name: &'static str,
21}
22
23impl Sticker {
24 pub fn url(&self) -> String {
25 format!(
26 "{IMAGE_BASE}/{}-250x250/{}?v={IMAGE_VERSION}",
27 self.category.to_lowercase(),
28 self.file
29 )
30 }
31}
32
33fn catalog() -> &'static [Sticker] {
34 static PARSED: OnceLock<Vec<Sticker>> = OnceLock::new();
35 PARSED.get_or_init(|| {
36 CATALOG
37 .lines()
38 .filter_map(|line| {
39 let mut fields = line.split('\t');
40 Some(Sticker {
41 id: fields.next()?,
42 category: fields.next()?,
43 file: fields.next()?,
44 name: fields.next()?,
45 })
46 })
47 .collect()
48 })
49}
50
51pub fn popular() -> Vec<&'static Sticker> {
52 POPULAR_IDS
53 .iter()
54 .filter_map(|id| catalog().iter().find(|sticker| sticker.id == *id))
55 .collect()
56}
57
58pub fn categories() -> Vec<&'static str> {
59 let mut found: Vec<&'static str> = Vec::new();
60 for sticker in catalog() {
61 if !found.contains(&sticker.category) {
62 found.push(sticker.category);
63 }
64 }
65 found
66}
67
68pub fn in_category(category: &str) -> Vec<&'static Sticker> {
69 catalog()
70 .iter()
71 .filter(|sticker| sticker.category == category)
72 .collect()
73}
74
75/// `OfficeDrama` becomes "Office Drama", `CatsInSuits` becomes "Cats in Suits", `BMac` stays.
76pub fn category_label(category: &str) -> String {
77 let mut label = String::new();
78 let mut previous: Option<char> = None;
79 for character in category.chars() {
80 if character.is_uppercase() && previous.is_some_and(char::is_lowercase) {
81 label.push(' ');
82 }
83 label.push(character);
84 previous = Some(character);
85 }
86 label
87 .split(' ')
88 .enumerate()
89 .map(|(index, word)| match word {
90 "In" | "Of" | "And" if index > 0 => word.to_lowercase(),
91 other => other.to_owned(),
92 })
93 .collect::<Vec<_>>()
94 .join(" ")
95}
96
97pub fn search(query: &str) -> Vec<&'static Sticker> {
98 let query = query.trim().to_lowercase();
99 catalog()
100 .iter()
101 .filter(|sticker| {
102 [sticker.name, sticker.id, sticker.category]
103 .iter()
104 .any(|field| field.to_lowercase().contains(&query))
105 })
106 .collect()
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112
113 #[test]
114 fn the_catalog_parses_every_row() {
115 assert_eq!(catalog().len(), CATALOG.lines().count());
116 assert!(catalog().iter().all(|sticker| !sticker.file.is_empty()));
117 }
118
119 #[test]
120 fn urls_use_the_lowercase_category_folder() {
121 let sticker = catalog()
122 .iter()
123 .find(|sticker| sticker.id == "Clippy_HelloThere")
124 .unwrap();
125 assert_eq!(
126 sticker.url(),
127 "https://statics.teams.cdn.office.net/evergreen-assets/stickerassets/clippy-250x250/Clippy_HelloThere.gif?v=5"
128 );
129 }
130
131 #[test]
132 fn categories_keep_the_catalog_order() {
133 let found = categories();
134 assert_eq!(found.first(), Some(&"Clippy"));
135 assert_eq!(found.len(), 18);
136 }
137
138 #[test]
139 fn labels_split_camel_case() {
140 assert_eq!(category_label("OfficeDrama"), "Office Drama");
141 assert_eq!(category_label("CatsInSuits"), "Cats in Suits");
142 assert_eq!(category_label("BMac"), "BMac");
143 assert_eq!(category_label("Clippy"), "Clippy");
144 }
145
146 #[test]
147 fn popular_follows_the_given_order() {
148 let ids: Vec<&str> = popular().iter().map(|sticker| sticker.id).collect();
149 assert_eq!(ids[0], "Clippy_HelloThere");
150 assert_eq!(ids.len(), 6);
151 }
152
153 #[test]
154 fn search_ignores_case_and_covers_name_id_and_category() {
155 assert!(
156 search("hello there")
157 .iter()
158 .any(|sticker| sticker.id == "Clippy_HelloThere")
159 );
160 assert!(
161 search("OCTOCORN_COFFEE")
162 .iter()
163 .any(|sticker| sticker.id == "Octocorn_Coffee")
164 );
165 assert!(
166 search("wordart")
167 .iter()
168 .all(|sticker| sticker.category == "WordArt"
169 || sticker.name.to_lowercase().contains("wordart")
170 || sticker.id.to_lowercase().contains("wordart"))
171 );
172 assert!(search("zzzzqqq").is_empty());
173 }
174}
crates/app/src/views/attachment_tray.rs +137 −40
@@ -12,6 +12,7 @@ use teams_core::{FileKind, FileReference, UploadedFile};
12 12 use super::attachments::file_badge;
13 13 use super::widgets::icon;
14 14 use crate::format;
15 use crate::remote_image::{RemoteImage, image_source};
15 16 use crate::theme;
16 17
17 18 pub const MAX_ATTACHMENTS: usize = 10;
@@ -171,6 +172,7 @@ pub enum ItemKind {
171 172 image: Arc<Image>,
172 173 dimensions: Option<(u32, u32)>,
173 174 },
175 Remote(RemoteImage),
174 176 File {
175 177 bytes: Arc<Vec<u8>>,
176 178 upload: UploadState,
@@ -186,31 +188,57 @@ pub struct TrayItem {
186 188 pub kind: ItemKind,
187 189 }
188 190
191 impl ItemKind {
192 /// Shown inline in the text instead of as a chip.
193 fn is_object(&self) -> bool {
194 matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_))
195 }
196 }
197
189 198 impl TrayItem {
190 199 fn blocks_send(&self) -> bool {
191 200 match &self.kind {
192 201 ItemKind::Reading => true,
193 ItemKind::Image { .. } => false,
202 ItemKind::Image { .. } | ItemKind::Remote(_) => false,
194 203 ItemKind::File { upload, .. } => !matches!(upload, UploadState::Done(_)),
195 204 }
196 205 }
197 206 }
198 207
199 208 #[derive(Debug, Clone)]
200 pub struct PreviewImage {
201 pub image: Arc<Image>,
202 pub dimensions: Option<(u32, u32)>,
209 pub enum PreviewImage {
210 Inline {
211 image: Arc<Image>,
212 dimensions: Option<(u32, u32)>,
213 },
214 Remote(RemoteImage),
215 }
216
217 impl PreviewImage {
218 fn dimensions(&self) -> Option<(u32, u32)> {
219 match self {
220 PreviewImage::Inline { dimensions, .. } => *dimensions,
221 PreviewImage::Remote(remote) => Some((remote.width, remote.height)),
222 }
223 }
203 224 }
204 225
205 226 pub type RemoveImage = Rc<dyn Fn(&mut Window, &mut App)>;
206 227
207 228 #[derive(Debug, Clone, PartialEq, Eq)]
208 pub struct OutgoingImage {
229 pub struct InlineImage {
209 230 pub name: String,
210 231 pub image: Arc<Image>,
211 232 pub dimensions: Option<(u32, u32)>,
212 233 }
213 234
235 /// One object in the text: uploaded bytes or a GIF or sticker the message links to.
236 #[derive(Debug, Clone, PartialEq, Eq)]
237 pub enum OutgoingImage {
238 Inline(InlineImage),
239 Remote(RemoteImage),
240 }
241
214 242 #[derive(Debug, Clone, PartialEq, Eq)]
215 243 pub struct OutgoingFile {
216 244 pub name: String,
@@ -266,21 +294,34 @@ impl AttachmentTray {
266 294 }
267 295
268 296 pub fn has_chips(&self) -> bool {
269 self.items
270 .iter()
271 .any(|item| !matches!(item.kind, ItemKind::Image { .. }))
297 self.items.iter().any(|item| !item.kind.is_object())
272 298 }
273 299
274 300 pub fn image(&self, id: u64) -> Option<PreviewImage> {
275 301 self.items.iter().find_map(|item| match &item.kind {
276 ItemKind::Image { image, dimensions } if item.id == id => Some(PreviewImage {
277 image: image.clone(),
278 dimensions: *dimensions,
279 }),
302 ItemKind::Image { image, dimensions } if item.id == id => {
303 Some(PreviewImage::Inline {
304 image: image.clone(),
305 dimensions: *dimensions,
306 })
307 }
308 ItemKind::Remote(remote) if item.id == id => {
309 Some(PreviewImage::Remote(remote.clone()))
310 }
280 311 _ => None,
281 312 })
282 313 }
283 314
315 /// `None` when the tray is full.
316 pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> {
317 self.notice = None;
318 if self.items.len() >= MAX_ATTACHMENTS {
319 self.notice = Some(limit_notice(1));
320 return None;
321 }
322 Some(self.push(remote.title.clone(), 0, ItemKind::Remote(remote)))
323 }
324
284 325 pub fn notice(&self) -> Option<&str> {
285 326 self.notice.as_deref()
286 327 }
@@ -469,7 +510,7 @@ impl AttachmentTray {
469 510 let (images, others): (Vec<_>, Vec<_>) = self
470 511 .items
471 512 .drain(..)
472 .partition(|item| matches!(item.kind, ItemKind::Image { .. }));
513 .partition(|item| item.kind.is_object());
473 514 self.items = images;
474 515 others
475 516 .into_iter()
@@ -492,15 +533,18 @@ impl AttachmentTray {
492 533 self.clear();
493 534 let image_ids = images
494 535 .iter()
495 .map(|image| {
496 self.push(
497 image.name.clone(),
498 image.image.bytes.len() as u64,
536 .map(|image| match image {
537 OutgoingImage::Inline(inline) => self.push(
538 inline.name.clone(),
539 inline.image.bytes.len() as u64,
499 540 ItemKind::Image {
500 image: image.image.clone(),
501 dimensions: image.dimensions,
541 image: inline.image.clone(),
542 dimensions: inline.dimensions,
502 543 },
503 )
544 ),
545 OutgoingImage::Remote(remote) => {
546 self.push(remote.title.clone(), 0, ItemKind::Remote(remote.clone()))
547 }
504 548 })
505 549 .collect();
506 550 for file in files {
@@ -525,11 +569,14 @@ impl AttachmentTray {
525 569 .filter_map(|id| {
526 570 let item = self.items.iter().find(|item| item.id == *id)?;
527 571 match &item.kind {
528 ItemKind::Image { image, dimensions } => Some(OutgoingImage {
529 name: item.name.clone(),
530 image: image.clone(),
531 dimensions: *dimensions,
532 }),
572 ItemKind::Image { image, dimensions } => {
573 Some(OutgoingImage::Inline(InlineImage {
574 name: item.name.clone(),
575 image: image.clone(),
576 dimensions: *dimensions,
577 }))
578 }
579 ItemKind::Remote(remote) => Some(OutgoingImage::Remote(remote.clone())),
533 580 _ => None,
534 581 }
535 582 })
@@ -538,7 +585,7 @@ impl AttachmentTray {
538 585
539 586 pub fn discard_images_except(&mut self, kept: &[u64]) {
540 587 self.items
541 .retain(|item| !matches!(item.kind, ItemKind::Image { .. }) || kept.contains(&item.id));
588 .retain(|item| !item.kind.is_object() || kept.contains(&item.id));
542 589 }
543 590
544 591 pub fn outgoing_files(&self) -> Vec<OutgoingFile> {
@@ -697,7 +744,7 @@ pub fn chip_state(item: &TrayItem) -> ChipState {
697 744 };
698 745 match &item.kind {
699 746 ItemKind::Reading => muted("Reading ...".to_owned()),
700 ItemKind::Image { .. } => muted(size),
747 ItemKind::Image { .. } | ItemKind::Remote(_) => muted(size),
701 748 ItemKind::File {
702 749 upload,
703 750 sent_as_file,
@@ -770,7 +817,7 @@ pub fn inline_preview(
770 817 selected: bool,
771 818 remove: RemoveImage,
772 819 ) -> AnyElement {
773 let dimensions = preview.as_ref().and_then(|preview| preview.dimensions);
820 let dimensions = preview.as_ref().and_then(PreviewImage::dimensions);
774 821 let (width, height) = preview_size(dimensions, f32::from(available_width));
775 822 let group = SharedString::from(format!("image-preview-{id}"));
776 823 let frame = div()
@@ -782,12 +829,18 @@ pub fn inline_preview(
782 829 .border_color(theme::border_strong())
783 830 .bg(theme::surface_raised());
784 831 let frame = match preview {
785 Some(preview) => frame.child(
786 img(preview.image)
787 .size_full()
788 .rounded(px(PREVIEW_RADIUS))
789 .object_fit(ObjectFit::Cover),
790 ),
832 Some(preview) => {
833 let source = match preview {
834 PreviewImage::Inline { image, .. } => ImageSource::from(image),
835 PreviewImage::Remote(remote) => image_source(&remote.url),
836 };
837 frame.child(
838 img(source)
839 .size_full()
840 .rounded(px(PREVIEW_RADIUS))
841 .object_fit(ObjectFit::Cover),
842 )
843 }
791 844 None => frame,
792 845 };
793 846 div()
@@ -925,7 +978,7 @@ pub fn render_tray<T: 'static>(
925 978 let elements: Vec<AnyElement> = tray
926 979 .items()
927 980 .iter()
928 .filter(|item| !matches!(item.kind, ItemKind::Image { .. }))
981 .filter(|item| !item.kind.is_object())
929 982 .map(|item| chip(item, remove, retry, cx))
930 983 .collect();
931 984 Some(
@@ -951,10 +1004,12 @@ mod tests {
951 1004
952 1005 use super::{
953 1006 AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,
954 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, PasteAction,
955 Tone, UploadResult, chip_state, classify, limit_notice, paste_action, pasted_image_name,
956 prepare_pasted_image, preview_size, read_attachment, sniff_inline_format,
1007 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, OutgoingImage,
1008 PasteAction, PreviewImage, RemoteImage, Tone, UploadResult, chip_state, classify,
1009 limit_notice, paste_action, pasted_image_name, prepare_pasted_image, preview_size,
1010 read_attachment, sniff_inline_format,
957 1011 };
1012 use crate::remote_image::RemoteKind;
958 1013
959 1014 const PNG_HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
960 1015
@@ -1357,6 +1412,42 @@ mod tests {
1357 1412 assert!(!restored.blocks_send());
1358 1413 }
1359 1414
1415 fn gif(title: &str) -> RemoteImage {
1416 RemoteImage {
1417 kind: RemoteKind::Gif,
1418 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
1419 title: title.into(),
1420 width: 200,
1421 height: 100,
1422 }
1423 }
1424
1425 #[test]
1426 fn a_remote_image_is_an_object_without_a_chip_and_never_blocks_sending() {
1427 let mut tray = AttachmentTray::default();
1428 let id = tray.add_remote(gif("Wave")).unwrap();
1429 assert!(!tray.has_chips());
1430 assert!(!tray.blocks_send());
1431 assert!(matches!(tray.image(id), Some(PreviewImage::Remote(_))));
1432 let images = tray.images_in(&[id]);
1433 assert_eq!(images, vec![OutgoingImage::Remote(gif("Wave"))]);
1434 let mut restored = AttachmentTray::default();
1435 let ids = restored.restore(&images, &[]);
1436 assert_eq!(restored.images_in(&ids), images);
1437 assert_eq!(tray.keep_images_only(), Vec::new());
1438 assert_eq!(tray.items().len(), 1);
1439 }
1440
1441 #[test]
1442 fn a_full_tray_refuses_another_remote_image() {
1443 let mut tray = AttachmentTray::default();
1444 for _ in 0..MAX_ATTACHMENTS {
1445 assert!(tray.add_remote(gif("Wave")).is_some());
1446 }
1447 assert!(tray.add_remote(gif("Wave")).is_none());
1448 assert!(tray.notice().is_some());
1449 }
1450
1360 1451 #[test]
1361 1452 fn images_come_back_in_the_order_asked_for_and_only_when_known() {
1362 1453 let mut tray = AttachmentTray::default();
@@ -1365,8 +1456,14 @@ mod tests {
1365 1456 tray.finish_reading(ids[1], LoadedFile::new(png(4, 4)), true);
1366 1457 let images = tray.images_in(&[ids[1], 99, ids[0]]);
1367 1458 assert_eq!(images.len(), 2);
1368 assert_eq!(images[0].dimensions, Some((4, 4)));
1369 assert_eq!(images[1].dimensions, Some((2, 2)));
1459 let dimensions: Vec<_> = images
1460 .iter()
1461 .map(|image| match image {
1462 OutgoingImage::Inline(inline) => inline.dimensions,
1463 OutgoingImage::Remote(_) => None,
1464 })
1465 .collect();
1466 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
1370 1467 assert!(!tray.has_chips());
1371 1468 tray.discard_images_except(&[ids[1]]);
1372 1469 assert_eq!(tray.items().len(), 1);
@@ -12,6 +12,7 @@ use teams_core::{FileKind, FileReference, UploadedFile};
12use super::attachments::file_badge;
12use super::attachments::file_badge;
13use super::widgets::icon;
13use super::widgets::icon;
14use crate::format;
14use crate::format;
15use crate::remote_image::{RemoteImage, image_source};
15use crate::theme;
16use crate::theme;
16
17
17pub const MAX_ATTACHMENTS: usize = 10;
18pub const MAX_ATTACHMENTS: usize = 10;
@@ -171,6 +172,7 @@ pub enum ItemKind {
171 image: Arc<Image>,
172 image: Arc<Image>,
172 dimensions: Option<(u32, u32)>,
173 dimensions: Option<(u32, u32)>,
173 },
174 },
175 Remote(RemoteImage),
174 File {
176 File {
175 bytes: Arc<Vec<u8>>,
177 bytes: Arc<Vec<u8>>,
176 upload: UploadState,
178 upload: UploadState,
@@ -186,31 +188,57 @@ pub struct TrayItem {
186 pub kind: ItemKind,
188 pub kind: ItemKind,
187}
189}
188
190
191impl ItemKind {
192 /// Shown inline in the text instead of as a chip.
193 fn is_object(&self) -> bool {
194 matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_))
195 }
196}
197
189impl TrayItem {
198impl TrayItem {
190 fn blocks_send(&self) -> bool {
199 fn blocks_send(&self) -> bool {
191 match &self.kind {
200 match &self.kind {
192 ItemKind::Reading => true,
201 ItemKind::Reading => true,
193 ItemKind::Image { .. } => false,
202 ItemKind::Image { .. } | ItemKind::Remote(_) => false,
194 ItemKind::File { upload, .. } => !matches!(upload, UploadState::Done(_)),
203 ItemKind::File { upload, .. } => !matches!(upload, UploadState::Done(_)),
195 }
204 }
196 }
205 }
197}
206}
198
207
199#[derive(Debug, Clone)]
208#[derive(Debug, Clone)]
200pub struct PreviewImage {
209pub enum PreviewImage {
201 pub image: Arc<Image>,
210 Inline {
202 pub dimensions: Option<(u32, u32)>,
211 image: Arc<Image>,
212 dimensions: Option<(u32, u32)>,
213 },
214 Remote(RemoteImage),
215}
216
217impl PreviewImage {
218 fn dimensions(&self) -> Option<(u32, u32)> {
219 match self {
220 PreviewImage::Inline { dimensions, .. } => *dimensions,
221 PreviewImage::Remote(remote) => Some((remote.width, remote.height)),
222 }
223 }
203}
224}
204
225
205pub type RemoveImage = Rc<dyn Fn(&mut Window, &mut App)>;
226pub type RemoveImage = Rc<dyn Fn(&mut Window, &mut App)>;
206
227
207#[derive(Debug, Clone, PartialEq, Eq)]
228#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct OutgoingImage {
229pub struct InlineImage {
209 pub name: String,
230 pub name: String,
210 pub image: Arc<Image>,
231 pub image: Arc<Image>,
211 pub dimensions: Option<(u32, u32)>,
232 pub dimensions: Option<(u32, u32)>,
212}
233}
213
234
235/// One object in the text: uploaded bytes or a GIF or sticker the message links to.
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub enum OutgoingImage {
238 Inline(InlineImage),
239 Remote(RemoteImage),
240}
241
214#[derive(Debug, Clone, PartialEq, Eq)]
242#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct OutgoingFile {
243pub struct OutgoingFile {
216 pub name: String,
244 pub name: String,
@@ -266,21 +294,34 @@ impl AttachmentTray {
266 }
294 }
267
295
268 pub fn has_chips(&self) -> bool {
296 pub fn has_chips(&self) -> bool {
269 self.items
297 self.items.iter().any(|item| !item.kind.is_object())
270 .iter()
271 .any(|item| !matches!(item.kind, ItemKind::Image { .. }))
272 }
298 }
273
299
274 pub fn image(&self, id: u64) -> Option<PreviewImage> {
300 pub fn image(&self, id: u64) -> Option<PreviewImage> {
275 self.items.iter().find_map(|item| match &item.kind {
301 self.items.iter().find_map(|item| match &item.kind {
276 ItemKind::Image { image, dimensions } if item.id == id => Some(PreviewImage {
302 ItemKind::Image { image, dimensions } if item.id == id => {
277 image: image.clone(),
303 Some(PreviewImage::Inline {
278 dimensions: *dimensions,
304 image: image.clone(),
279 }),
305 dimensions: *dimensions,
306 })
307 }
308 ItemKind::Remote(remote) if item.id == id => {
309 Some(PreviewImage::Remote(remote.clone()))
310 }
280 _ => None,
311 _ => None,
281 })
312 })
282 }
313 }
283
314
315 /// `None` when the tray is full.
316 pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> {
317 self.notice = None;
318 if self.items.len() >= MAX_ATTACHMENTS {
319 self.notice = Some(limit_notice(1));
320 return None;
321 }
322 Some(self.push(remote.title.clone(), 0, ItemKind::Remote(remote)))
323 }
324
284 pub fn notice(&self) -> Option<&str> {
325 pub fn notice(&self) -> Option<&str> {
285 self.notice.as_deref()
326 self.notice.as_deref()
286 }
327 }
@@ -469,7 +510,7 @@ impl AttachmentTray {
469 let (images, others): (Vec<_>, Vec<_>) = self
510 let (images, others): (Vec<_>, Vec<_>) = self
470 .items
511 .items
471 .drain(..)
512 .drain(..)
472 .partition(|item| matches!(item.kind, ItemKind::Image { .. }));
513 .partition(|item| item.kind.is_object());
473 self.items = images;
514 self.items = images;
474 others
515 others
475 .into_iter()
516 .into_iter()
@@ -492,15 +533,18 @@ impl AttachmentTray {
492 self.clear();
533 self.clear();
493 let image_ids = images
534 let image_ids = images
494 .iter()
535 .iter()
495 .map(|image| {
536 .map(|image| match image {
496 self.push(
537 OutgoingImage::Inline(inline) => self.push(
497 image.name.clone(),
538 inline.name.clone(),
498 image.image.bytes.len() as u64,
539 inline.image.bytes.len() as u64,
499 ItemKind::Image {
540 ItemKind::Image {
500 image: image.image.clone(),
541 image: inline.image.clone(),
501 dimensions: image.dimensions,
542 dimensions: inline.dimensions,
502 },
543 },
503 )
544 ),
545 OutgoingImage::Remote(remote) => {
546 self.push(remote.title.clone(), 0, ItemKind::Remote(remote.clone()))
547 }
504 })
548 })
505 .collect();
549 .collect();
506 for file in files {
550 for file in files {
@@ -525,11 +569,14 @@ impl AttachmentTray {
525 .filter_map(|id| {
569 .filter_map(|id| {
526 let item = self.items.iter().find(|item| item.id == *id)?;
570 let item = self.items.iter().find(|item| item.id == *id)?;
527 match &item.kind {
571 match &item.kind {
528 ItemKind::Image { image, dimensions } => Some(OutgoingImage {
572 ItemKind::Image { image, dimensions } => {
529 name: item.name.clone(),
573 Some(OutgoingImage::Inline(InlineImage {
530 image: image.clone(),
574 name: item.name.clone(),
531 dimensions: *dimensions,
575 image: image.clone(),
532 }),
576 dimensions: *dimensions,
577 }))
578 }
579 ItemKind::Remote(remote) => Some(OutgoingImage::Remote(remote.clone())),
533 _ => None,
580 _ => None,
534 }
581 }
535 })
582 })
@@ -538,7 +585,7 @@ impl AttachmentTray {
538
585
539 pub fn discard_images_except(&mut self, kept: &[u64]) {
586 pub fn discard_images_except(&mut self, kept: &[u64]) {
540 self.items
587 self.items
541 .retain(|item| !matches!(item.kind, ItemKind::Image { .. }) || kept.contains(&item.id));
588 .retain(|item| !item.kind.is_object() || kept.contains(&item.id));
542 }
589 }
543
590
544 pub fn outgoing_files(&self) -> Vec<OutgoingFile> {
591 pub fn outgoing_files(&self) -> Vec<OutgoingFile> {
@@ -697,7 +744,7 @@ pub fn chip_state(item: &TrayItem) -> ChipState {
697 };
744 };
698 match &item.kind {
745 match &item.kind {
699 ItemKind::Reading => muted("Reading ...".to_owned()),
746 ItemKind::Reading => muted("Reading ...".to_owned()),
700 ItemKind::Image { .. } => muted(size),
747 ItemKind::Image { .. } | ItemKind::Remote(_) => muted(size),
701 ItemKind::File {
748 ItemKind::File {
702 upload,
749 upload,
703 sent_as_file,
750 sent_as_file,
@@ -770,7 +817,7 @@ pub fn inline_preview(
770 selected: bool,
817 selected: bool,
771 remove: RemoveImage,
818 remove: RemoveImage,
772) -> AnyElement {
819) -> AnyElement {
773 let dimensions = preview.as_ref().and_then(|preview| preview.dimensions);
820 let dimensions = preview.as_ref().and_then(PreviewImage::dimensions);
774 let (width, height) = preview_size(dimensions, f32::from(available_width));
821 let (width, height) = preview_size(dimensions, f32::from(available_width));
775 let group = SharedString::from(format!("image-preview-{id}"));
822 let group = SharedString::from(format!("image-preview-{id}"));
776 let frame = div()
823 let frame = div()
@@ -782,12 +829,18 @@ pub fn inline_preview(
782 .border_color(theme::border_strong())
829 .border_color(theme::border_strong())
783 .bg(theme::surface_raised());
830 .bg(theme::surface_raised());
784 let frame = match preview {
831 let frame = match preview {
785 Some(preview) => frame.child(
832 Some(preview) => {
786 img(preview.image)
833 let source = match preview {
787 .size_full()
834 PreviewImage::Inline { image, .. } => ImageSource::from(image),
788 .rounded(px(PREVIEW_RADIUS))
835 PreviewImage::Remote(remote) => image_source(&remote.url),
789 .object_fit(ObjectFit::Cover),
836 };
790 ),
837 frame.child(
838 img(source)
839 .size_full()
840 .rounded(px(PREVIEW_RADIUS))
841 .object_fit(ObjectFit::Cover),
842 )
843 }
791 None => frame,
844 None => frame,
792 };
845 };
793 div()
846 div()
@@ -925,7 +978,7 @@ pub fn render_tray<T: 'static>(
925 let elements: Vec<AnyElement> = tray
978 let elements: Vec<AnyElement> = tray
926 .items()
979 .items()
927 .iter()
980 .iter()
928 .filter(|item| !matches!(item.kind, ItemKind::Image { .. }))
981 .filter(|item| !item.kind.is_object())
929 .map(|item| chip(item, remove, retry, cx))
982 .map(|item| chip(item, remove, retry, cx))
930 .collect();
983 .collect();
931 Some(
984 Some(
@@ -951,10 +1004,12 @@ mod tests {
951
1004
952 use super::{
1005 use super::{
953 AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,
1006 AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,
954 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, PasteAction,
1007 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, OutgoingImage,
955 Tone, UploadResult, chip_state, classify, limit_notice, paste_action, pasted_image_name,
1008 PasteAction, PreviewImage, RemoteImage, Tone, UploadResult, chip_state, classify,
956 prepare_pasted_image, preview_size, read_attachment, sniff_inline_format,
1009 limit_notice, paste_action, pasted_image_name, prepare_pasted_image, preview_size,
1010 read_attachment, sniff_inline_format,
957 };
1011 };
1012 use crate::remote_image::RemoteKind;
958
1013
959 const PNG_HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
1014 const PNG_HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
960
1015
@@ -1357,6 +1412,42 @@ mod tests {
1357 assert!(!restored.blocks_send());
1412 assert!(!restored.blocks_send());
1358 }
1413 }
1359
1414
1415 fn gif(title: &str) -> RemoteImage {
1416 RemoteImage {
1417 kind: RemoteKind::Gif,
1418 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
1419 title: title.into(),
1420 width: 200,
1421 height: 100,
1422 }
1423 }
1424
1425 #[test]
1426 fn a_remote_image_is_an_object_without_a_chip_and_never_blocks_sending() {
1427 let mut tray = AttachmentTray::default();
1428 let id = tray.add_remote(gif("Wave")).unwrap();
1429 assert!(!tray.has_chips());
1430 assert!(!tray.blocks_send());
1431 assert!(matches!(tray.image(id), Some(PreviewImage::Remote(_))));
1432 let images = tray.images_in(&[id]);
1433 assert_eq!(images, vec![OutgoingImage::Remote(gif("Wave"))]);
1434 let mut restored = AttachmentTray::default();
1435 let ids = restored.restore(&images, &[]);
1436 assert_eq!(restored.images_in(&ids), images);
1437 assert_eq!(tray.keep_images_only(), Vec::new());
1438 assert_eq!(tray.items().len(), 1);
1439 }
1440
1441 #[test]
1442 fn a_full_tray_refuses_another_remote_image() {
1443 let mut tray = AttachmentTray::default();
1444 for _ in 0..MAX_ATTACHMENTS {
1445 assert!(tray.add_remote(gif("Wave")).is_some());
1446 }
1447 assert!(tray.add_remote(gif("Wave")).is_none());
1448 assert!(tray.notice().is_some());
1449 }
1450
1360 #[test]
1451 #[test]
1361 fn images_come_back_in_the_order_asked_for_and_only_when_known() {
1452 fn images_come_back_in_the_order_asked_for_and_only_when_known() {
1362 let mut tray = AttachmentTray::default();
1453 let mut tray = AttachmentTray::default();
@@ -1365,8 +1456,14 @@ mod tests {
1365 tray.finish_reading(ids[1], LoadedFile::new(png(4, 4)), true);
1456 tray.finish_reading(ids[1], LoadedFile::new(png(4, 4)), true);
1366 let images = tray.images_in(&[ids[1], 99, ids[0]]);
1457 let images = tray.images_in(&[ids[1], 99, ids[0]]);
1367 assert_eq!(images.len(), 2);
1458 assert_eq!(images.len(), 2);
1368 assert_eq!(images[0].dimensions, Some((4, 4)));
1459 let dimensions: Vec<_> = images
1369 assert_eq!(images[1].dimensions, Some((2, 2)));
1460 .iter()
1461 .map(|image| match image {
1462 OutgoingImage::Inline(inline) => inline.dimensions,
1463 OutgoingImage::Remote(_) => None,
1464 })
1465 .collect();
1466 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
1370 assert!(!tray.has_chips());
1467 assert!(!tray.has_chips());
1371 tray.discard_images_except(&[ids[1]]);
1468 tray.discard_images_except(&[ids[1]]);
1372 assert_eq!(tray.items().len(), 1);
1469 assert_eq!(tray.items().len(), 1);
crates/app/src/views/attachments.rs +20 −5
@@ -4,12 +4,13 @@ use gpui_kit::assets::IconName;
4 4 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5 5 use gpui_kit::prelude::FluentBuilder as _;
6 6 use gpui_kit::*;
7 use teams_core::{FileCard, FileKind, ImageRef};
7 use teams_core::{FileCard, FileKind, ImageRef, external_image_url};
8 8
9 9 use super::widgets::{icon, symbol};
10 10 use crate::data::Directory;
11 11 use crate::downloads::{self, DownloadState};
12 12 use crate::format;
13 use crate::remote_image;
13 14 use crate::render::{Block, render_blocks};
14 15 use crate::rows::LocalImage;
15 16 use crate::theme;
@@ -36,12 +37,16 @@ pub struct FileActions {
36 37 }
37 38
38 39 pub fn fit_image(size: Option<(u32, u32)>) -> (f32, f32) {
40 fit_image_within(size, IMAGE_MAX_HEIGHT)
41 }
42
43 fn fit_image_within(size: Option<(u32, u32)>, max_height: f32) -> (f32, f32) {
39 44 let Some((width, height)) = size.filter(|(width, height)| *width > 0 && *height > 0) else {
40 45 return IMAGE_FALLBACK;
41 46 };
42 47 let (width, height) = (width as f32, height as f32);
43 48 let scale = (IMAGE_MAX_WIDTH / width)
44 .min(IMAGE_MAX_HEIGHT / height)
49 .min(max_height / height)
45 50 .min(1.);
46 51 (
47 52 (width * scale).max(IMAGE_MIN_SIDE).round(),
@@ -55,7 +60,12 @@ fn declared_size(image: &ImageRef) -> Option<(u32, u32)> {
55 60
56 61 pub fn image_size(image: &ImageRef, directory: &Directory) -> (f32, f32) {
57 62 let loaded = directory.image(&image.url).and_then(|entry| entry.size);
58 fit_image(declared_size(image).or(loaded))
63 let max_height = if external_image_url(&image.url).is_some() {
64 remote_image::MAX_HEIGHT as f32
65 } else {
66 IMAGE_MAX_HEIGHT
67 };
68 fit_image_within(declared_size(image).or(loaded), max_height)
59 69 }
60 70
61 71 fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement {
@@ -408,8 +418,8 @@ pub fn attachments_view(
408 418 #[cfg(test)]
409 419 mod tests {
410 420 use super::{
411 IMAGE_FALLBACK, Placement, file_subtitle, fit_image, local_image_index, placement,
412 placements,
421 IMAGE_FALLBACK, Placement, file_subtitle, fit_image, fit_image_within, local_image_index,
422 placement, placements,
413 423 };
414 424 use crate::render::Block;
415 425 use teams_core::{FileCard, FileKind, ImageRef};
@@ -455,6 +465,11 @@ mod tests {
455 465 assert_eq!(fit_image(Some((720, 360))), (360., 180.));
456 466 }
457 467
468 #[test]
469 fn gifs_and_stickers_are_capped_at_250_high() {
470 assert_eq!(fit_image_within(Some((300, 500)), 250.), (150., 250.));
471 }
472
458 473 #[test]
459 474 fn tall_images_shrink_to_the_max_height() {
460 475 assert_eq!(fit_image(Some((300, 600))), (150., 300.));
@@ -4,12 +4,13 @@ use gpui_kit::assets::IconName;
4use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
6use gpui_kit::*;
7use teams_core::{FileCard, FileKind, ImageRef};
7use teams_core::{FileCard, FileKind, ImageRef, external_image_url};
8
8
9use super::widgets::{icon, symbol};
9use super::widgets::{icon, symbol};
10use crate::data::Directory;
10use crate::data::Directory;
11use crate::downloads::{self, DownloadState};
11use crate::downloads::{self, DownloadState};
12use crate::format;
12use crate::format;
13use crate::remote_image;
13use crate::render::{Block, render_blocks};
14use crate::render::{Block, render_blocks};
14use crate::rows::LocalImage;
15use crate::rows::LocalImage;
15use crate::theme;
16use crate::theme;
@@ -36,12 +37,16 @@ pub struct FileActions {
36}
37}
37
38
38pub fn fit_image(size: Option<(u32, u32)>) -> (f32, f32) {
39pub fn fit_image(size: Option<(u32, u32)>) -> (f32, f32) {
40 fit_image_within(size, IMAGE_MAX_HEIGHT)
41}
42
43fn fit_image_within(size: Option<(u32, u32)>, max_height: f32) -> (f32, f32) {
39 let Some((width, height)) = size.filter(|(width, height)| *width > 0 && *height > 0) else {
44 let Some((width, height)) = size.filter(|(width, height)| *width > 0 && *height > 0) else {
40 return IMAGE_FALLBACK;
45 return IMAGE_FALLBACK;
41 };
46 };
42 let (width, height) = (width as f32, height as f32);
47 let (width, height) = (width as f32, height as f32);
43 let scale = (IMAGE_MAX_WIDTH / width)
48 let scale = (IMAGE_MAX_WIDTH / width)
44 .min(IMAGE_MAX_HEIGHT / height)
49 .min(max_height / height)
45 .min(1.);
50 .min(1.);
46 (
51 (
47 (width * scale).max(IMAGE_MIN_SIDE).round(),
52 (width * scale).max(IMAGE_MIN_SIDE).round(),
@@ -55,7 +60,12 @@ fn declared_size(image: &ImageRef) -> Option<(u32, u32)> {
55
60
56pub fn image_size(image: &ImageRef, directory: &Directory) -> (f32, f32) {
61pub fn image_size(image: &ImageRef, directory: &Directory) -> (f32, f32) {
57 let loaded = directory.image(&image.url).and_then(|entry| entry.size);
62 let loaded = directory.image(&image.url).and_then(|entry| entry.size);
58 fit_image(declared_size(image).or(loaded))
63 let max_height = if external_image_url(&image.url).is_some() {
64 remote_image::MAX_HEIGHT as f32
65 } else {
66 IMAGE_MAX_HEIGHT
67 };
68 fit_image_within(declared_size(image).or(loaded), max_height)
59}
69}
60
70
61fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement {
71fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement {
@@ -408,8 +418,8 @@ pub fn attachments_view(
408#[cfg(test)]
418#[cfg(test)]
409mod tests {
419mod tests {
410 use super::{
420 use super::{
411 IMAGE_FALLBACK, Placement, file_subtitle, fit_image, local_image_index, placement,
421 IMAGE_FALLBACK, Placement, file_subtitle, fit_image, fit_image_within, local_image_index,
412 placements,
422 placement, placements,
413 };
423 };
414 use crate::render::Block;
424 use crate::render::Block;
415 use teams_core::{FileCard, FileKind, ImageRef};
425 use teams_core::{FileCard, FileKind, ImageRef};
@@ -455,6 +465,11 @@ mod tests {
455 assert_eq!(fit_image(Some((720, 360))), (360., 180.));
465 assert_eq!(fit_image(Some((720, 360))), (360., 180.));
456 }
466 }
457
467
468 #[test]
469 fn gifs_and_stickers_are_capped_at_250_high() {
470 assert_eq!(fit_image_within(Some((300, 500)), 250.), (150., 250.));
471 }
472
458 #[test]
473 #[test]
459 fn tall_images_shrink_to_the_max_height() {
474 fn tall_images_shrink_to_the_max_height() {
460 assert_eq!(fit_image(Some((300, 600))), (150., 300.));
475 assert_eq!(fit_image(Some((300, 600))), (150., 300.));
crates/app/src/views/composer.rs +185 −17
@@ -8,12 +8,15 @@ use std::time::{Duration, Instant};
8 8
9 9 use gpui_kit::assets::IconName;
10 10 use gpui_kit::component::{
11 ActiveTheme as _, h_flex,
11 ActiveTheme as _,
12 button::{Button, ButtonVariants as _},
13 h_flex,
12 14 input::{
13 15 Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,
14 16 InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
15 17 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
16 18 },
19 popover::Popover,
17 20 tooltip::Tooltip,
18 21 v_flex,
19 22 };
@@ -35,9 +38,11 @@ use super::draft_style::draft_style;
35 38 use super::emoji_popup::{self, EmojiPopup};
36 39 use super::format_toolbar::{self, FormatButton};
37 40 use super::link_preview::{ComposeLink, draft_link, link_preview_card};
41 use super::fun_picker::{FunPicker, FunPickerEvent};
38 42 use super::widgets::{icon, symbol};
39 43 use crate::app_state::AppState;
40 44 use crate::emoji;
45 use crate::remote_image::RemoteImage;
41 46 use crate::runtime;
42 47 use crate::theme;
43 48 use crate::typing::OutgoingTyping;
@@ -127,15 +132,20 @@ impl Outgoing {
127 132 /// The body before mentions become `<at>` tags.
128 133 pub fn html(&self) -> String {
129 134 let mut html = String::new();
130 let mut placed = 0;
135 let mut objects = self.images.iter();
136 let mut uploaded = 0;
131 137 for character in self.draft.to_html().chars() {
132 138 if character != OBJECT_MARK {
133 139 html.push(character);
134 140 continue;
135 141 }
136 placed += 1;
137 if placed <= self.images.len() {
138 html.push_str(&format!("<img src=\"../hostedContents/{placed}/$value\">"));
142 match objects.next() {
143 Some(OutgoingImage::Inline(_)) => {
144 uploaded += 1;
145 html.push_str(&format!("<img src=\"../hostedContents/{uploaded}/$value\">"));
146 }
147 Some(OutgoingImage::Remote(remote)) => html.push_str(&remote.html()),
148 None => {}
139 149 }
140 150 }
141 151 html
@@ -151,9 +161,12 @@ impl Outgoing {
151 161 images: self
152 162 .images
153 163 .iter()
154 .map(|outgoing| HostedImage {
155 content_type: outgoing.image.format.mime_type().to_owned(),
156 bytes: Arc::new(outgoing.image.bytes.clone()),
164 .filter_map(|outgoing| match outgoing {
165 OutgoingImage::Inline(inline) => Some(HostedImage {
166 content_type: inline.image.format.mime_type().to_owned(),
167 bytes: Arc::new(inline.image.bytes.clone()),
168 }),
169 OutgoingImage::Remote(_) => None,
157 170 })
158 171 .collect(),
159 172 files: self
@@ -268,7 +281,8 @@ pub struct Composer {
268 281 carry_images_into: Option<String>,
269 282 pending_anchors: HashMap<u64, usize>,
270 283 link: ComposeLink,
271 _subscriptions: [Subscription; 3],
284 fun_picker: Entity<FunPicker>,
285 _subscriptions: [Subscription; 4],
272 286 }
273 287
274 288 impl EventEmitter<ComposerEvent> for Composer {}
@@ -410,6 +424,8 @@ impl Composer {
410 424 cx.notify();
411 425 }
412 426 });
427 let fun_picker = cx.new(|cx| FunPicker::new(app.clone(), window, cx));
428 let picker_subscription = cx.subscribe_in(&fun_picker, window, Self::on_fun_pick);
413 429 let decorations = input.update(cx, |state, cx| {
414 430 (
415 431 state.create_decorations_collection(Vec::new(), cx),
@@ -457,7 +473,8 @@ impl Composer {
457 473 carry_images_into: None,
458 474 pending_anchors: HashMap::new(),
459 475 link: ComposeLink::default(),
460 _subscriptions: [subscription, observer, image_observer],
476 fun_picker,
477 _subscriptions: [subscription, observer, image_observer, picker_subscription],
461 478 }
462 479 }
463 480
@@ -1699,8 +1716,9 @@ impl Composer {
1699 1716 cx.notify();
1700 1717 }
1701 1718
1702 fn add_pending(&mut self, names: &[String], cx: &App) -> Vec<u64> {
1703 if self.tray.items().len() + names.len() > MAX_ATTACHMENTS {
1719 /// Images that no longer sit in the text give way to new attachments.
1720 fn make_room(&mut self, needed: usize, cx: &App) {
1721 if self.tray.items().len() + needed > MAX_ATTACHMENTS {
1704 1722 let referenced: Vec<u64> = self
1705 1723 .input
1706 1724 .read(cx)
@@ -1710,6 +1728,10 @@ impl Composer {
1710 1728 .collect();
1711 1729 self.tray.discard_images_except(&referenced);
1712 1730 }
1731 }
1732
1733 fn add_pending(&mut self, names: &[String], cx: &App) -> Vec<u64> {
1734 self.make_room(names.len(), cx);
1713 1735 let ids = self.tray.add_pending(names);
1714 1736 let anchor = self.selection(cx).end;
1715 1737 self.pending_anchors
@@ -1736,6 +1758,41 @@ impl Composer {
1736 1758 .detach();
1737 1759 }
1738 1760
1761 fn on_fun_pick(
1762 &mut self,
1763 _: &Entity<FunPicker>,
1764 event: &FunPickerEvent,
1765 window: &mut Window,
1766 cx: &mut Context<Self>,
1767 ) {
1768 match event {
1769 FunPickerEvent::Emoji(glyph) => self.insert_emoji(glyph, window, cx),
1770 FunPickerEvent::Image(image) => self.insert_remote_image(image.clone(), window, cx),
1771 }
1772 }
1773
1774 fn insert_emoji(&mut self, glyph: &str, window: &mut Window, cx: &mut Context<Self>) {
1775 let range = self.selection(cx);
1776 let cursor = range.end;
1777 self.replace_text(range, glyph, cursor, window, cx);
1778 self.remember_emoji(glyph, cx);
1779 cx.notify();
1780 }
1781
1782 fn insert_remote_image(
1783 &mut self,
1784 image: RemoteImage,
1785 window: &mut Window,
1786 cx: &mut Context<Self>,
1787 ) {
1788 self.make_room(1, cx);
1789 if let Some(id) = self.tray.add_remote(image) {
1790 self.insert_image_token(id, window, cx);
1791 }
1792 self.focus(window, cx);
1793 cx.notify();
1794 }
1795
1739 1796 fn paste(&mut self, item: &ClipboardItem, window: &mut Window, cx: &mut Context<Self>) -> bool {
1740 1797 if self.editing.is_none() {
1741 1798 match paste_action(item) {
@@ -2348,6 +2405,31 @@ impl Render for Composer {
2348 2405 .hover(|button| button.bg(white().opacity(0.1)))
2349 2406 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
2350 2407 });
2408 let fun = can_attach.then(|| {
2409 let picker = self.fun_picker.clone();
2410 let reset_picker = self.fun_picker.clone();
2411 Popover::new("composer-fun-popover")
2412 .anchor(Anchor::BottomLeft)
2413 .offset(px(10.))
2414 .p_0()
2415 .trigger(
2416 Button::new("composer-fun")
2417 .ghost()
2418 .size(px(32.))
2419 .tooltip("Emoji, GIFs und Sticker")
2420 .child(symbol("mood", 20., theme::text_muted())),
2421 )
2422 .on_open_change(move |open, window, cx| {
2423 if *open {
2424 reset_picker.update(cx, |picker, cx| picker.reset(window, cx));
2425 }
2426 })
2427 .content(move |_, _, cx| {
2428 let popover = cx.entity().downgrade();
2429 picker.update(cx, |picker, _| picker.set_popover(popover));
2430 picker.clone()
2431 })
2432 });
2351 2433 let attach = can_attach.then(|| {
2352 2434 div()
2353 2435 .id("composer-attach")
@@ -2613,6 +2695,7 @@ impl Render for Composer {
2613 2695 .py(px(6.))
2614 2696 .pl(px(if can_attach { 6. } else { 12. }))
2615 2697 .pr(px(6.))
2698 .children(fun)
2616 2699 .children(attach)
2617 2700 .child(
2618 2701 div()
@@ -2725,6 +2808,7 @@ mod tests {
2725 2808 use gpui_kit::{Image, ImageFormat};
2726 2809 use teams_core::FileKind;
2727 2810
2811 use super::super::attachment_tray::InlineImage;
2728 2812 use super::{Outgoing, OutgoingFile, OutgoingImage};
2729 2813
2730 2814 let outgoing = Outgoing {
@@ -2733,11 +2817,11 @@ mod tests {
2733 2817 link_preview: None,
2734 2818 reply: None,
2735 2819 edit: None,
2736 images: vec![OutgoingImage {
2820 images: vec![OutgoingImage::Inline(InlineImage {
2737 2821 name: "pasted-image.png".into(),
2738 2822 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
2739 2823 dimensions: Some((1, 1)),
2740 }],
2824 })],
2741 2825 files: vec![OutgoingFile {
2742 2826 name: "plan.pdf".into(),
2743 2827 size: 9,
@@ -2762,11 +2846,21 @@ mod tests {
2762 2846
2763 2847 use gpui_kit::{Image, ImageFormat};
2764 2848
2765 super::OutgoingImage {
2849 super::OutgoingImage::Inline(super::super::attachment_tray::InlineImage {
2766 2850 name: "pasted-image.png".into(),
2767 2851 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![width as u8])),
2768 2852 dimensions: Some((width, width)),
2769 }
2853 })
2854 }
2855
2856 fn remote_gif(title: &str) -> super::OutgoingImage {
2857 super::OutgoingImage::Remote(super::RemoteImage {
2858 kind: crate::remote_image::RemoteKind::Gif,
2859 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
2860 title: title.into(),
2861 width: 200,
2862 height: 100,
2863 })
2770 2864 }
2771 2865
2772 2866 fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {
@@ -2800,6 +2894,33 @@ mod tests {
2800 2894 );
2801 2895 }
2802 2896
2897 #[test]
2898 fn gifs_sit_in_place_and_only_uploaded_images_are_numbered() {
2899 let outgoing = outgoing_with(
2900 "\u{FFFC}a\u{FFFC}b\u{FFFC}",
2901 vec![placed_image(2), remote_gif("Wave"), placed_image(4)],
2902 );
2903 assert_eq!(
2904 outgoing.html(),
2905 "<img src=\"../hostedContents/1/$value\">a<img src=\"https://media0.giphy.com/media/a/giphy.gif\" width=\"200\" height=\"100\" alt=\"Wave\" itemtype=\"http://schema.skype.com/Giphy\">b<img src=\"../hostedContents/2/$value\">"
2906 );
2907 assert_eq!(outgoing.extras().images.len(), 2);
2908 }
2909
2910 #[test]
2911 fn a_gif_title_is_escaped_in_the_html() {
2912 let outgoing = outgoing_with("\u{FFFC}", vec![remote_gif("a \"b\" <c>")]);
2913 assert!(outgoing.html().contains("alt=\"a &quot;b&quot; &lt;c&gt;\""));
2914 }
2915
2916 #[test]
2917 fn a_sticker_carries_the_sticker_itemtype() {
2918 let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
2919 let outgoing = outgoing_with("\u{FFFC}", vec![super::OutgoingImage::Remote(sticker)]);
2920 assert!(outgoing.html().contains("itemtype=\"http://schema.skype.com/Sticker\""));
2921 assert!(outgoing.html().contains("width=\"250\" height=\"250\""));
2922 }
2923
2803 2924 #[test]
2804 2925 fn a_mark_without_an_image_leaves_no_trace() {
2805 2926 assert_eq!(outgoing_with("a\u{FFFC}b", Vec::new()).html(), "ab");
@@ -3059,7 +3180,10 @@ mod tests {
3059 3180 let dimensions: Vec<_> = outgoing
3060 3181 .images
3061 3182 .iter()
3062 .map(|image| image.dimensions)
3183 .map(|image| match image {
3184 super::super::OutgoingImage::Inline(inline) => inline.dimensions,
3185 super::super::OutgoingImage::Remote(_) => None,
3186 })
3063 3187 .collect();
3064 3188 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
3065 3189 assert_eq!(
@@ -3083,6 +3207,50 @@ mod tests {
3083 3207 assert_eq!(copied.as_deref(), Some("hi"));
3084 3208 }
3085 3209
3210 #[gpui_kit::test]
3211 fn an_inserted_gif_alone_can_be_sent_and_undo_removes_it(cx: &mut TestAppContext) {
3212 let mut typist = typist(cx);
3213 let composer = typist.composer.clone();
3214 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3215 typist.act(|window, cx| {
3216 composer.update(cx, |composer, cx| {
3217 composer.insert_remote_image(
3218 super::super::RemoteImage {
3219 kind: crate::remote_image::RemoteKind::Gif,
3220 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
3221 title: "Wave".into(),
3222 width: 200,
3223 height: 100,
3224 },
3225 window,
3226 cx,
3227 )
3228 });
3229 });
3230 assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3231 assert_eq!(typist.value(), "\u{FFFC}");
3232 let outgoing = typist.outgoing();
3233 assert!(outgoing.html().starts_with("<img src=\"https://media0.giphy.com/"));
3234 assert!(outgoing.extras().images.is_empty());
3235 typist.press("ctrl-z");
3236 assert_eq!(typist.value(), "");
3237 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3238 }
3239
3240 #[gpui_kit::test]
3241 fn an_inserted_emoji_lands_at_the_cursor(cx: &mut TestAppContext) {
3242 let mut typist = typist(cx);
3243 typist.type_text("ab");
3244 typist.press("left");
3245 let composer = typist.composer.clone();
3246 typist.act(|window, cx| {
3247 composer.update(cx, |composer, cx| {
3248 composer.insert_emoji("\u{1F44D}", window, cx)
3249 });
3250 });
3251 assert_eq!(typist.value(), "a\u{1F44D}b");
3252 }
3253
3086 3254 #[gpui_kit::test]
3087 3255 fn pasted_text_loses_object_marks(cx: &mut TestAppContext) {
3088 3256 let mut typist = typist(cx);
@@ -8,12 +8,15 @@ use std::time::{Duration, Instant};
8
8
9use gpui_kit::assets::IconName;
9use gpui_kit::assets::IconName;
10use gpui_kit::component::{
10use gpui_kit::component::{
11 ActiveTheme as _, h_flex,
11 ActiveTheme as _,
12 button::{Button, ButtonVariants as _},
13 h_flex,
12 input::{
14 input::{
13 Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,
15 Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,
14 InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
16 InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
15 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
17 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
16 },
18 },
19 popover::Popover,
17 tooltip::Tooltip,
20 tooltip::Tooltip,
18 v_flex,
21 v_flex,
19};
22};
@@ -35,9 +38,11 @@ use super::draft_style::draft_style;
35use super::emoji_popup::{self, EmojiPopup};
38use super::emoji_popup::{self, EmojiPopup};
36use super::format_toolbar::{self, FormatButton};
39use super::format_toolbar::{self, FormatButton};
37use super::link_preview::{ComposeLink, draft_link, link_preview_card};
40use super::link_preview::{ComposeLink, draft_link, link_preview_card};
41use super::fun_picker::{FunPicker, FunPickerEvent};
38use super::widgets::{icon, symbol};
42use super::widgets::{icon, symbol};
39use crate::app_state::AppState;
43use crate::app_state::AppState;
40use crate::emoji;
44use crate::emoji;
45use crate::remote_image::RemoteImage;
41use crate::runtime;
46use crate::runtime;
42use crate::theme;
47use crate::theme;
43use crate::typing::OutgoingTyping;
48use crate::typing::OutgoingTyping;
@@ -127,15 +132,20 @@ impl Outgoing {
127 /// The body before mentions become `<at>` tags.
132 /// The body before mentions become `<at>` tags.
128 pub fn html(&self) -> String {
133 pub fn html(&self) -> String {
129 let mut html = String::new();
134 let mut html = String::new();
130 let mut placed = 0;
135 let mut objects = self.images.iter();
136 let mut uploaded = 0;
131 for character in self.draft.to_html().chars() {
137 for character in self.draft.to_html().chars() {
132 if character != OBJECT_MARK {
138 if character != OBJECT_MARK {
133 html.push(character);
139 html.push(character);
134 continue;
140 continue;
135 }
141 }
136 placed += 1;
142 match objects.next() {
137 if placed <= self.images.len() {
143 Some(OutgoingImage::Inline(_)) => {
138 html.push_str(&format!("<img src=\"../hostedContents/{placed}/$value\">"));
144 uploaded += 1;
145 html.push_str(&format!("<img src=\"../hostedContents/{uploaded}/$value\">"));
146 }
147 Some(OutgoingImage::Remote(remote)) => html.push_str(&remote.html()),
148 None => {}
139 }
149 }
140 }
150 }
141 html
151 html
@@ -151,9 +161,12 @@ impl Outgoing {
151 images: self
161 images: self
152 .images
162 .images
153 .iter()
163 .iter()
154 .map(|outgoing| HostedImage {
164 .filter_map(|outgoing| match outgoing {
155 content_type: outgoing.image.format.mime_type().to_owned(),
165 OutgoingImage::Inline(inline) => Some(HostedImage {
156 bytes: Arc::new(outgoing.image.bytes.clone()),
166 content_type: inline.image.format.mime_type().to_owned(),
167 bytes: Arc::new(inline.image.bytes.clone()),
168 }),
169 OutgoingImage::Remote(_) => None,
157 })
170 })
158 .collect(),
171 .collect(),
159 files: self
172 files: self
@@ -268,7 +281,8 @@ pub struct Composer {
268 carry_images_into: Option<String>,
281 carry_images_into: Option<String>,
269 pending_anchors: HashMap<u64, usize>,
282 pending_anchors: HashMap<u64, usize>,
270 link: ComposeLink,
283 link: ComposeLink,
271 _subscriptions: [Subscription; 3],
284 fun_picker: Entity<FunPicker>,
285 _subscriptions: [Subscription; 4],
272}
286}
273
287
274impl EventEmitter<ComposerEvent> for Composer {}
288impl EventEmitter<ComposerEvent> for Composer {}
@@ -410,6 +424,8 @@ impl Composer {
410 cx.notify();
424 cx.notify();
411 }
425 }
412 });
426 });
427 let fun_picker = cx.new(|cx| FunPicker::new(app.clone(), window, cx));
428 let picker_subscription = cx.subscribe_in(&fun_picker, window, Self::on_fun_pick);
413 let decorations = input.update(cx, |state, cx| {
429 let decorations = input.update(cx, |state, cx| {
414 (
430 (
415 state.create_decorations_collection(Vec::new(), cx),
431 state.create_decorations_collection(Vec::new(), cx),
@@ -457,7 +473,8 @@ impl Composer {
457 carry_images_into: None,
473 carry_images_into: None,
458 pending_anchors: HashMap::new(),
474 pending_anchors: HashMap::new(),
459 link: ComposeLink::default(),
475 link: ComposeLink::default(),
460 _subscriptions: [subscription, observer, image_observer],
476 fun_picker,
477 _subscriptions: [subscription, observer, image_observer, picker_subscription],
461 }
478 }
462 }
479 }
463
480
@@ -1699,8 +1716,9 @@ impl Composer {
1699 cx.notify();
1716 cx.notify();
1700 }
1717 }
1701
1718
1702 fn add_pending(&mut self, names: &[String], cx: &App) -> Vec<u64> {
1719 /// Images that no longer sit in the text give way to new attachments.
1703 if self.tray.items().len() + names.len() > MAX_ATTACHMENTS {
1720 fn make_room(&mut self, needed: usize, cx: &App) {
1721 if self.tray.items().len() + needed > MAX_ATTACHMENTS {
1704 let referenced: Vec<u64> = self
1722 let referenced: Vec<u64> = self
1705 .input
1723 .input
1706 .read(cx)
1724 .read(cx)
@@ -1710,6 +1728,10 @@ impl Composer {
1710 .collect();
1728 .collect();
1711 self.tray.discard_images_except(&referenced);
1729 self.tray.discard_images_except(&referenced);
1712 }
1730 }
1731 }
1732
1733 fn add_pending(&mut self, names: &[String], cx: &App) -> Vec<u64> {
1734 self.make_room(names.len(), cx);
1713 let ids = self.tray.add_pending(names);
1735 let ids = self.tray.add_pending(names);
1714 let anchor = self.selection(cx).end;
1736 let anchor = self.selection(cx).end;
1715 self.pending_anchors
1737 self.pending_anchors
@@ -1736,6 +1758,41 @@ impl Composer {
1736 .detach();
1758 .detach();
1737 }
1759 }
1738
1760
1761 fn on_fun_pick(
1762 &mut self,
1763 _: &Entity<FunPicker>,
1764 event: &FunPickerEvent,
1765 window: &mut Window,
1766 cx: &mut Context<Self>,
1767 ) {
1768 match event {
1769 FunPickerEvent::Emoji(glyph) => self.insert_emoji(glyph, window, cx),
1770 FunPickerEvent::Image(image) => self.insert_remote_image(image.clone(), window, cx),
1771 }
1772 }
1773
1774 fn insert_emoji(&mut self, glyph: &str, window: &mut Window, cx: &mut Context<Self>) {
1775 let range = self.selection(cx);
1776 let cursor = range.end;
1777 self.replace_text(range, glyph, cursor, window, cx);
1778 self.remember_emoji(glyph, cx);
1779 cx.notify();
1780 }
1781
1782 fn insert_remote_image(
1783 &mut self,
1784 image: RemoteImage,
1785 window: &mut Window,
1786 cx: &mut Context<Self>,
1787 ) {
1788 self.make_room(1, cx);
1789 if let Some(id) = self.tray.add_remote(image) {
1790 self.insert_image_token(id, window, cx);
1791 }
1792 self.focus(window, cx);
1793 cx.notify();
1794 }
1795
1739 fn paste(&mut self, item: &ClipboardItem, window: &mut Window, cx: &mut Context<Self>) -> bool {
1796 fn paste(&mut self, item: &ClipboardItem, window: &mut Window, cx: &mut Context<Self>) -> bool {
1740 if self.editing.is_none() {
1797 if self.editing.is_none() {
1741 match paste_action(item) {
1798 match paste_action(item) {
@@ -2348,6 +2405,31 @@ impl Render for Composer {
2348 .hover(|button| button.bg(white().opacity(0.1)))
2405 .hover(|button| button.bg(white().opacity(0.1)))
2349 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
2406 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
2350 });
2407 });
2408 let fun = can_attach.then(|| {
2409 let picker = self.fun_picker.clone();
2410 let reset_picker = self.fun_picker.clone();
2411 Popover::new("composer-fun-popover")
2412 .anchor(Anchor::BottomLeft)
2413 .offset(px(10.))
2414 .p_0()
2415 .trigger(
2416 Button::new("composer-fun")
2417 .ghost()
2418 .size(px(32.))
2419 .tooltip("Emoji, GIFs und Sticker")
2420 .child(symbol("mood", 20., theme::text_muted())),
2421 )
2422 .on_open_change(move |open, window, cx| {
2423 if *open {
2424 reset_picker.update(cx, |picker, cx| picker.reset(window, cx));
2425 }
2426 })
2427 .content(move |_, _, cx| {
2428 let popover = cx.entity().downgrade();
2429 picker.update(cx, |picker, _| picker.set_popover(popover));
2430 picker.clone()
2431 })
2432 });
2351 let attach = can_attach.then(|| {
2433 let attach = can_attach.then(|| {
2352 div()
2434 div()
2353 .id("composer-attach")
2435 .id("composer-attach")
@@ -2613,6 +2695,7 @@ impl Render for Composer {
2613 .py(px(6.))
2695 .py(px(6.))
2614 .pl(px(if can_attach { 6. } else { 12. }))
2696 .pl(px(if can_attach { 6. } else { 12. }))
2615 .pr(px(6.))
2697 .pr(px(6.))
2698 .children(fun)
2616 .children(attach)
2699 .children(attach)
2617 .child(
2700 .child(
2618 div()
2701 div()
@@ -2725,6 +2808,7 @@ mod tests {
2725 use gpui_kit::{Image, ImageFormat};
2808 use gpui_kit::{Image, ImageFormat};
2726 use teams_core::FileKind;
2809 use teams_core::FileKind;
2727
2810
2811 use super::super::attachment_tray::InlineImage;
2728 use super::{Outgoing, OutgoingFile, OutgoingImage};
2812 use super::{Outgoing, OutgoingFile, OutgoingImage};
2729
2813
2730 let outgoing = Outgoing {
2814 let outgoing = Outgoing {
@@ -2733,11 +2817,11 @@ mod tests {
2733 link_preview: None,
2817 link_preview: None,
2734 reply: None,
2818 reply: None,
2735 edit: None,
2819 edit: None,
2736 images: vec![OutgoingImage {
2820 images: vec![OutgoingImage::Inline(InlineImage {
2737 name: "pasted-image.png".into(),
2821 name: "pasted-image.png".into(),
2738 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
2822 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
2739 dimensions: Some((1, 1)),
2823 dimensions: Some((1, 1)),
2740 }],
2824 })],
2741 files: vec![OutgoingFile {
2825 files: vec![OutgoingFile {
2742 name: "plan.pdf".into(),
2826 name: "plan.pdf".into(),
2743 size: 9,
2827 size: 9,
@@ -2762,11 +2846,21 @@ mod tests {
2762
2846
2763 use gpui_kit::{Image, ImageFormat};
2847 use gpui_kit::{Image, ImageFormat};
2764
2848
2765 super::OutgoingImage {
2849 super::OutgoingImage::Inline(super::super::attachment_tray::InlineImage {
2766 name: "pasted-image.png".into(),
2850 name: "pasted-image.png".into(),
2767 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![width as u8])),
2851 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![width as u8])),
2768 dimensions: Some((width, width)),
2852 dimensions: Some((width, width)),
2769 }
2853 })
2854 }
2855
2856 fn remote_gif(title: &str) -> super::OutgoingImage {
2857 super::OutgoingImage::Remote(super::RemoteImage {
2858 kind: crate::remote_image::RemoteKind::Gif,
2859 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
2860 title: title.into(),
2861 width: 200,
2862 height: 100,
2863 })
2770 }
2864 }
2771
2865
2772 fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {
2866 fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {
@@ -2800,6 +2894,33 @@ mod tests {
2800 );
2894 );
2801 }
2895 }
2802
2896
2897 #[test]
2898 fn gifs_sit_in_place_and_only_uploaded_images_are_numbered() {
2899 let outgoing = outgoing_with(
2900 "\u{FFFC}a\u{FFFC}b\u{FFFC}",
2901 vec![placed_image(2), remote_gif("Wave"), placed_image(4)],
2902 );
2903 assert_eq!(
2904 outgoing.html(),
2905 "<img src=\"../hostedContents/1/$value\">a<img src=\"https://media0.giphy.com/media/a/giphy.gif\" width=\"200\" height=\"100\" alt=\"Wave\" itemtype=\"http://schema.skype.com/Giphy\">b<img src=\"../hostedContents/2/$value\">"
2906 );
2907 assert_eq!(outgoing.extras().images.len(), 2);
2908 }
2909
2910 #[test]
2911 fn a_gif_title_is_escaped_in_the_html() {
2912 let outgoing = outgoing_with("\u{FFFC}", vec![remote_gif("a \"b\" <c>")]);
2913 assert!(outgoing.html().contains("alt=\"a &quot;b&quot; &lt;c&gt;\""));
2914 }
2915
2916 #[test]
2917 fn a_sticker_carries_the_sticker_itemtype() {
2918 let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
2919 let outgoing = outgoing_with("\u{FFFC}", vec![super::OutgoingImage::Remote(sticker)]);
2920 assert!(outgoing.html().contains("itemtype=\"http://schema.skype.com/Sticker\""));
2921 assert!(outgoing.html().contains("width=\"250\" height=\"250\""));
2922 }
2923
2803 #[test]
2924 #[test]
2804 fn a_mark_without_an_image_leaves_no_trace() {
2925 fn a_mark_without_an_image_leaves_no_trace() {
2805 assert_eq!(outgoing_with("a\u{FFFC}b", Vec::new()).html(), "ab");
2926 assert_eq!(outgoing_with("a\u{FFFC}b", Vec::new()).html(), "ab");
@@ -3059,7 +3180,10 @@ mod tests {
3059 let dimensions: Vec<_> = outgoing
3180 let dimensions: Vec<_> = outgoing
3060 .images
3181 .images
3061 .iter()
3182 .iter()
3062 .map(|image| image.dimensions)
3183 .map(|image| match image {
3184 super::super::OutgoingImage::Inline(inline) => inline.dimensions,
3185 super::super::OutgoingImage::Remote(_) => None,
3186 })
3063 .collect();
3187 .collect();
3064 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
3188 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
3065 assert_eq!(
3189 assert_eq!(
@@ -3083,6 +3207,50 @@ mod tests {
3083 assert_eq!(copied.as_deref(), Some("hi"));
3207 assert_eq!(copied.as_deref(), Some("hi"));
3084 }
3208 }
3085
3209
3210 #[gpui_kit::test]
3211 fn an_inserted_gif_alone_can_be_sent_and_undo_removes_it(cx: &mut TestAppContext) {
3212 let mut typist = typist(cx);
3213 let composer = typist.composer.clone();
3214 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3215 typist.act(|window, cx| {
3216 composer.update(cx, |composer, cx| {
3217 composer.insert_remote_image(
3218 super::super::RemoteImage {
3219 kind: crate::remote_image::RemoteKind::Gif,
3220 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
3221 title: "Wave".into(),
3222 width: 200,
3223 height: 100,
3224 },
3225 window,
3226 cx,
3227 )
3228 });
3229 });
3230 assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3231 assert_eq!(typist.value(), "\u{FFFC}");
3232 let outgoing = typist.outgoing();
3233 assert!(outgoing.html().starts_with("<img src=\"https://media0.giphy.com/"));
3234 assert!(outgoing.extras().images.is_empty());
3235 typist.press("ctrl-z");
3236 assert_eq!(typist.value(), "");
3237 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3238 }
3239
3240 #[gpui_kit::test]
3241 fn an_inserted_emoji_lands_at_the_cursor(cx: &mut TestAppContext) {
3242 let mut typist = typist(cx);
3243 typist.type_text("ab");
3244 typist.press("left");
3245 let composer = typist.composer.clone();
3246 typist.act(|window, cx| {
3247 composer.update(cx, |composer, cx| {
3248 composer.insert_emoji("\u{1F44D}", window, cx)
3249 });
3250 });
3251 assert_eq!(typist.value(), "a\u{1F44D}b");
3252 }
3253
3086 #[gpui_kit::test]
3254 #[gpui_kit::test]
3087 fn pasted_text_loses_object_marks(cx: &mut TestAppContext) {
3255 fn pasted_text_loses_object_marks(cx: &mut TestAppContext) {
3088 let mut typist = typist(cx);
3256 let mut typist = typist(cx);
crates/app/src/views/conversation.rs +15 −4
@@ -19,6 +19,7 @@ use store::MessageRecord;
19 19 use teams_core::{FileCard, ImageRef, LinkPreview};
20 20
21 21 use super::adaptive_card::ensure_cards_inputs;
22 use super::attachment_tray::OutgoingImage;
22 23 use super::attachments::FileActions;
23 24 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
24 25 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
@@ -1749,13 +1750,23 @@ impl ConversationView {
1749 1750 edited: false,
1750 1751 deleted: false,
1751 1752 reactions: Vec::new(),
1752 images: Vec::new(),
1753 images: outgoing
1754 .images
1755 .iter()
1756 .filter_map(|image| match image {
1757 OutgoingImage::Remote(remote) => Some(remote.image_ref()),
1758 OutgoingImage::Inline(_) => None,
1759 })
1760 .collect(),
1753 1761 local_images: outgoing
1754 1762 .images
1755 1763 .iter()
1756 .map(|image| LocalImage {
1757 image: image.image.clone(),
1758 size: image.dimensions,
1764 .filter_map(|image| match image {
1765 OutgoingImage::Inline(inline) => Some(LocalImage {
1766 image: inline.image.clone(),
1767 size: inline.dimensions,
1768 }),
1769 OutgoingImage::Remote(_) => None,
1759 1770 })
1760 1771 .collect(),
1761 1772 adaptive_cards: Vec::new(),
@@ -19,6 +19,7 @@ use store::MessageRecord;
19use teams_core::{FileCard, ImageRef, LinkPreview};
19use teams_core::{FileCard, ImageRef, LinkPreview};
20
20
21use super::adaptive_card::ensure_cards_inputs;
21use super::adaptive_card::ensure_cards_inputs;
22use super::attachment_tray::OutgoingImage;
22use super::attachments::FileActions;
23use super::attachments::FileActions;
23use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
24use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
24use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
25use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
@@ -1749,13 +1750,23 @@ impl ConversationView {
1749 edited: false,
1750 edited: false,
1750 deleted: false,
1751 deleted: false,
1751 reactions: Vec::new(),
1752 reactions: Vec::new(),
1752 images: Vec::new(),
1753 images: outgoing
1754 .images
1755 .iter()
1756 .filter_map(|image| match image {
1757 OutgoingImage::Remote(remote) => Some(remote.image_ref()),
1758 OutgoingImage::Inline(_) => None,
1759 })
1760 .collect(),
1753 local_images: outgoing
1761 local_images: outgoing
1754 .images
1762 .images
1755 .iter()
1763 .iter()
1756 .map(|image| LocalImage {
1764 .filter_map(|image| match image {
1757 image: image.image.clone(),
1765 OutgoingImage::Inline(inline) => Some(LocalImage {
1758 size: image.dimensions,
1766 image: inline.image.clone(),
1767 size: inline.dimensions,
1768 }),
1769 OutgoingImage::Remote(_) => None,
1759 })
1770 })
1760 .collect(),
1771 .collect(),
1761 adaptive_cards: Vec::new(),
1772 adaptive_cards: Vec::new(),
crates/app/src/views/fun_picker.rs added +747 −0
@@ -0,0 +1,747 @@
1 use std::time::Duration;
2
3 use gpui_kit::base::PopoverState;
4 use gpui_kit::component::{
5 h_flex,
6 input::{Input, InputEvent, InputState},
7 v_flex,
8 };
9 use gpui_kit::prelude::FluentBuilder as _;
10 use gpui_kit::*;
11 use teams_core::Gif;
12
13 use crate::app_state::AppState;
14 use crate::emoji;
15 use crate::gifs::{self, GifError};
16 use crate::remote_image::{RemoteImage, image_source};
17 use crate::stickers::{self, Sticker};
18 use crate::theme;
19
20 const TAB_KEY: &str = "fun_picker_tab";
21 const WIDTH: f32 = 360.;
22 const HEIGHT: f32 = 380.;
23 const PADDING: f32 = 8.;
24 const CONTENT_WIDTH: f32 = WIDTH - 2. * PADDING;
25 const EMOJI_COLUMNS: usize = 8;
26 const EMOJI_CELL: f32 = 32.;
27 const EMOJI_GAP: f32 = 2.;
28 const EMOJI_SEARCH_LIMIT: usize = 240;
29 const GIF_COLUMNS: usize = 3;
30 const GIF_GAP: f32 = 6.;
31 const GIF_DEBOUNCE: Duration = Duration::from_millis(300);
32 const GIF_MIN_HEIGHT: f32 = 48.;
33 const GIF_MAX_HEIGHT: f32 = 200.;
34 const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];
35 const STICKER_COLUMNS: usize = 4;
36 const STICKER_GAP: f32 = 6.;
37 const POPULAR_LABEL: &str = "Beliebt";
38 const TILE_RADIUS: f32 = 6.;
39
40 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
41 enum Tab {
42 Emoji,
43 Gif,
44 Sticker,
45 }
46
47 impl Tab {
48 const ALL: [Tab; 3] = [Tab::Emoji, Tab::Gif, Tab::Sticker];
49
50 fn key(self) -> &'static str {
51 match self {
52 Tab::Emoji => "emoji",
53 Tab::Gif => "gif",
54 Tab::Sticker => "sticker",
55 }
56 }
57
58 fn from_key(key: &str) -> Option<Tab> {
59 Tab::ALL.into_iter().find(|tab| tab.key() == key)
60 }
61
62 fn label(self) -> &'static str {
63 match self {
64 Tab::Emoji => "Emoji",
65 Tab::Gif => "GIF",
66 Tab::Sticker => "Sticker",
67 }
68 }
69
70 fn placeholder(self) -> &'static str {
71 match self {
72 Tab::Emoji => "Emoji suchen",
73 Tab::Gif => "GIFs suchen",
74 Tab::Sticker => "Sticker suchen",
75 }
76 }
77 }
78
79 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
80 enum StickerChip {
81 Popular,
82 Category(&'static str),
83 }
84
85 enum GifState {
86 Loading,
87 Ready(Vec<Gif>),
88 Failed,
89 Disabled,
90 }
91
92 enum EmojiRow {
93 Header(&'static str),
94 Cells(Vec<String>),
95 }
96
97 pub enum FunPickerEvent {
98 Emoji(String),
99 Image(RemoteImage),
100 }
101
102 pub struct FunPicker {
103 app: Entity<AppState>,
104 input: Entity<InputState>,
105 tab: Tab,
106 query: String,
107 recent: emoji::Recent,
108 popover: Option<WeakEntity<PopoverState>>,
109 emoji_rows: Vec<EmojiRow>,
110 emoji_scroll: UniformListScrollHandle,
111 gifs: GifState,
112 gif_generation: u64,
113 gif_task: Option<Task<()>>,
114 chip: StickerChip,
115 sticker_rows: Vec<Vec<&'static Sticker>>,
116 sticker_scroll: UniformListScrollHandle,
117 _subscription: Subscription,
118 }
119
120 impl EventEmitter<FunPickerEvent> for FunPicker {}
121
122 fn emoji_rows(query: &str, recent: &[String]) -> Vec<EmojiRow> {
123 let chunked = |glyphs: Vec<String>| -> Vec<EmojiRow> {
124 glyphs
125 .chunks(EMOJI_COLUMNS)
126 .map(|chunk| EmojiRow::Cells(chunk.to_vec()))
127 .collect()
128 };
129 if !query.is_empty() {
130 let found = emoji::search(query, recent, EMOJI_SEARCH_LIMIT)
131 .into_iter()
132 .map(|found| found.glyph.to_owned())
133 .collect();
134 return chunked(found);
135 }
136 let mut rows = Vec::new();
137 if !recent.is_empty() {
138 rows.push(EmojiRow::Header("Zuletzt verwendet"));
139 rows.extend(chunked(recent.to_vec()));
140 }
141 rows.push(EmojiRow::Header("Alle Emojis"));
142 rows.extend(chunked(emoji::glyphs().map(str::to_owned).collect()));
143 rows
144 }
145
146 fn sticker_rows(query: &str, chip: StickerChip) -> Vec<Vec<&'static Sticker>> {
147 let stickers = if !query.is_empty() {
148 stickers::search(query)
149 } else {
150 match chip {
151 StickerChip::Popular => stickers::popular(),
152 StickerChip::Category(category) => stickers::in_category(category),
153 }
154 };
155 stickers
156 .chunks(STICKER_COLUMNS)
157 .map(<[&Sticker]>::to_vec)
158 .collect()
159 }
160
161 /// Indices per column; each item goes to the currently shortest column.
162 fn masonry(heights: &[f32], columns: usize) -> Vec<Vec<usize>> {
163 let mut layout: Vec<Vec<usize>> = vec![Vec::new(); columns];
164 let mut totals = vec![0_f32; columns];
165 for (index, height) in heights.iter().enumerate() {
166 let shortest = totals
167 .iter()
168 .enumerate()
169 .min_by(|left, right| left.1.total_cmp(right.1))
170 .map_or(0, |(column, _)| column);
171 layout[shortest].push(index);
172 totals[shortest] += height + GIF_GAP;
173 }
174 layout
175 }
176
177 fn gif_tile_width() -> f32 {
178 (CONTENT_WIDTH - GIF_GAP * (GIF_COLUMNS - 1) as f32) / GIF_COLUMNS as f32
179 }
180
181 fn gif_tile_height(gif: &Gif) -> f32 {
182 let ratio = gif.preview_height as f32 / gif.preview_width.max(1) as f32;
183 (gif_tile_width() * ratio).clamp(GIF_MIN_HEIGHT, GIF_MAX_HEIGHT)
184 }
185
186 fn sticker_tile_size() -> f32 {
187 (CONTENT_WIDTH - STICKER_GAP * (STICKER_COLUMNS - 1) as f32) / STICKER_COLUMNS as f32
188 }
189
190 impl FunPicker {
191 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
192 let input = cx.new(|cx| InputState::new(window, cx).placeholder(Tab::Emoji.placeholder()));
193 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
194 let recent = emoji::Recent::load(&app.read(cx).store);
195 FunPicker {
196 app,
197 input,
198 tab: Tab::Emoji,
199 query: String::new(),
200 emoji_rows: emoji_rows("", &recent.glyphs()),
201 recent,
202 popover: None,
203 emoji_scroll: UniformListScrollHandle::new(),
204 gifs: GifState::Loading,
205 gif_generation: 0,
206 gif_task: None,
207 chip: StickerChip::Popular,
208 sticker_rows: sticker_rows("", StickerChip::Popular),
209 sticker_scroll: UniformListScrollHandle::new(),
210 _subscription: subscription,
211 }
212 }
213
214 pub fn set_popover(&mut self, popover: WeakEntity<PopoverState>) {
215 self.popover = Some(popover);
216 }
217
218 pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
219 let store = self.app.read(cx).store.clone();
220 self.recent.reload(&store);
221 self.tab = store
222 .meta(TAB_KEY)
223 .ok()
224 .flatten()
225 .and_then(|key| Tab::from_key(&key))
226 .unwrap_or(Tab::Emoji);
227 self.show_tab(window, cx);
228 }
229
230 fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
231 if tab == self.tab {
232 return;
233 }
234 self.tab = tab;
235 let _ = self.app.read(cx).store.set_meta(TAB_KEY, tab.key());
236 self.show_tab(window, cx);
237 }
238
239 fn show_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
240 self.query.clear();
241 let placeholder = self.tab.placeholder();
242 self.input.update(cx, |state, cx| {
243 state.set_value("", window, cx);
244 state.set_placeholder(placeholder, window, cx);
245 state.focus(window, cx);
246 });
247 self.refresh(false, cx);
248 }
249
250 fn refresh(&mut self, debounce: bool, cx: &mut Context<Self>) {
251 match self.tab {
252 Tab::Emoji => {
253 self.emoji_rows = emoji_rows(&self.query, &self.recent.glyphs());
254 self.emoji_scroll.scroll_to_item(0, ScrollStrategy::Top);
255 }
256 Tab::Gif => self.search_gifs(debounce, cx),
257 Tab::Sticker => {
258 self.sticker_rows = sticker_rows(&self.query, self.chip);
259 self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top);
260 }
261 }
262 cx.notify();
263 }
264
265 fn on_input_event(
266 &mut self,
267 input: &Entity<InputState>,
268 event: &InputEvent,
269 _: &mut Window,
270 cx: &mut Context<Self>,
271 ) {
272 match event {
273 InputEvent::Change => {
274 let query = input.read(cx).value().trim().to_owned();
275 if query != self.query {
276 self.query = query;
277 self.refresh(true, cx);
278 }
279 }
280 InputEvent::PressEnter { .. } if self.tab == Tab::Emoji => {
281 let first = self.emoji_rows.iter().find_map(|row| match row {
282 EmojiRow::Cells(glyphs) => glyphs.first().cloned(),
283 EmojiRow::Header(_) => None,
284 });
285 if let Some(glyph) = first.filter(|_| !self.query.is_empty()) {
286 self.pick_emoji(&glyph, cx);
287 }
288 }
289 _ => {}
290 }
291 }
292
293 fn search_gifs(&mut self, debounce: bool, cx: &mut Context<Self>) {
294 self.gif_generation += 1;
295 let generation = self.gif_generation;
296 self.gifs = GifState::Loading;
297 let query = self.query.clone();
298 let (demo, engine) = {
299 let state = self.app.read(cx);
300 (state.mode.demo, state.engine.clone())
301 };
302 self.gif_task = Some(cx.spawn(async move |this, cx| {
303 if debounce {
304 cx.background_executor().timer(GIF_DEBOUNCE).await;
305 }
306 let outcome = gifs::search(engine, demo, query)
307 .await
308 .unwrap_or(Err(GifError::Failed));
309 this.update(cx, |this, cx| {
310 if this.gif_generation != generation {
311 return;
312 }
313 this.gifs = match outcome {
314 Ok(found) => GifState::Ready(found),
315 Err(GifError::Disabled) => GifState::Disabled,
316 Err(GifError::Failed) => GifState::Failed,
317 };
318 cx.notify();
319 })
320 .ok();
321 }));
322 }
323
324 fn pick_emoji(&mut self, glyph: &str, cx: &mut Context<Self>) {
325 self.recent.push(glyph);
326 self.refresh(false, cx);
327 cx.emit(FunPickerEvent::Emoji(glyph.to_owned()));
328 }
329
330 fn pick_image(&mut self, image: RemoteImage, window: &mut Window, cx: &mut Context<Self>) {
331 if let Some(popover) = &self.popover {
332 popover
333 .update(cx, |state, cx| state.dismiss(window, cx))
334 .ok();
335 }
336 cx.emit(FunPickerEvent::Image(image));
337 }
338
339 fn select_chip(&mut self, chip: StickerChip, cx: &mut Context<Self>) {
340 self.chip = chip;
341 self.refresh(false, cx);
342 }
343
344 fn tab_button(&self, tab: Tab, cx: &mut Context<Self>) -> Stateful<Div> {
345 let selected = tab == self.tab;
346 div()
347 .id(("fun-picker-tab", tab as usize))
348 .h(px(32.))
349 .px(px(14.))
350 .flex()
351 .items_center()
352 .cursor_pointer()
353 .text_size(px(13.))
354 .font_weight(FontWeight::SEMIBOLD)
355 .border_b_2()
356 .border_color(if selected {
357 theme::accent()
358 } else {
359 transparent_black()
360 })
361 .text_color(if selected {
362 theme::accent_text()
363 } else {
364 theme::text_muted()
365 })
366 .hover(|button| button.text_color(theme::text_strong()))
367 .child(tab.label())
368 .on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
369 }
370
371 fn search_field(&self) -> Div {
372 div()
373 .h(px(32.))
374 .px(px(8.))
375 .flex()
376 .flex_none()
377 .items_center()
378 .rounded(px(8.))
379 .bg(theme::surface())
380 .border_1()
381 .border_color(theme::border_strong())
382 .child(Input::new(&self.input).appearance(false).bordered(false))
383 }
384
385 fn message(text: String) -> Div {
386 div()
387 .size_full()
388 .flex()
389 .flex_col()
390 .gap(px(8.))
391 .items_center()
392 .justify_center()
393 .text_size(px(12.5))
394 .text_color(theme::text_muted())
395 .child(text)
396 }
397
398 fn emoji_row(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
399 let row = match &self.emoji_rows[index] {
400 EmojiRow::Header(title) => {
401 return div()
402 .h(px(EMOJI_CELL + EMOJI_GAP))
403 .flex()
404 .items_end()
405 .pb(px(4.))
406 .text_size(px(11.))
407 .text_color(theme::text_muted())
408 .child(*title)
409 .into_any_element();
410 }
411 EmojiRow::Cells(glyphs) => glyphs,
412 };
413 let cells = row.iter().enumerate().map(|(column, glyph)| {
414 let picked = glyph.clone();
415 div()
416 .id(("fun-picker-emoji", index * EMOJI_COLUMNS + column))
417 .size(px(EMOJI_CELL))
418 .flex_none()
419 .flex()
420 .items_center()
421 .justify_center()
422 .rounded(px(6.))
423 .text_size(px(20.))
424 .cursor_pointer()
425 .hover(|cell| cell.bg(theme::border_strong()))
426 .child(glyph.clone())
427 .on_click(cx.listener(move |this, _, _, cx| this.pick_emoji(&picked, cx)))
428 });
429 h_flex()
430 .h(px(EMOJI_CELL + EMOJI_GAP))
431 .gap(px(EMOJI_GAP))
432 .children(cells)
433 .into_any_element()
434 }
435
436 fn render_emoji(&self, cx: &mut Context<Self>) -> AnyElement {
437 if self.emoji_rows.is_empty() {
438 return Self::message(format!("Keine Emojis zu \"{}\"", self.query)).into_any_element();
439 }
440 uniform_list(
441 "fun-picker-emoji-list",
442 self.emoji_rows.len(),
443 cx.processor(|this, range: std::ops::Range<usize>, _, cx| {
444 range
445 .map(|index| this.emoji_row(index, cx))
446 .collect::<Vec<_>>()
447 }),
448 )
449 .track_scroll(&self.emoji_scroll)
450 .size_full()
451 .into_any_element()
452 }
453
454 fn gif_tile(&self, gif: &Gif, index: usize, cx: &mut Context<Self>) -> AnyElement {
455 let picked = RemoteImage::gif(gif);
456 div()
457 .id(("fun-picker-gif", index))
458 .w(px(gif_tile_width()))
459 .h(px(gif_tile_height(gif)))
460 .flex_none()
461 .rounded(px(TILE_RADIUS))
462 .overflow_hidden()
463 .bg(theme::surface_raised())
464 .cursor_pointer()
465 .hover(|tile| tile.opacity(0.85))
466 .child(
467 img(image_source(&gif.preview_url))
468 .size_full()
469 .object_fit(ObjectFit::Cover),
470 )
471 .on_click(
472 cx.listener(move |this, _, window, cx| this.pick_image(picked.clone(), window, cx)),
473 )
474 .into_any_element()
475 }
476
477 fn gif_columns(columns: Vec<Vec<AnyElement>>) -> AnyElement {
478 h_flex()
479 .w_full()
480 .items_start()
481 .gap(px(GIF_GAP))
482 .children(
483 columns
484 .into_iter()
485 .map(|column| v_flex().gap(px(GIF_GAP)).children(column)),
486 )
487 .into_any_element()
488 }
489
490 fn render_gifs(&self, cx: &mut Context<Self>) -> AnyElement {
491 let body = match &self.gifs {
492 GifState::Loading => {
493 let layout = masonry(&GIF_PLACEHOLDER_HEIGHTS, GIF_COLUMNS);
494 Self::gif_columns(
495 layout
496 .into_iter()
497 .map(|column| {
498 column
499 .into_iter()
500 .map(|index| {
501 div()
502 .w(px(gif_tile_width()))
503 .h(px(GIF_PLACEHOLDER_HEIGHTS[index]))
504 .flex_none()
505 .rounded(px(TILE_RADIUS))
506 .bg(theme::surface_raised())
507 .into_any_element()
508 })
509 .collect()
510 })
511 .collect(),
512 )
513 }
514 GifState::Ready(found) if found.is_empty() => {
515 let text = if self.query.is_empty() {
516 "Keine GIFs gefunden".to_owned()
517 } else {
518 format!("Keine GIFs zu \"{}\"", self.query)
519 };
520 return Self::message(text).into_any_element();
521 }
522 GifState::Ready(found) => {
523 let heights: Vec<f32> = found.iter().map(gif_tile_height).collect();
524 let layout = masonry(&heights, GIF_COLUMNS);
525 Self::gif_columns(
526 layout
527 .into_iter()
528 .map(|column| {
529 column
530 .into_iter()
531 .map(|index| self.gif_tile(&found[index], index, cx))
532 .collect()
533 })
534 .collect(),
535 )
536 }
537 GifState::Failed => {
538 return Self::message("GIFs konnten nicht geladen werden.".to_owned())
539 .child(
540 div()
541 .id("fun-picker-gif-retry")
542 .h(px(28.))
543 .px(px(12.))
544 .flex()
545 .items_center()
546 .rounded(px(6.))
547 .border_1()
548 .border_color(theme::border_strong())
549 .text_color(theme::text())
550 .cursor_pointer()
551 .hover(|button| button.bg(theme::row_hover()))
552 .child("Erneut versuchen")
553 .on_click(cx.listener(|this, _, _, cx| this.refresh(false, cx))),
554 )
555 .into_any_element();
556 }
557 GifState::Disabled => {
558 return Self::message("GIFs sind in deiner Organisation deaktiviert.".to_owned())
559 .into_any_element();
560 }
561 };
562 div()
563 .id("fun-picker-gifs")
564 .size_full()
565 .overflow_y_scroll()
566 .child(body)
567 .into_any_element()
568 }
569
570 fn sticker_row(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
571 let size = sticker_tile_size();
572 let tiles = self.sticker_rows[index]
573 .iter()
574 .enumerate()
575 .map(|(column, sticker)| {
576 let picked = RemoteImage::sticker(sticker);
577 div()
578 .id(("fun-picker-sticker", index * STICKER_COLUMNS + column))
579 .size(px(size))
580 .flex_none()
581 .p(px(4.))
582 .rounded(px(TILE_RADIUS))
583 .bg(theme::surface_raised())
584 .cursor_pointer()
585 .hover(|tile| tile.bg(theme::border_strong()))
586 .child(
587 img(image_source(&sticker.url()))
588 .size_full()
589 .object_fit(ObjectFit::Contain),
590 )
591 .on_click(cx.listener(move |this, _, window, cx| {
592 this.pick_image(picked.clone(), window, cx)
593 }))
594 });
595 h_flex()
596 .h(px(size + STICKER_GAP))
597 .gap(px(STICKER_GAP))
598 .children(tiles)
599 .into_any_element()
600 }
601
602 fn chip_button(&self, chip: StickerChip, cx: &mut Context<Self>) -> Stateful<Div> {
603 let (label, id) = match chip {
604 StickerChip::Popular => (POPULAR_LABEL.to_owned(), "popular"),
605 StickerChip::Category(category) => (stickers::category_label(category), category),
606 };
607 let selected = self.query.is_empty() && chip == self.chip;
608 div()
609 .id(ElementId::Name(format!("fun-picker-chip-{id}").into()))
610 .h(px(26.))
611 .px(px(10.))
612 .flex_none()
613 .flex()
614 .items_center()
615 .rounded_full()
616 .cursor_pointer()
617 .text_size(px(12.))
618 .when(selected, |button| {
619 button
620 .bg(theme::accent_soft())
621 .text_color(theme::accent_text())
622 })
623 .when(!selected, |button| {
624 button
625 .bg(theme::surface_raised())
626 .text_color(theme::text_muted())
627 .hover(|button| button.text_color(theme::text_strong()))
628 })
629 .child(label)
630 .on_click(cx.listener(move |this, _, _, cx| this.select_chip(chip, cx)))
631 }
632
633 fn render_stickers(&self, cx: &mut Context<Self>) -> AnyElement {
634 let chips = std::iter::once(StickerChip::Popular)
635 .chain(
636 stickers::categories()
637 .into_iter()
638 .map(StickerChip::Category),
639 )
640 .map(|chip| self.chip_button(chip, cx))
641 .collect::<Vec<_>>();
642 let grid = if self.sticker_rows.is_empty() {
643 Self::message(format!("Keine Sticker zu \"{}\"", self.query)).into_any_element()
644 } else {
645 uniform_list(
646 "fun-picker-sticker-list",
647 self.sticker_rows.len(),
648 cx.processor(|this, range: std::ops::Range<usize>, _, cx| {
649 range
650 .map(|index| this.sticker_row(index, cx))
651 .collect::<Vec<_>>()
652 }),
653 )
654 .track_scroll(&self.sticker_scroll)
655 .size_full()
656 .into_any_element()
657 };
658 v_flex()
659 .size_full()
660 .gap(px(8.))
661 .child(
662 h_flex()
663 .id("fun-picker-chips")
664 .w_full()
665 .flex_none()
666 .gap(px(6.))
667 .overflow_x_scroll()
668 .children(chips),
669 )
670 .child(div().flex_1().min_h_0().child(grid))
671 .into_any_element()
672 }
673 }
674
675 impl Render for FunPicker {
676 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
677 let tabs = Tab::ALL.map(|tab| self.tab_button(tab, cx));
678 let body = match self.tab {
679 Tab::Emoji => self.render_emoji(cx),
680 Tab::Gif => self.render_gifs(cx),
681 Tab::Sticker => self.render_stickers(cx),
682 };
683 v_flex()
684 .w(px(WIDTH))
685 .h(px(HEIGHT))
686 .gap(px(8.))
687 .p(px(PADDING))
688 .child(h_flex().flex_none().gap(px(2.)).children(tabs))
689 .child(self.search_field())
690 .child(div().flex_1().min_h_0().child(body))
691 .when(self.tab == Tab::Gif, |picker| {
692 picker.child(
693 div()
694 .flex_none()
695 .flex()
696 .justify_end()
697 .text_size(px(10.5))
698 .text_color(theme::text_faint())
699 .child("Powered by GIPHY"),
700 )
701 })
702 }
703 }
704
705 #[cfg(test)]
706 mod tests {
707 use super::{EmojiRow, STICKER_COLUMNS, StickerChip, Tab, emoji_rows, masonry, sticker_rows};
708
709 #[test]
710 fn tabs_round_trip_through_their_keys() {
711 for tab in Tab::ALL {
712 assert_eq!(Tab::from_key(tab.key()), Some(tab));
713 }
714 assert_eq!(Tab::from_key("unknown"), None);
715 }
716
717 #[test]
718 fn masonry_fills_the_shortest_column() {
719 let layout = masonry(&[100., 50., 50., 50.], 2);
720 assert_eq!(layout, vec![vec![0, 3], vec![1, 2]]);
721 }
722
723 #[test]
724 fn emoji_rows_lead_with_recent_and_filter_by_query() {
725 let recent = vec!["\u{1F44D}".to_owned()];
726 let rows = emoji_rows("", &recent);
727 assert!(matches!(rows[0], EmojiRow::Header("Zuletzt verwendet")));
728 assert!(matches!(&rows[1], EmojiRow::Cells(cells) if cells == &recent));
729 let found = emoji_rows("thumbs", &recent);
730 assert!(!found.is_empty());
731 assert!(found.iter().all(|row| matches!(row, EmojiRow::Cells(_))));
732 }
733
734 #[test]
735 fn sticker_rows_hold_four_and_search_spans_categories() {
736 let popular = sticker_rows("", StickerChip::Popular);
737 assert_eq!(popular.len(), 2);
738 assert_eq!(popular[0].len(), STICKER_COLUMNS);
739 let found = sticker_rows("coffee", StickerChip::Category("Clippy"));
740 assert!(
741 found
742 .iter()
743 .flatten()
744 .any(|sticker| sticker.id == "Octocorn_Coffee")
745 );
746 }
747 }
@@ -0,0 +1,747 @@
1use std::time::Duration;
2
3use gpui_kit::base::PopoverState;
4use gpui_kit::component::{
5 h_flex,
6 input::{Input, InputEvent, InputState},
7 v_flex,
8};
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
11use teams_core::Gif;
12
13use crate::app_state::AppState;
14use crate::emoji;
15use crate::gifs::{self, GifError};
16use crate::remote_image::{RemoteImage, image_source};
17use crate::stickers::{self, Sticker};
18use crate::theme;
19
20const TAB_KEY: &str = "fun_picker_tab";
21const WIDTH: f32 = 360.;
22const HEIGHT: f32 = 380.;
23const PADDING: f32 = 8.;
24const CONTENT_WIDTH: f32 = WIDTH - 2. * PADDING;
25const EMOJI_COLUMNS: usize = 8;
26const EMOJI_CELL: f32 = 32.;
27const EMOJI_GAP: f32 = 2.;
28const EMOJI_SEARCH_LIMIT: usize = 240;
29const GIF_COLUMNS: usize = 3;
30const GIF_GAP: f32 = 6.;
31const GIF_DEBOUNCE: Duration = Duration::from_millis(300);
32const GIF_MIN_HEIGHT: f32 = 48.;
33const GIF_MAX_HEIGHT: f32 = 200.;
34const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];
35const STICKER_COLUMNS: usize = 4;
36const STICKER_GAP: f32 = 6.;
37const POPULAR_LABEL: &str = "Beliebt";
38const TILE_RADIUS: f32 = 6.;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41enum Tab {
42 Emoji,
43 Gif,
44 Sticker,
45}
46
47impl Tab {
48 const ALL: [Tab; 3] = [Tab::Emoji, Tab::Gif, Tab::Sticker];
49
50 fn key(self) -> &'static str {
51 match self {
52 Tab::Emoji => "emoji",
53 Tab::Gif => "gif",
54 Tab::Sticker => "sticker",
55 }
56 }
57
58 fn from_key(key: &str) -> Option<Tab> {
59 Tab::ALL.into_iter().find(|tab| tab.key() == key)
60 }
61
62 fn label(self) -> &'static str {
63 match self {
64 Tab::Emoji => "Emoji",
65 Tab::Gif => "GIF",
66 Tab::Sticker => "Sticker",
67 }
68 }
69
70 fn placeholder(self) -> &'static str {
71 match self {
72 Tab::Emoji => "Emoji suchen",
73 Tab::Gif => "GIFs suchen",
74 Tab::Sticker => "Sticker suchen",
75 }
76 }
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80enum StickerChip {
81 Popular,
82 Category(&'static str),
83}
84
85enum GifState {
86 Loading,
87 Ready(Vec<Gif>),
88 Failed,
89 Disabled,
90}
91
92enum EmojiRow {
93 Header(&'static str),
94 Cells(Vec<String>),
95}
96
97pub enum FunPickerEvent {
98 Emoji(String),
99 Image(RemoteImage),
100}
101
102pub struct FunPicker {
103 app: Entity<AppState>,
104 input: Entity<InputState>,
105 tab: Tab,
106 query: String,
107 recent: emoji::Recent,
108 popover: Option<WeakEntity<PopoverState>>,
109 emoji_rows: Vec<EmojiRow>,
110 emoji_scroll: UniformListScrollHandle,
111 gifs: GifState,
112 gif_generation: u64,
113 gif_task: Option<Task<()>>,
114 chip: StickerChip,
115 sticker_rows: Vec<Vec<&'static Sticker>>,
116 sticker_scroll: UniformListScrollHandle,
117 _subscription: Subscription,
118}
119
120impl EventEmitter<FunPickerEvent> for FunPicker {}
121
122fn emoji_rows(query: &str, recent: &[String]) -> Vec<EmojiRow> {
123 let chunked = |glyphs: Vec<String>| -> Vec<EmojiRow> {
124 glyphs
125 .chunks(EMOJI_COLUMNS)
126 .map(|chunk| EmojiRow::Cells(chunk.to_vec()))
127 .collect()
128 };
129 if !query.is_empty() {
130 let found = emoji::search(query, recent, EMOJI_SEARCH_LIMIT)
131 .into_iter()
132 .map(|found| found.glyph.to_owned())
133 .collect();
134 return chunked(found);
135 }
136 let mut rows = Vec::new();
137 if !recent.is_empty() {
138 rows.push(EmojiRow::Header("Zuletzt verwendet"));
139 rows.extend(chunked(recent.to_vec()));
140 }
141 rows.push(EmojiRow::Header("Alle Emojis"));
142 rows.extend(chunked(emoji::glyphs().map(str::to_owned).collect()));
143 rows
144}
145
146fn sticker_rows(query: &str, chip: StickerChip) -> Vec<Vec<&'static Sticker>> {
147 let stickers = if !query.is_empty() {
148 stickers::search(query)
149 } else {
150 match chip {
151 StickerChip::Popular => stickers::popular(),
152 StickerChip::Category(category) => stickers::in_category(category),
153 }
154 };
155 stickers
156 .chunks(STICKER_COLUMNS)
157 .map(<[&Sticker]>::to_vec)
158 .collect()
159}
160
161/// Indices per column; each item goes to the currently shortest column.
162fn masonry(heights: &[f32], columns: usize) -> Vec<Vec<usize>> {
163 let mut layout: Vec<Vec<usize>> = vec![Vec::new(); columns];
164 let mut totals = vec![0_f32; columns];
165 for (index, height) in heights.iter().enumerate() {
166 let shortest = totals
167 .iter()
168 .enumerate()
169 .min_by(|left, right| left.1.total_cmp(right.1))
170 .map_or(0, |(column, _)| column);
171 layout[shortest].push(index);
172 totals[shortest] += height + GIF_GAP;
173 }
174 layout
175}
176
177fn gif_tile_width() -> f32 {
178 (CONTENT_WIDTH - GIF_GAP * (GIF_COLUMNS - 1) as f32) / GIF_COLUMNS as f32
179}
180
181fn gif_tile_height(gif: &Gif) -> f32 {
182 let ratio = gif.preview_height as f32 / gif.preview_width.max(1) as f32;
183 (gif_tile_width() * ratio).clamp(GIF_MIN_HEIGHT, GIF_MAX_HEIGHT)
184}
185
186fn sticker_tile_size() -> f32 {
187 (CONTENT_WIDTH - STICKER_GAP * (STICKER_COLUMNS - 1) as f32) / STICKER_COLUMNS as f32
188}
189
190impl FunPicker {
191 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
192 let input = cx.new(|cx| InputState::new(window, cx).placeholder(Tab::Emoji.placeholder()));
193 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
194 let recent = emoji::Recent::load(&app.read(cx).store);
195 FunPicker {
196 app,
197 input,
198 tab: Tab::Emoji,
199 query: String::new(),
200 emoji_rows: emoji_rows("", &recent.glyphs()),
201 recent,
202 popover: None,
203 emoji_scroll: UniformListScrollHandle::new(),
204 gifs: GifState::Loading,
205 gif_generation: 0,
206 gif_task: None,
207 chip: StickerChip::Popular,
208 sticker_rows: sticker_rows("", StickerChip::Popular),
209 sticker_scroll: UniformListScrollHandle::new(),
210 _subscription: subscription,
211 }
212 }
213
214 pub fn set_popover(&mut self, popover: WeakEntity<PopoverState>) {
215 self.popover = Some(popover);
216 }
217
218 pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
219 let store = self.app.read(cx).store.clone();
220 self.recent.reload(&store);
221 self.tab = store
222 .meta(TAB_KEY)
223 .ok()
224 .flatten()
225 .and_then(|key| Tab::from_key(&key))
226 .unwrap_or(Tab::Emoji);
227 self.show_tab(window, cx);
228 }
229
230 fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
231 if tab == self.tab {
232 return;
233 }
234 self.tab = tab;
235 let _ = self.app.read(cx).store.set_meta(TAB_KEY, tab.key());
236 self.show_tab(window, cx);
237 }
238
239 fn show_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
240 self.query.clear();
241 let placeholder = self.tab.placeholder();
242 self.input.update(cx, |state, cx| {
243 state.set_value("", window, cx);
244 state.set_placeholder(placeholder, window, cx);
245 state.focus(window, cx);
246 });
247 self.refresh(false, cx);
248 }
249
250 fn refresh(&mut self, debounce: bool, cx: &mut Context<Self>) {
251 match self.tab {
252 Tab::Emoji => {
253 self.emoji_rows = emoji_rows(&self.query, &self.recent.glyphs());
254 self.emoji_scroll.scroll_to_item(0, ScrollStrategy::Top);
255 }
256 Tab::Gif => self.search_gifs(debounce, cx),
257 Tab::Sticker => {
258 self.sticker_rows = sticker_rows(&self.query, self.chip);
259 self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top);
260 }
261 }
262 cx.notify();
263 }
264
265 fn on_input_event(
266 &mut self,
267 input: &Entity<InputState>,
268 event: &InputEvent,
269 _: &mut Window,
270 cx: &mut Context<Self>,
271 ) {
272 match event {
273 InputEvent::Change => {
274 let query = input.read(cx).value().trim().to_owned();
275 if query != self.query {
276 self.query = query;
277 self.refresh(true, cx);
278 }
279 }
280 InputEvent::PressEnter { .. } if self.tab == Tab::Emoji => {
281 let first = self.emoji_rows.iter().find_map(|row| match row {
282 EmojiRow::Cells(glyphs) => glyphs.first().cloned(),
283 EmojiRow::Header(_) => None,
284 });
285 if let Some(glyph) = first.filter(|_| !self.query.is_empty()) {
286 self.pick_emoji(&glyph, cx);
287 }
288 }
289 _ => {}
290 }
291 }
292
293 fn search_gifs(&mut self, debounce: bool, cx: &mut Context<Self>) {
294 self.gif_generation += 1;
295 let generation = self.gif_generation;
296 self.gifs = GifState::Loading;
297 let query = self.query.clone();
298 let (demo, engine) = {
299 let state = self.app.read(cx);
300 (state.mode.demo, state.engine.clone())
301 };
302 self.gif_task = Some(cx.spawn(async move |this, cx| {
303 if debounce {
304 cx.background_executor().timer(GIF_DEBOUNCE).await;
305 }
306 let outcome = gifs::search(engine, demo, query)
307 .await
308 .unwrap_or(Err(GifError::Failed));
309 this.update(cx, |this, cx| {
310 if this.gif_generation != generation {
311 return;
312 }
313 this.gifs = match outcome {
314 Ok(found) => GifState::Ready(found),
315 Err(GifError::Disabled) => GifState::Disabled,
316 Err(GifError::Failed) => GifState::Failed,
317 };
318 cx.notify();
319 })
320 .ok();
321 }));
322 }
323
324 fn pick_emoji(&mut self, glyph: &str, cx: &mut Context<Self>) {
325 self.recent.push(glyph);
326 self.refresh(false, cx);
327 cx.emit(FunPickerEvent::Emoji(glyph.to_owned()));
328 }
329
330 fn pick_image(&mut self, image: RemoteImage, window: &mut Window, cx: &mut Context<Self>) {
331 if let Some(popover) = &self.popover {
332 popover
333 .update(cx, |state, cx| state.dismiss(window, cx))
334 .ok();
335 }
336 cx.emit(FunPickerEvent::Image(image));
337 }
338
339 fn select_chip(&mut self, chip: StickerChip, cx: &mut Context<Self>) {
340 self.chip = chip;
341 self.refresh(false, cx);
342 }
343
344 fn tab_button(&self, tab: Tab, cx: &mut Context<Self>) -> Stateful<Div> {
345 let selected = tab == self.tab;
346 div()
347 .id(("fun-picker-tab", tab as usize))
348 .h(px(32.))
349 .px(px(14.))
350 .flex()
351 .items_center()
352 .cursor_pointer()
353 .text_size(px(13.))
354 .font_weight(FontWeight::SEMIBOLD)
355 .border_b_2()
356 .border_color(if selected {
357 theme::accent()
358 } else {
359 transparent_black()
360 })
361 .text_color(if selected {
362 theme::accent_text()
363 } else {
364 theme::text_muted()
365 })
366 .hover(|button| button.text_color(theme::text_strong()))
367 .child(tab.label())
368 .on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
369 }
370
371 fn search_field(&self) -> Div {
372 div()
373 .h(px(32.))
374 .px(px(8.))
375 .flex()
376 .flex_none()
377 .items_center()
378 .rounded(px(8.))
379 .bg(theme::surface())
380 .border_1()
381 .border_color(theme::border_strong())
382 .child(Input::new(&self.input).appearance(false).bordered(false))
383 }
384
385 fn message(text: String) -> Div {
386 div()
387 .size_full()
388 .flex()
389 .flex_col()
390 .gap(px(8.))
391 .items_center()
392 .justify_center()
393 .text_size(px(12.5))
394 .text_color(theme::text_muted())
395 .child(text)
396 }
397
398 fn emoji_row(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
399 let row = match &self.emoji_rows[index] {
400 EmojiRow::Header(title) => {
401 return div()
402 .h(px(EMOJI_CELL + EMOJI_GAP))
403 .flex()
404 .items_end()
405 .pb(px(4.))
406 .text_size(px(11.))
407 .text_color(theme::text_muted())
408 .child(*title)
409 .into_any_element();
410 }
411 EmojiRow::Cells(glyphs) => glyphs,
412 };
413 let cells = row.iter().enumerate().map(|(column, glyph)| {
414 let picked = glyph.clone();
415 div()
416 .id(("fun-picker-emoji", index * EMOJI_COLUMNS + column))
417 .size(px(EMOJI_CELL))
418 .flex_none()
419 .flex()
420 .items_center()
421 .justify_center()
422 .rounded(px(6.))
423 .text_size(px(20.))
424 .cursor_pointer()
425 .hover(|cell| cell.bg(theme::border_strong()))
426 .child(glyph.clone())
427 .on_click(cx.listener(move |this, _, _, cx| this.pick_emoji(&picked, cx)))
428 });
429 h_flex()
430 .h(px(EMOJI_CELL + EMOJI_GAP))
431 .gap(px(EMOJI_GAP))
432 .children(cells)
433 .into_any_element()
434 }
435
436 fn render_emoji(&self, cx: &mut Context<Self>) -> AnyElement {
437 if self.emoji_rows.is_empty() {
438 return Self::message(format!("Keine Emojis zu \"{}\"", self.query)).into_any_element();
439 }
440 uniform_list(
441 "fun-picker-emoji-list",
442 self.emoji_rows.len(),
443 cx.processor(|this, range: std::ops::Range<usize>, _, cx| {
444 range
445 .map(|index| this.emoji_row(index, cx))
446 .collect::<Vec<_>>()
447 }),
448 )
449 .track_scroll(&self.emoji_scroll)
450 .size_full()
451 .into_any_element()
452 }
453
454 fn gif_tile(&self, gif: &Gif, index: usize, cx: &mut Context<Self>) -> AnyElement {
455 let picked = RemoteImage::gif(gif);
456 div()
457 .id(("fun-picker-gif", index))
458 .w(px(gif_tile_width()))
459 .h(px(gif_tile_height(gif)))
460 .flex_none()
461 .rounded(px(TILE_RADIUS))
462 .overflow_hidden()
463 .bg(theme::surface_raised())
464 .cursor_pointer()
465 .hover(|tile| tile.opacity(0.85))
466 .child(
467 img(image_source(&gif.preview_url))
468 .size_full()
469 .object_fit(ObjectFit::Cover),
470 )
471 .on_click(
472 cx.listener(move |this, _, window, cx| this.pick_image(picked.clone(), window, cx)),
473 )
474 .into_any_element()
475 }
476
477 fn gif_columns(columns: Vec<Vec<AnyElement>>) -> AnyElement {
478 h_flex()
479 .w_full()
480 .items_start()
481 .gap(px(GIF_GAP))
482 .children(
483 columns
484 .into_iter()
485 .map(|column| v_flex().gap(px(GIF_GAP)).children(column)),
486 )
487 .into_any_element()
488 }
489
490 fn render_gifs(&self, cx: &mut Context<Self>) -> AnyElement {
491 let body = match &self.gifs {
492 GifState::Loading => {
493 let layout = masonry(&GIF_PLACEHOLDER_HEIGHTS, GIF_COLUMNS);
494 Self::gif_columns(
495 layout
496 .into_iter()
497 .map(|column| {
498 column
499 .into_iter()
500 .map(|index| {
501 div()
502 .w(px(gif_tile_width()))
503 .h(px(GIF_PLACEHOLDER_HEIGHTS[index]))
504 .flex_none()
505 .rounded(px(TILE_RADIUS))
506 .bg(theme::surface_raised())
507 .into_any_element()
508 })
509 .collect()
510 })
511 .collect(),
512 )
513 }
514 GifState::Ready(found) if found.is_empty() => {
515 let text = if self.query.is_empty() {
516 "Keine GIFs gefunden".to_owned()
517 } else {
518 format!("Keine GIFs zu \"{}\"", self.query)
519 };
520 return Self::message(text).into_any_element();
521 }
522 GifState::Ready(found) => {
523 let heights: Vec<f32> = found.iter().map(gif_tile_height).collect();
524 let layout = masonry(&heights, GIF_COLUMNS);
525 Self::gif_columns(
526 layout
527 .into_iter()
528 .map(|column| {
529 column
530 .into_iter()
531 .map(|index| self.gif_tile(&found[index], index, cx))
532 .collect()
533 })
534 .collect(),
535 )
536 }
537 GifState::Failed => {
538 return Self::message("GIFs konnten nicht geladen werden.".to_owned())
539 .child(
540 div()
541 .id("fun-picker-gif-retry")
542 .h(px(28.))
543 .px(px(12.))
544 .flex()
545 .items_center()
546 .rounded(px(6.))
547 .border_1()
548 .border_color(theme::border_strong())
549 .text_color(theme::text())
550 .cursor_pointer()
551 .hover(|button| button.bg(theme::row_hover()))
552 .child("Erneut versuchen")
553 .on_click(cx.listener(|this, _, _, cx| this.refresh(false, cx))),
554 )
555 .into_any_element();
556 }
557 GifState::Disabled => {
558 return Self::message("GIFs sind in deiner Organisation deaktiviert.".to_owned())
559 .into_any_element();
560 }
561 };
562 div()
563 .id("fun-picker-gifs")
564 .size_full()
565 .overflow_y_scroll()
566 .child(body)
567 .into_any_element()
568 }
569
570 fn sticker_row(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
571 let size = sticker_tile_size();
572 let tiles = self.sticker_rows[index]
573 .iter()
574 .enumerate()
575 .map(|(column, sticker)| {
576 let picked = RemoteImage::sticker(sticker);
577 div()
578 .id(("fun-picker-sticker", index * STICKER_COLUMNS + column))
579 .size(px(size))
580 .flex_none()
581 .p(px(4.))
582 .rounded(px(TILE_RADIUS))
583 .bg(theme::surface_raised())
584 .cursor_pointer()
585 .hover(|tile| tile.bg(theme::border_strong()))
586 .child(
587 img(image_source(&sticker.url()))
588 .size_full()
589 .object_fit(ObjectFit::Contain),
590 )
591 .on_click(cx.listener(move |this, _, window, cx| {
592 this.pick_image(picked.clone(), window, cx)
593 }))
594 });
595 h_flex()
596 .h(px(size + STICKER_GAP))
597 .gap(px(STICKER_GAP))
598 .children(tiles)
599 .into_any_element()
600 }
601
602 fn chip_button(&self, chip: StickerChip, cx: &mut Context<Self>) -> Stateful<Div> {
603 let (label, id) = match chip {
604 StickerChip::Popular => (POPULAR_LABEL.to_owned(), "popular"),
605 StickerChip::Category(category) => (stickers::category_label(category), category),
606 };
607 let selected = self.query.is_empty() && chip == self.chip;
608 div()
609 .id(ElementId::Name(format!("fun-picker-chip-{id}").into()))
610 .h(px(26.))
611 .px(px(10.))
612 .flex_none()
613 .flex()
614 .items_center()
615 .rounded_full()
616 .cursor_pointer()
617 .text_size(px(12.))
618 .when(selected, |button| {
619 button
620 .bg(theme::accent_soft())
621 .text_color(theme::accent_text())
622 })
623 .when(!selected, |button| {
624 button
625 .bg(theme::surface_raised())
626 .text_color(theme::text_muted())
627 .hover(|button| button.text_color(theme::text_strong()))
628 })
629 .child(label)
630 .on_click(cx.listener(move |this, _, _, cx| this.select_chip(chip, cx)))
631 }
632
633 fn render_stickers(&self, cx: &mut Context<Self>) -> AnyElement {
634 let chips = std::iter::once(StickerChip::Popular)
635 .chain(
636 stickers::categories()
637 .into_iter()
638 .map(StickerChip::Category),
639 )
640 .map(|chip| self.chip_button(chip, cx))
641 .collect::<Vec<_>>();
642 let grid = if self.sticker_rows.is_empty() {
643 Self::message(format!("Keine Sticker zu \"{}\"", self.query)).into_any_element()
644 } else {
645 uniform_list(
646 "fun-picker-sticker-list",
647 self.sticker_rows.len(),
648 cx.processor(|this, range: std::ops::Range<usize>, _, cx| {
649 range
650 .map(|index| this.sticker_row(index, cx))
651 .collect::<Vec<_>>()
652 }),
653 )
654 .track_scroll(&self.sticker_scroll)
655 .size_full()
656 .into_any_element()
657 };
658 v_flex()
659 .size_full()
660 .gap(px(8.))
661 .child(
662 h_flex()
663 .id("fun-picker-chips")
664 .w_full()
665 .flex_none()
666 .gap(px(6.))
667 .overflow_x_scroll()
668 .children(chips),
669 )
670 .child(div().flex_1().min_h_0().child(grid))
671 .into_any_element()
672 }
673}
674
675impl Render for FunPicker {
676 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
677 let tabs = Tab::ALL.map(|tab| self.tab_button(tab, cx));
678 let body = match self.tab {
679 Tab::Emoji => self.render_emoji(cx),
680 Tab::Gif => self.render_gifs(cx),
681 Tab::Sticker => self.render_stickers(cx),
682 };
683 v_flex()
684 .w(px(WIDTH))
685 .h(px(HEIGHT))
686 .gap(px(8.))
687 .p(px(PADDING))
688 .child(h_flex().flex_none().gap(px(2.)).children(tabs))
689 .child(self.search_field())
690 .child(div().flex_1().min_h_0().child(body))
691 .when(self.tab == Tab::Gif, |picker| {
692 picker.child(
693 div()
694 .flex_none()
695 .flex()
696 .justify_end()
697 .text_size(px(10.5))
698 .text_color(theme::text_faint())
699 .child("Powered by GIPHY"),
700 )
701 })
702 }
703}
704
705#[cfg(test)]
706mod tests {
707 use super::{EmojiRow, STICKER_COLUMNS, StickerChip, Tab, emoji_rows, masonry, sticker_rows};
708
709 #[test]
710 fn tabs_round_trip_through_their_keys() {
711 for tab in Tab::ALL {
712 assert_eq!(Tab::from_key(tab.key()), Some(tab));
713 }
714 assert_eq!(Tab::from_key("unknown"), None);
715 }
716
717 #[test]
718 fn masonry_fills_the_shortest_column() {
719 let layout = masonry(&[100., 50., 50., 50.], 2);
720 assert_eq!(layout, vec![vec![0, 3], vec![1, 2]]);
721 }
722
723 #[test]
724 fn emoji_rows_lead_with_recent_and_filter_by_query() {
725 let recent = vec!["\u{1F44D}".to_owned()];
726 let rows = emoji_rows("", &recent);
727 assert!(matches!(rows[0], EmojiRow::Header("Zuletzt verwendet")));
728 assert!(matches!(&rows[1], EmojiRow::Cells(cells) if cells == &recent));
729 let found = emoji_rows("thumbs", &recent);
730 assert!(!found.is_empty());
731 assert!(found.iter().all(|row| matches!(row, EmojiRow::Cells(_))));
732 }
733
734 #[test]
735 fn sticker_rows_hold_four_and_search_spans_categories() {
736 let popular = sticker_rows("", StickerChip::Popular);
737 assert_eq!(popular.len(), 2);
738 assert_eq!(popular[0].len(), STICKER_COLUMNS);
739 let found = sticker_rows("coffee", StickerChip::Category("Clippy"));
740 assert!(
741 found
742 .iter()
743 .flatten()
744 .any(|sticker| sticker.id == "Octocorn_Coffee")
745 );
746 }
747}
crates/app/src/views/mod.rs +1 −0
@@ -11,6 +11,7 @@ pub mod draft_style;
11 11 pub mod emoji_popup;
12 12 pub mod format_toolbar;
13 13 pub mod link_preview;
14 pub mod fun_picker;
14 15 pub mod message_actions;
15 16 pub mod message_row;
16 17 pub mod new_chat;
@@ -11,6 +11,7 @@ pub mod draft_style;
11pub mod emoji_popup;
11pub mod emoji_popup;
12pub mod format_toolbar;
12pub mod format_toolbar;
13pub mod link_preview;
13pub mod link_preview;
14pub mod fun_picker;
14pub mod message_actions;
15pub mod message_actions;
15pub mod message_row;
16pub mod message_row;
16pub mod new_chat;
17pub mod new_chat;
crates/chatsvc/src/error.rs +2 −0
@@ -12,6 +12,8 @@ pub enum Error {
12 12 UnknownFolder(String),
13 13 #[error("pin list changed twice while writing, giving up")]
14 14 VersionConflict,
15 #[error("GIFs are disabled by the organization")]
16 GifsDisabled,
15 17 #[error("invalid event payload: {0}")]
16 18 Decode(String),
17 19 }
@@ -12,6 +12,8 @@ pub enum Error {
12 UnknownFolder(String),
12 UnknownFolder(String),
13 #[error("pin list changed twice while writing, giving up")]
13 #[error("pin list changed twice while writing, giving up")]
14 VersionConflict,
14 VersionConflict,
15 #[error("GIFs are disabled by the organization")]
16 GifsDisabled,
15 #[error("invalid event payload: {0}")]
17 #[error("invalid event payload: {0}")]
16 Decode(String),
18 Decode(String),
17}
19}
crates/chatsvc/src/gifs.rs added +205 −0
@@ -0,0 +1,205 @@
1 use serde_json::{Value, json};
2 use session::{ApiResponse, Method, Request, Session};
3
4 use crate::cards::{CardTransport, DEFAULT_MT_REGION, SessionCardTransport, spaces_scope};
5 use crate::error::{Error, Result};
6
7 const FORBIDDEN_STATUS: u16 = 403;
8 const RESULT_LIMIT: &str = "27";
9 const RATING: &str = "g";
10 const LANGUAGE: &str = "de-de";
11
12 #[derive(Debug, Clone, PartialEq, Eq)]
13 pub struct Gif {
14 pub url: String,
15 pub preview_url: String,
16 pub title: String,
17 pub width: u32,
18 pub height: u32,
19 pub preview_width: u32,
20 pub preview_height: u32,
21 }
22
23 pub struct Gifs<T: CardTransport = SessionCardTransport> {
24 transport: T,
25 url: String,
26 }
27
28 impl Gifs<SessionCardTransport> {
29 pub fn new(session: &Session) -> Self {
30 Gifs::with_transport(SessionCardTransport::new(session), DEFAULT_MT_REGION)
31 }
32 }
33
34 impl<T: CardTransport> Gifs<T> {
35 pub fn with_transport(transport: T, mt_region: &str) -> Self {
36 Gifs {
37 transport,
38 url: format!(
39 "https://teams.cloud.microsoft/api/mt/{mt_region}/beta/commands/com.microsoft.teamspace.inputextension.giphy/execute?version=1.0"
40 ),
41 }
42 }
43
44 /// An empty query returns the trending GIFs.
45 pub async fn search(&self, query: &str) -> Result<Vec<Gif>> {
46 let mut request = Request::with_body(Method::Post, &self.url, search_body(query));
47 request.headers = vec![(
48 "content-type".to_owned(),
49 "application/json;charset=UTF-8".to_owned(),
50 )];
51 let answer = self.transport.send(request, spaces_scope()).await?;
52 parse_answer(answer, &self.url)
53 }
54 }
55
56 fn search_body(query: &str) -> Value {
57 json!([
58 {"name": "query", "value": query},
59 {"name": "rating", "value": RATING},
60 {"name": "limit", "value": RESULT_LIMIT},
61 {"name": "lang", "value": LANGUAGE},
62 ])
63 }
64
65 fn parse_answer(answer: ApiResponse, url: &str) -> Result<Vec<Gif>> {
66 if answer.status == FORBIDDEN_STATUS {
67 return Err(Error::GifsDisabled);
68 }
69 if !answer.is_success() {
70 return Err(Error::Session(session::Error::api(
71 answer.status,
72 url,
73 answer.body,
74 )));
75 }
76 Ok(parse_gifs(&answer.body))
77 }
78
79 pub fn parse_gifs(body: &Value) -> Vec<Gif> {
80 body.pointer("/result/0/result")
81 .and_then(Value::as_array)
82 .into_iter()
83 .flatten()
84 .filter_map(parse_gif)
85 .collect()
86 }
87
88 fn parse_gif(entry: &Value) -> Option<Gif> {
89 let field = |name: &str| {
90 entry
91 .get("fieldValues")?
92 .as_array()?
93 .iter()
94 .find(|field| field.get("fieldName").and_then(Value::as_str) == Some(name))?
95 .get("fieldValue")?
96 .as_str()
97 };
98 let number = |name: &str| field(name)?.parse::<u32>().ok().filter(|size| *size > 0);
99 let url = entry.get("composeValue")?.as_str()?.to_owned();
100 Some(Gif {
101 preview_url: field("previewImageFW")
102 .or_else(|| field("previewImage"))
103 .map_or_else(|| url.clone(), str::to_owned),
104 title: field("title").unwrap_or_default().to_owned(),
105 width: number("width")?,
106 height: number("height")?,
107 preview_width: number("previewImageFWWidth").unwrap_or(1),
108 preview_height: number("previewImageFWHeight").unwrap_or(1),
109 url,
110 })
111 }
112
113 #[cfg(test)]
114 mod tests {
115 use std::sync::Mutex;
116
117 use session::Scope;
118
119 use super::*;
120
121 struct Canned {
122 status: u16,
123 body: Value,
124 sent: Mutex<Vec<(Request, Scope)>>,
125 }
126
127 impl CardTransport for Canned {
128 async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {
129 self.sent.lock().unwrap().push((request, scope));
130 Ok(ApiResponse {
131 status: self.status,
132 body: self.body.clone(),
133 retry_after: None,
134 })
135 }
136 }
137
138 fn gifs(status: u16, body: Value) -> Gifs<Canned> {
139 Gifs::with_transport(
140 Canned {
141 status,
142 body,
143 sent: Mutex::new(Vec::new()),
144 },
145 "emea",
146 )
147 }
148
149 fn fixture() -> Value {
150 serde_json::from_str(include_str!("../tests/fixtures/giphy_search.json")).unwrap()
151 }
152
153 #[tokio::test]
154 async fn search_posts_the_query_to_the_giphy_command() {
155 let gifs = gifs(200, fixture());
156 gifs.search("thumbs up").await.unwrap();
157 let sent = gifs.transport.sent.lock().unwrap();
158 let (request, scope) = &sent[0];
159 assert_eq!(request.method, Method::Post);
160 assert_eq!(
161 request.url,
162 "https://teams.cloud.microsoft/api/mt/emea/beta/commands/com.microsoft.teamspace.inputextension.giphy/execute?version=1.0"
163 );
164 assert_eq!(request.body.as_ref().unwrap()[0]["value"], "thumbs up");
165 assert_eq!(request.body.as_ref().unwrap()[2]["value"], "27");
166 assert_eq!(*scope, spaces_scope());
167 }
168
169 #[tokio::test]
170 async fn results_carry_urls_titles_and_sizes() {
171 let found = gifs(200, fixture()).search("x").await.unwrap();
172 assert_eq!(found.len(), 2);
173 assert_eq!(found[0].title, "Baby Thank You GIF");
174 assert!(found[0].url.ends_with("/giphy.gif"));
175 assert!(found[0].preview_url.ends_with("/200w.gif"));
176 assert_eq!((found[0].width, found[0].height), (358, 360));
177 assert_eq!(
178 (found[0].preview_width, found[0].preview_height),
179 (200, 202)
180 );
181 }
182
183 #[tokio::test]
184 async fn forbidden_means_disabled() {
185 let outcome = gifs(403, json!({"errorCode": "Forbidden"}))
186 .search("")
187 .await;
188 assert!(matches!(outcome, Err(Error::GifsDisabled)));
189 }
190
191 #[tokio::test]
192 async fn other_failures_are_api_errors() {
193 let outcome = gifs(500, Value::Null).search("").await;
194 assert!(matches!(
195 outcome,
196 Err(Error::Session(session::Error::Api { status: 500, .. }))
197 ));
198 }
199
200 #[test]
201 fn entries_without_a_size_are_skipped() {
202 let body = json!({"result": [{"result": [{"composeValue": "https://media0.giphy.com/a.gif", "fieldValues": []}]}]});
203 assert!(parse_gifs(&body).is_empty());
204 }
205 }
@@ -0,0 +1,205 @@
1use serde_json::{Value, json};
2use session::{ApiResponse, Method, Request, Session};
3
4use crate::cards::{CardTransport, DEFAULT_MT_REGION, SessionCardTransport, spaces_scope};
5use crate::error::{Error, Result};
6
7const FORBIDDEN_STATUS: u16 = 403;
8const RESULT_LIMIT: &str = "27";
9const RATING: &str = "g";
10const LANGUAGE: &str = "de-de";
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Gif {
14 pub url: String,
15 pub preview_url: String,
16 pub title: String,
17 pub width: u32,
18 pub height: u32,
19 pub preview_width: u32,
20 pub preview_height: u32,
21}
22
23pub struct Gifs<T: CardTransport = SessionCardTransport> {
24 transport: T,
25 url: String,
26}
27
28impl Gifs<SessionCardTransport> {
29 pub fn new(session: &Session) -> Self {
30 Gifs::with_transport(SessionCardTransport::new(session), DEFAULT_MT_REGION)
31 }
32}
33
34impl<T: CardTransport> Gifs<T> {
35 pub fn with_transport(transport: T, mt_region: &str) -> Self {
36 Gifs {
37 transport,
38 url: format!(
39 "https://teams.cloud.microsoft/api/mt/{mt_region}/beta/commands/com.microsoft.teamspace.inputextension.giphy/execute?version=1.0"
40 ),
41 }
42 }
43
44 /// An empty query returns the trending GIFs.
45 pub async fn search(&self, query: &str) -> Result<Vec<Gif>> {
46 let mut request = Request::with_body(Method::Post, &self.url, search_body(query));
47 request.headers = vec![(
48 "content-type".to_owned(),
49 "application/json;charset=UTF-8".to_owned(),
50 )];
51 let answer = self.transport.send(request, spaces_scope()).await?;
52 parse_answer(answer, &self.url)
53 }
54}
55
56fn search_body(query: &str) -> Value {
57 json!([
58 {"name": "query", "value": query},
59 {"name": "rating", "value": RATING},
60 {"name": "limit", "value": RESULT_LIMIT},
61 {"name": "lang", "value": LANGUAGE},
62 ])
63}
64
65fn parse_answer(answer: ApiResponse, url: &str) -> Result<Vec<Gif>> {
66 if answer.status == FORBIDDEN_STATUS {
67 return Err(Error::GifsDisabled);
68 }
69 if !answer.is_success() {
70 return Err(Error::Session(session::Error::api(
71 answer.status,
72 url,
73 answer.body,
74 )));
75 }
76 Ok(parse_gifs(&answer.body))
77}
78
79pub fn parse_gifs(body: &Value) -> Vec<Gif> {
80 body.pointer("/result/0/result")
81 .and_then(Value::as_array)
82 .into_iter()
83 .flatten()
84 .filter_map(parse_gif)
85 .collect()
86}
87
88fn parse_gif(entry: &Value) -> Option<Gif> {
89 let field = |name: &str| {
90 entry
91 .get("fieldValues")?
92 .as_array()?
93 .iter()
94 .find(|field| field.get("fieldName").and_then(Value::as_str) == Some(name))?
95 .get("fieldValue")?
96 .as_str()
97 };
98 let number = |name: &str| field(name)?.parse::<u32>().ok().filter(|size| *size > 0);
99 let url = entry.get("composeValue")?.as_str()?.to_owned();
100 Some(Gif {
101 preview_url: field("previewImageFW")
102 .or_else(|| field("previewImage"))
103 .map_or_else(|| url.clone(), str::to_owned),
104 title: field("title").unwrap_or_default().to_owned(),
105 width: number("width")?,
106 height: number("height")?,
107 preview_width: number("previewImageFWWidth").unwrap_or(1),
108 preview_height: number("previewImageFWHeight").unwrap_or(1),
109 url,
110 })
111}
112
113#[cfg(test)]
114mod tests {
115 use std::sync::Mutex;
116
117 use session::Scope;
118
119 use super::*;
120
121 struct Canned {
122 status: u16,
123 body: Value,
124 sent: Mutex<Vec<(Request, Scope)>>,
125 }
126
127 impl CardTransport for Canned {
128 async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {
129 self.sent.lock().unwrap().push((request, scope));
130 Ok(ApiResponse {
131 status: self.status,
132 body: self.body.clone(),
133 retry_after: None,
134 })
135 }
136 }
137
138 fn gifs(status: u16, body: Value) -> Gifs<Canned> {
139 Gifs::with_transport(
140 Canned {
141 status,
142 body,
143 sent: Mutex::new(Vec::new()),
144 },
145 "emea",
146 )
147 }
148
149 fn fixture() -> Value {
150 serde_json::from_str(include_str!("../tests/fixtures/giphy_search.json")).unwrap()
151 }
152
153 #[tokio::test]
154 async fn search_posts_the_query_to_the_giphy_command() {
155 let gifs = gifs(200, fixture());
156 gifs.search("thumbs up").await.unwrap();
157 let sent = gifs.transport.sent.lock().unwrap();
158 let (request, scope) = &sent[0];
159 assert_eq!(request.method, Method::Post);
160 assert_eq!(
161 request.url,
162 "https://teams.cloud.microsoft/api/mt/emea/beta/commands/com.microsoft.teamspace.inputextension.giphy/execute?version=1.0"
163 );
164 assert_eq!(request.body.as_ref().unwrap()[0]["value"], "thumbs up");
165 assert_eq!(request.body.as_ref().unwrap()[2]["value"], "27");
166 assert_eq!(*scope, spaces_scope());
167 }
168
169 #[tokio::test]
170 async fn results_carry_urls_titles_and_sizes() {
171 let found = gifs(200, fixture()).search("x").await.unwrap();
172 assert_eq!(found.len(), 2);
173 assert_eq!(found[0].title, "Baby Thank You GIF");
174 assert!(found[0].url.ends_with("/giphy.gif"));
175 assert!(found[0].preview_url.ends_with("/200w.gif"));
176 assert_eq!((found[0].width, found[0].height), (358, 360));
177 assert_eq!(
178 (found[0].preview_width, found[0].preview_height),
179 (200, 202)
180 );
181 }
182
183 #[tokio::test]
184 async fn forbidden_means_disabled() {
185 let outcome = gifs(403, json!({"errorCode": "Forbidden"}))
186 .search("")
187 .await;
188 assert!(matches!(outcome, Err(Error::GifsDisabled)));
189 }
190
191 #[tokio::test]
192 async fn other_failures_are_api_errors() {
193 let outcome = gifs(500, Value::Null).search("").await;
194 assert!(matches!(
195 outcome,
196 Err(Error::Session(session::Error::Api { status: 500, .. }))
197 ));
198 }
199
200 #[test]
201 fn entries_without_a_size_are_skipped() {
202 let body = json!({"result": [{"result": [{"composeValue": "https://media0.giphy.com/a.gif", "fieldValues": []}]}]});
203 assert!(parse_gifs(&body).is_empty());
204 }
205}
crates/chatsvc/src/lib.rs +2 −0
@@ -2,6 +2,7 @@ pub mod cards;
2 2 pub mod conversations;
3 3 mod error;
4 4 pub mod links;
5 pub mod gifs;
5 6 mod mask;
6 7 pub mod messages;
7 8 pub mod pins;
@@ -14,6 +15,7 @@ pub use cards::{
14 15 };
15 16 pub use conversations::Conversations;
16 17 pub use error::{Error, Result};
18 pub use gifs::{Gif, Gifs};
17 19 pub use mask::mask_conversation_id;
18 20 pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
19 21 pub use messages::{ConversationRef, Messages};
@@ -2,6 +2,7 @@ pub mod cards;
2pub mod conversations;
2pub mod conversations;
3mod error;
3mod error;
4pub mod links;
4pub mod links;
5pub mod gifs;
5mod mask;
6mod mask;
6pub mod messages;
7pub mod messages;
7pub mod pins;
8pub mod pins;
@@ -14,6 +15,7 @@ pub use cards::{
14};
15};
15pub use conversations::Conversations;
16pub use conversations::Conversations;
16pub use error::{Error, Result};
17pub use error::{Error, Result};
18pub use gifs::{Gif, Gifs};
17pub use mask::mask_conversation_id;
19pub use mask::mask_conversation_id;
18pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
20pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
19pub use messages::{ConversationRef, Messages};
21pub use messages::{ConversationRef, Messages};
crates/chatsvc/tests/fixtures/giphy_search.json added +221 −0
@@ -0,0 +1,221 @@
1 {
2 "commandId": "com.microsoft.teamspace.inputextension.giphy",
3 "parameters": [
4 {
5 "name": "query",
6 "value": "thumbs up"
7 },
8 {
9 "name": "rating",
10 "value": "g"
11 },
12 {
13 "name": "limit",
14 "value": "3"
15 },
16 {
17 "name": "lang",
18 "value": "de"
19 }
20 ],
21 "result": [
22 {
23 "result": [
24 {
25 "composeType": "Image",
26 "composeValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/BYoRqTmcgzHcL9TCy1/giphy.gif",
27 "fieldValues": [
28 {
29 "fieldName": "title",
30 "fieldValue": "Baby Thank You GIF"
31 },
32 {
33 "fieldName": "image",
34 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/BYoRqTmcgzHcL9TCy1/giphy.gif"
35 },
36 {
37 "fieldName": "previewImage",
38 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/BYoRqTmcgzHcL9TCy1/giphy-preview.gif"
39 },
40 {
41 "fieldName": "previewImageFW",
42 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/BYoRqTmcgzHcL9TCy1/200w.gif"
43 },
44 {
45 "fieldName": "previewImageFH",
46 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/BYoRqTmcgzHcL9TCy1/200.gif"
47 },
48 {
49 "fieldName": "width",
50 "fieldValue": "358"
51 },
52 {
53 "fieldName": "height",
54 "fieldValue": "360"
55 },
56 {
57 "fieldName": "previewImageWidth",
58 "fieldValue": "100"
59 },
60 {
61 "fieldName": "previewImageHeight",
62 "fieldValue": "100"
63 },
64 {
65 "fieldName": "previewImageFWWidth",
66 "fieldValue": "200"
67 },
68 {
69 "fieldName": "previewImageFWHeight",
70 "fieldValue": "202"
71 },
72 {
73 "fieldName": "previewImageFHWidth",
74 "fieldValue": "198"
75 },
76 {
77 "fieldName": "previewImageFHHeight",
78 "fieldValue": "200"
79 }
80 ]
81 },
82 {
83 "composeType": "Image",
84 "composeValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/JwjBy94VzDd6/giphy.gif",
85 "fieldValues": [
86 {
87 "fieldName": "title",
88 "fieldValue": "No Problem Yes GIF by Vevo"
89 },
90 {
91 "fieldName": "image",
92 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/JwjBy94VzDd6/giphy.gif"
93 },
94 {
95 "fieldName": "previewImage",
96 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/JwjBy94VzDd6/giphy-preview.gif"
97 },
98 {
99 "fieldName": "previewImageFW",
100 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/JwjBy94VzDd6/200w.gif"
101 },
102 {
103 "fieldName": "previewImageFH",
104 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/JwjBy94VzDd6/200.gif"
105 },
106 {
107 "fieldName": "width",
108 "fieldValue": "141"
109 },
110 {
111 "fieldName": "height",
112 "fieldValue": "141"
113 },
114 {
115 "fieldName": "previewImageWidth",
116 "fieldValue": "100"
117 },
118 {
119 "fieldName": "previewImageHeight",
120 "fieldValue": "100"
121 },
122 {
123 "fieldName": "previewImageFWWidth",
124 "fieldValue": "200"
125 },
126 {
127 "fieldName": "previewImageFWHeight",
128 "fieldValue": "200"
129 },
130 {
131 "fieldName": "previewImageFHWidth",
132 "fieldValue": "200"
133 },
134 {
135 "fieldName": "previewImageFHHeight",
136 "fieldValue": "200"
137 }
138 ]
139 }
140 ],
141 "templateType": "Grid"
142 }
143 ],
144 "schema": {
145 "composeType": "Image",
146 "composeValueSelector": "images.original.url",
147 "isCollection": true,
148 "resultSelector": "data",
149 "supportedTemplates": [
150 {
151 "fields": [
152 {
153 "name": "title",
154 "value": "title"
155 },
156 {
157 "isRequired": true,
158 "name": "image",
159 "value": "images.original.url"
160 },
161 {
162 "isRequired": true,
163 "name": "previewImage",
164 "value": "images.preview_gif.url"
165 },
166 {
167 "isRequired": true,
168 "name": "previewImageFW",
169 "value": "images.fixed_width.url"
170 },
171 {
172 "isRequired": true,
173 "name": "previewImageFH",
174 "value": "images.fixed_height.url"
175 },
176 {
177 "isRequired": true,
178 "name": "width",
179 "value": "images.original.width"
180 },
181 {
182 "isRequired": true,
183 "name": "height",
184 "value": "images.original.height"
185 },
186 {
187 "isRequired": true,
188 "name": "previewImageWidth",
189 "value": "images.preview_gif.width"
190 },
191 {
192 "isRequired": true,
193 "name": "previewImageHeight",
194 "value": "images.preview_gif.height"
195 },
196 {
197 "isRequired": true,
198 "name": "previewImageFWWidth",
199 "value": "images.fixed_width.width"
200 },
201 {
202 "isRequired": true,
203 "name": "previewImageFWHeight",
204 "value": "images.fixed_width.height"
205 },
206 {
207 "isRequired": true,
208 "name": "previewImageFHWidth",
209 "value": "images.fixed_height.width"
210 },
211 {
212 "isRequired": true,
213 "name": "previewImageFHHeight",
214 "value": "images.fixed_height.height"
215 }
216 ],
217 "type": "Grid"
218 }
219 ]
220 }
221 }
@@ -0,0 +1,221 @@
1{
2 "commandId": "com.microsoft.teamspace.inputextension.giphy",
3 "parameters": [
4 {
5 "name": "query",
6 "value": "thumbs up"
7 },
8 {
9 "name": "rating",
10 "value": "g"
11 },
12 {
13 "name": "limit",
14 "value": "3"
15 },
16 {
17 "name": "lang",
18 "value": "de"
19 }
20 ],
21 "result": [
22 {
23 "result": [
24 {
25 "composeType": "Image",
26 "composeValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/BYoRqTmcgzHcL9TCy1/giphy.gif",
27 "fieldValues": [
28 {
29 "fieldName": "title",
30 "fieldValue": "Baby Thank You GIF"
31 },
32 {
33 "fieldName": "image",
34 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/BYoRqTmcgzHcL9TCy1/giphy.gif"
35 },
36 {
37 "fieldName": "previewImage",
38 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/BYoRqTmcgzHcL9TCy1/giphy-preview.gif"
39 },
40 {
41 "fieldName": "previewImageFW",
42 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/BYoRqTmcgzHcL9TCy1/200w.gif"
43 },
44 {
45 "fieldName": "previewImageFH",
46 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/BYoRqTmcgzHcL9TCy1/200.gif"
47 },
48 {
49 "fieldName": "width",
50 "fieldValue": "358"
51 },
52 {
53 "fieldName": "height",
54 "fieldValue": "360"
55 },
56 {
57 "fieldName": "previewImageWidth",
58 "fieldValue": "100"
59 },
60 {
61 "fieldName": "previewImageHeight",
62 "fieldValue": "100"
63 },
64 {
65 "fieldName": "previewImageFWWidth",
66 "fieldValue": "200"
67 },
68 {
69 "fieldName": "previewImageFWHeight",
70 "fieldValue": "202"
71 },
72 {
73 "fieldName": "previewImageFHWidth",
74 "fieldValue": "198"
75 },
76 {
77 "fieldName": "previewImageFHHeight",
78 "fieldValue": "200"
79 }
80 ]
81 },
82 {
83 "composeType": "Image",
84 "composeValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/JwjBy94VzDd6/giphy.gif",
85 "fieldValues": [
86 {
87 "fieldName": "title",
88 "fieldValue": "No Problem Yes GIF by Vevo"
89 },
90 {
91 "fieldName": "image",
92 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/JwjBy94VzDd6/giphy.gif"
93 },
94 {
95 "fieldName": "previewImage",
96 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/JwjBy94VzDd6/giphy-preview.gif"
97 },
98 {
99 "fieldName": "previewImageFW",
100 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/JwjBy94VzDd6/200w.gif"
101 },
102 {
103 "fieldName": "previewImageFH",
104 "fieldValue": "https://media0.giphy.com/media/v1.Y2lkPWZjZGU1NDk1bXBhdnhsemhvaDlkMXI0ODI2eWt1dHFhNnpxM2J2cWZuZ3RwMWY3dyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/JwjBy94VzDd6/200.gif"
105 },
106 {
107 "fieldName": "width",
108 "fieldValue": "141"
109 },
110 {
111 "fieldName": "height",
112 "fieldValue": "141"
113 },
114 {
115 "fieldName": "previewImageWidth",
116 "fieldValue": "100"
117 },
118 {
119 "fieldName": "previewImageHeight",
120 "fieldValue": "100"
121 },
122 {
123 "fieldName": "previewImageFWWidth",
124 "fieldValue": "200"
125 },
126 {
127 "fieldName": "previewImageFWHeight",
128 "fieldValue": "200"
129 },
130 {
131 "fieldName": "previewImageFHWidth",
132 "fieldValue": "200"
133 },
134 {
135 "fieldName": "previewImageFHHeight",
136 "fieldValue": "200"
137 }
138 ]
139 }
140 ],
141 "templateType": "Grid"
142 }
143 ],
144 "schema": {
145 "composeType": "Image",
146 "composeValueSelector": "images.original.url",
147 "isCollection": true,
148 "resultSelector": "data",
149 "supportedTemplates": [
150 {
151 "fields": [
152 {
153 "name": "title",
154 "value": "title"
155 },
156 {
157 "isRequired": true,
158 "name": "image",
159 "value": "images.original.url"
160 },
161 {
162 "isRequired": true,
163 "name": "previewImage",
164 "value": "images.preview_gif.url"
165 },
166 {
167 "isRequired": true,
168 "name": "previewImageFW",
169 "value": "images.fixed_width.url"
170 },
171 {
172 "isRequired": true,
173 "name": "previewImageFH",
174 "value": "images.fixed_height.url"
175 },
176 {
177 "isRequired": true,
178 "name": "width",
179 "value": "images.original.width"
180 },
181 {
182 "isRequired": true,
183 "name": "height",
184 "value": "images.original.height"
185 },
186 {
187 "isRequired": true,
188 "name": "previewImageWidth",
189 "value": "images.preview_gif.width"
190 },
191 {
192 "isRequired": true,
193 "name": "previewImageHeight",
194 "value": "images.preview_gif.height"
195 },
196 {
197 "isRequired": true,
198 "name": "previewImageFWWidth",
199 "value": "images.fixed_width.width"
200 },
201 {
202 "isRequired": true,
203 "name": "previewImageFWHeight",
204 "value": "images.fixed_width.height"
205 },
206 {
207 "isRequired": true,
208 "name": "previewImageFHWidth",
209 "value": "images.fixed_height.width"
210 },
211 {
212 "isRequired": true,
213 "name": "previewImageFHHeight",
214 "value": "images.fixed_height.height"
215 }
216 ],
217 "type": "Grid"
218 }
219 ]
220 }
221}
crates/core/Cargo.toml +1 −0
@@ -21,6 +21,7 @@ serde_json.workspace = true
21 21 store.workspace = true
22 22 thiserror.workspace = true
23 23 tokio.workspace = true
24 url.workspace = true
24 25
25 26 [dev-dependencies]
26 27 tempfile.workspace = true
@@ -21,6 +21,7 @@ serde_json.workspace = true
21store.workspace = true
21store.workspace = true
22thiserror.workspace = true
22thiserror.workspace = true
23tokio.workspace = true
23tokio.workspace = true
24url.workspace = true
24
25
25[dev-dependencies]
26[dev-dependencies]
26tempfile.workspace = true
27tempfile.workspace = true
crates/core/src/error.rs +3 −0
@@ -12,6 +12,8 @@ pub enum Error {
12 12 Folders(String),
13 13 #[error("unknown conversation {0}")]
14 14 UnknownConversation(String),
15 #[error("GIFs are disabled by the organization")]
16 GifsDisabled,
15 17 #[error("{0} is not supported yet")]
16 18 Unsupported(&'static str),
17 19 }
@@ -20,6 +22,7 @@ impl From<chatsvc::Error> for Error {
20 22 fn from(error: chatsvc::Error) -> Self {
21 23 match error {
22 24 chatsvc::Error::Session(inner) => Error::Graph(graph::Error::Session(inner)),
25 chatsvc::Error::GifsDisabled => Error::GifsDisabled,
23 26 other => Error::Folders(other.to_string()),
24 27 }
25 28 }
@@ -12,6 +12,8 @@ pub enum Error {
12 Folders(String),
12 Folders(String),
13 #[error("unknown conversation {0}")]
13 #[error("unknown conversation {0}")]
14 UnknownConversation(String),
14 UnknownConversation(String),
15 #[error("GIFs are disabled by the organization")]
16 GifsDisabled,
15 #[error("{0} is not supported yet")]
17 #[error("{0} is not supported yet")]
16 Unsupported(&'static str),
18 Unsupported(&'static str),
17}
19}
@@ -20,6 +22,7 @@ impl From<chatsvc::Error> for Error {
20 fn from(error: chatsvc::Error) -> Self {
22 fn from(error: chatsvc::Error) -> Self {
21 match error {
23 match error {
22 chatsvc::Error::Session(inner) => Error::Graph(graph::Error::Session(inner)),
24 chatsvc::Error::Session(inner) => Error::Graph(graph::Error::Session(inner)),
25 chatsvc::Error::GifsDisabled => Error::GifsDisabled,
23 other => Error::Folders(other.to_string()),
26 other => Error::Folders(other.to_string()),
24 }
27 }
25 }
28 }
crates/core/src/external_image.rs added +83 −0
@@ -0,0 +1,83 @@
1 use url::Url;
2
3 const PROXY_PATH: &str = "/urlp/v1/url/content";
4 const PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
5 const GIPHY_HOST: &str = "giphy.com";
6 const TEAMS_CDN_HOST: &str = "statics.teams.cdn.office.net";
7
8 /// The direct URL of a GIF or sticker image, `None` when `src` is not one of the known public hosts.
9 pub fn external_image_url(src: &str) -> Option<String> {
10 let url = Url::parse(src).ok()?;
11 if is_proxy(&url) {
12 let target = url
13 .query_pairs()
14 .find(|(name, _)| name == "url")
15 .map(|(_, value)| value.into_owned())?;
16 return direct_url(&Url::parse(&target).ok()?);
17 }
18 direct_url(&url)
19 }
20
21 fn is_proxy(url: &Url) -> bool {
22 url.scheme() == "https"
23 && url.path() == PROXY_PATH
24 && url
25 .host_str()
26 .is_some_and(|host| host.ends_with(PROXY_HOST_SUFFIX))
27 }
28
29 fn direct_url(url: &Url) -> Option<String> {
30 let host = url.host_str()?;
31 let allowed = host == TEAMS_CDN_HOST
32 || host == GIPHY_HOST
33 || host
34 .strip_suffix(GIPHY_HOST)
35 .is_some_and(|prefix| prefix.ends_with('.'));
36 (url.scheme() == "https" && allowed).then(|| url.to_string())
37 }
38
39 #[cfg(test)]
40 mod tests {
41 use super::*;
42
43 #[test]
44 fn giphy_and_teams_cdn_pass() {
45 let giphy = "https://media0.giphy.com/media/abc/giphy.gif";
46 assert_eq!(external_image_url(giphy).as_deref(), Some(giphy));
47 let sticker = "https://statics.teams.cdn.office.net/evergreen-assets/stickerassets/clippy-250x250/Clippy_HelloThere.gif?v=5";
48 assert_eq!(external_image_url(sticker).as_deref(), Some(sticker));
49 assert!(external_image_url("https://giphy.com/x.gif").is_some());
50 }
51
52 #[test]
53 fn proxy_urls_are_unwrapped() {
54 let wrapped = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/content?url=https%3a%2f%2fstatics.teams.cdn.office.net%2fevergreen-assets%2fx.png%3fv%3d5";
55 assert_eq!(
56 external_image_url(wrapped).as_deref(),
57 Some("https://statics.teams.cdn.office.net/evergreen-assets/x.png?v=5")
58 );
59 }
60
61 #[test]
62 fn proxy_of_a_foreign_host_is_rejected() {
63 let wrapped = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/content?url=https%3a%2f%2fevil.example%2fx.png";
64 assert_eq!(external_image_url(wrapped), None);
65 }
66
67 #[test]
68 fn insecure_and_lookalike_hosts_are_rejected() {
69 assert_eq!(external_image_url("http://media0.giphy.com/a.gif"), None);
70 assert_eq!(
71 external_image_url("https://giphy.com.evil.example/a.gif"),
72 None
73 );
74 assert_eq!(external_image_url("https://evilgiphy.com/a.gif"), None);
75 assert_eq!(
76 external_image_url(
77 "https://graph.microsoft.com/v1.0/chats/1/messages/2/hostedContents/3/$value"
78 ),
79 None
80 );
81 assert_eq!(external_image_url("not a url"), None);
82 }
83 }
@@ -0,0 +1,83 @@
1use url::Url;
2
3const PROXY_PATH: &str = "/urlp/v1/url/content";
4const PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
5const GIPHY_HOST: &str = "giphy.com";
6const TEAMS_CDN_HOST: &str = "statics.teams.cdn.office.net";
7
8/// The direct URL of a GIF or sticker image, `None` when `src` is not one of the known public hosts.
9pub fn external_image_url(src: &str) -> Option<String> {
10 let url = Url::parse(src).ok()?;
11 if is_proxy(&url) {
12 let target = url
13 .query_pairs()
14 .find(|(name, _)| name == "url")
15 .map(|(_, value)| value.into_owned())?;
16 return direct_url(&Url::parse(&target).ok()?);
17 }
18 direct_url(&url)
19}
20
21fn is_proxy(url: &Url) -> bool {
22 url.scheme() == "https"
23 && url.path() == PROXY_PATH
24 && url
25 .host_str()
26 .is_some_and(|host| host.ends_with(PROXY_HOST_SUFFIX))
27}
28
29fn direct_url(url: &Url) -> Option<String> {
30 let host = url.host_str()?;
31 let allowed = host == TEAMS_CDN_HOST
32 || host == GIPHY_HOST
33 || host
34 .strip_suffix(GIPHY_HOST)
35 .is_some_and(|prefix| prefix.ends_with('.'));
36 (url.scheme() == "https" && allowed).then(|| url.to_string())
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42
43 #[test]
44 fn giphy_and_teams_cdn_pass() {
45 let giphy = "https://media0.giphy.com/media/abc/giphy.gif";
46 assert_eq!(external_image_url(giphy).as_deref(), Some(giphy));
47 let sticker = "https://statics.teams.cdn.office.net/evergreen-assets/stickerassets/clippy-250x250/Clippy_HelloThere.gif?v=5";
48 assert_eq!(external_image_url(sticker).as_deref(), Some(sticker));
49 assert!(external_image_url("https://giphy.com/x.gif").is_some());
50 }
51
52 #[test]
53 fn proxy_urls_are_unwrapped() {
54 let wrapped = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/content?url=https%3a%2f%2fstatics.teams.cdn.office.net%2fevergreen-assets%2fx.png%3fv%3d5";
55 assert_eq!(
56 external_image_url(wrapped).as_deref(),
57 Some("https://statics.teams.cdn.office.net/evergreen-assets/x.png?v=5")
58 );
59 }
60
61 #[test]
62 fn proxy_of_a_foreign_host_is_rejected() {
63 let wrapped = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/content?url=https%3a%2f%2fevil.example%2fx.png";
64 assert_eq!(external_image_url(wrapped), None);
65 }
66
67 #[test]
68 fn insecure_and_lookalike_hosts_are_rejected() {
69 assert_eq!(external_image_url("http://media0.giphy.com/a.gif"), None);
70 assert_eq!(
71 external_image_url("https://giphy.com.evil.example/a.gif"),
72 None
73 );
74 assert_eq!(external_image_url("https://evilgiphy.com/a.gif"), None);
75 assert_eq!(
76 external_image_url(
77 "https://graph.microsoft.com/v1.0/chats/1/messages/2/hostedContents/3/$value"
78 ),
79 None
80 );
81 assert_eq!(external_image_url("not a url"), None);
82 }
83}
crates/core/src/gifs.rs added +12 −0
@@ -0,0 +1,12 @@
1 use chatsvc::Gif;
2
3 use crate::engine::SyncEngine;
4 use crate::error::Result;
5 use crate::remote::Remote;
6
7 impl<R: Remote> SyncEngine<R> {
8 /// An empty query returns the trending GIFs.
9 pub async fn search_gifs(&self, query: &str) -> Result<Vec<Gif>> {
10 self.remote.search_gifs(query).await
11 }
12 }
@@ -0,0 +1,12 @@
1use chatsvc::Gif;
2
3use crate::engine::SyncEngine;
4use crate::error::Result;
5use crate::remote::Remote;
6
7impl<R: Remote> SyncEngine<R> {
8 /// An empty query returns the trending GIFs.
9 pub async fn search_gifs(&self, query: &str) -> Result<Vec<Gif>> {
10 self.remote.search_gifs(query).await
11 }
12}
crates/core/src/images.rs +5 −1
@@ -6,6 +6,7 @@ use store::{ImageFileCache, ImageRecord};
6 6 use crate::engine::SyncEngine;
7 7 use crate::error::Result;
8 8 use crate::events::CoreEvent;
9 use crate::external_image::external_image_url;
9 10 use crate::image_size::sniff;
10 11 use crate::remote::Remote;
11 12 use crate::stored::ImageRef;
@@ -73,7 +74,10 @@ impl<R: Remote> SyncEngine<R> {
73 74 }
74 75
75 76 async fn download_image(&self, key: &str) -> Result<Option<PathBuf>> {
76 let photo = self.remote.hosted_content(key).await?;
77 let photo = match external_image_url(key) {
78 Some(url) => self.remote.external_image(&url).await?,
79 None => self.remote.hosted_content(key).await?,
80 };
77 81 let path = match &self.image_files {
78 82 Some(files) => {
79 83 let extension = file_extension(&photo.content_type, &photo.bytes);
@@ -6,6 +6,7 @@ use store::{ImageFileCache, ImageRecord};
6use crate::engine::SyncEngine;
6use crate::engine::SyncEngine;
7use crate::error::Result;
7use crate::error::Result;
8use crate::events::CoreEvent;
8use crate::events::CoreEvent;
9use crate::external_image::external_image_url;
9use crate::image_size::sniff;
10use crate::image_size::sniff;
10use crate::remote::Remote;
11use crate::remote::Remote;
11use crate::stored::ImageRef;
12use crate::stored::ImageRef;
@@ -73,7 +74,10 @@ impl<R: Remote> SyncEngine<R> {
73 }
74 }
74
75
75 async fn download_image(&self, key: &str) -> Result<Option<PathBuf>> {
76 async fn download_image(&self, key: &str) -> Result<Option<PathBuf>> {
76 let photo = self.remote.hosted_content(key).await?;
77 let photo = match external_image_url(key) {
78 Some(url) => self.remote.external_image(&url).await?,
79 None => self.remote.hosted_content(key).await?,
80 };
77 let path = match &self.image_files {
81 let path = match &self.image_files {
78 Some(files) => {
82 Some(files) => {
79 let extension = file_extension(&photo.content_type, &photo.bytes);
83 let extension = file_extension(&photo.content_type, &photo.bytes);
crates/core/src/lib.rs +4 −1
@@ -8,8 +8,10 @@ mod download;
8 8 mod draft;
9 9 mod engine;
10 10 mod error;
11 mod external_image;
11 12 mod events;
12 13 mod folders;
14 mod gifs;
13 15 mod image_size;
14 16 mod images;
15 17 mod link_sync;
@@ -40,7 +42,7 @@ pub use card_inputs::{
40 42 MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,
41 43 collect_input_values, merge_input_data,
42 44 };
43 pub use chatsvc::ChatApp;
45 pub use chatsvc::{ChatApp, Gif};
44 46 pub use draft::{
45 47 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
46 48 SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
@@ -53,6 +55,7 @@ pub use graph::{
53 55 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,
54 56 UploadedFile,
55 57 };
58 pub use external_image::external_image_url;
56 59 pub use images::StoredImage;
57 60 pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
58 61 pub use mapping::{chat_record, message_record};
@@ -8,8 +8,10 @@ mod download;
8mod draft;
8mod draft;
9mod engine;
9mod engine;
10mod error;
10mod error;
11mod external_image;
11mod events;
12mod events;
12mod folders;
13mod folders;
14mod gifs;
13mod image_size;
15mod image_size;
14mod images;
16mod images;
15mod link_sync;
17mod link_sync;
@@ -40,7 +42,7 @@ pub use card_inputs::{
40 MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,
42 MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,
41 collect_input_values, merge_input_data,
43 collect_input_values, merge_input_data,
42};
44};
43pub use chatsvc::ChatApp;
45pub use chatsvc::{ChatApp, Gif};
44pub use draft::{
46pub use draft::{
45 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
47 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
46 SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
48 SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
@@ -53,6 +55,7 @@ pub use graph::{
53 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,
55 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,
54 UploadedFile,
56 UploadedFile,
55};
57};
58pub use external_image::external_image_url;
56pub use images::StoredImage;
59pub use images::StoredImage;
57pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
60pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
58pub use mapping::{chat_record, message_record};
61pub use mapping::{chat_record, message_record};
crates/core/src/remote.rs +18 −2
@@ -1,6 +1,6 @@
1 1 use chatsvc::{
2 CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse, LinkInfo,
3 MemberHorizon, MessageLinks, Messages, Receipts,
2 CardActions, ChatApp, ConversationRef, Conversations, Gif, Gifs, InvokeRequest, InvokeResponse,
3 LinkInfo, MemberHorizon, MessageLinks, Messages, Receipts,
4 4 };
5 5 use chrono::{DateTime, Utc};
6 6 use graph::{
@@ -188,6 +188,10 @@ pub trait Remote {
188 188 Err(Error::Unsupported("hosted content"))
189 189 }
190 190
191 async fn external_image(&self, _url: &str) -> Result<Photo> {
192 Err(Error::Unsupported("external images"))
193 }
194
191 195 async fn user_photos(&self, _user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
192 196 Err(Error::Unsupported("profile photos"))
193 197 }
@@ -233,6 +237,10 @@ pub trait Remote {
233 237 async fn link_info(&self, _url: &str) -> Result<LinkInfo> {
234 238 Err(Error::Unsupported("link previews"))
235 239 }
240
241 async fn search_gifs(&self, _query: &str) -> Result<Vec<Gif>> {
242 Err(Error::Unsupported("GIF search"))
243 }
236 244 }
237 245
238 246 impl Remote for Graph {
@@ -557,6 +565,10 @@ impl Remote for Graph {
557 565 Ok(Graph::download_hosted_content(self, url).await?)
558 566 }
559 567
568 async fn external_image(&self, url: &str) -> Result<Photo> {
569 Ok(Graph::download_external_image(self, url).await?)
570 }
571
560 572 async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
561 573 let photos = Graph::user_photos(self, user_ids).await?;
562 574 Ok(photos
@@ -612,6 +624,10 @@ impl Remote for Graph {
612 624 async fn link_info(&self, url: &str) -> Result<LinkInfo> {
613 625 Ok(Messages::new(self.session()).link_info(url).await?)
614 626 }
627
628 async fn search_gifs(&self, query: &str) -> Result<Vec<Gif>> {
629 Ok(Gifs::new(self.session()).search(query).await?)
630 }
615 631 }
616 632
617 633 fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {
@@ -1,6 +1,6 @@
1use chatsvc::{
1use chatsvc::{
2 CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse, LinkInfo,
2 CardActions, ChatApp, ConversationRef, Conversations, Gif, Gifs, InvokeRequest, InvokeResponse,
3 MemberHorizon, MessageLinks, Messages, Receipts,
3 LinkInfo, MemberHorizon, MessageLinks, Messages, Receipts,
4};
4};
5use chrono::{DateTime, Utc};
5use chrono::{DateTime, Utc};
6use graph::{
6use graph::{
@@ -188,6 +188,10 @@ pub trait Remote {
188 Err(Error::Unsupported("hosted content"))
188 Err(Error::Unsupported("hosted content"))
189 }
189 }
190
190
191 async fn external_image(&self, _url: &str) -> Result<Photo> {
192 Err(Error::Unsupported("external images"))
193 }
194
191 async fn user_photos(&self, _user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
195 async fn user_photos(&self, _user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
192 Err(Error::Unsupported("profile photos"))
196 Err(Error::Unsupported("profile photos"))
193 }
197 }
@@ -233,6 +237,10 @@ pub trait Remote {
233 async fn link_info(&self, _url: &str) -> Result<LinkInfo> {
237 async fn link_info(&self, _url: &str) -> Result<LinkInfo> {
234 Err(Error::Unsupported("link previews"))
238 Err(Error::Unsupported("link previews"))
235 }
239 }
240
241 async fn search_gifs(&self, _query: &str) -> Result<Vec<Gif>> {
242 Err(Error::Unsupported("GIF search"))
243 }
236}
244}
237
245
238impl Remote for Graph {
246impl Remote for Graph {
@@ -557,6 +565,10 @@ impl Remote for Graph {
557 Ok(Graph::download_hosted_content(self, url).await?)
565 Ok(Graph::download_hosted_content(self, url).await?)
558 }
566 }
559
567
568 async fn external_image(&self, url: &str) -> Result<Photo> {
569 Ok(Graph::download_external_image(self, url).await?)
570 }
571
560 async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
572 async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
561 let photos = Graph::user_photos(self, user_ids).await?;
573 let photos = Graph::user_photos(self, user_ids).await?;
562 Ok(photos
574 Ok(photos
@@ -612,6 +624,10 @@ impl Remote for Graph {
612 async fn link_info(&self, url: &str) -> Result<LinkInfo> {
624 async fn link_info(&self, url: &str) -> Result<LinkInfo> {
613 Ok(Messages::new(self.session()).link_info(url).await?)
625 Ok(Messages::new(self.session()).link_info(url).await?)
614 }
626 }
627
628 async fn search_gifs(&self, query: &str) -> Result<Vec<Gif>> {
629 Ok(Gifs::new(self.session()).search(query).await?)
630 }
615}
631}
616
632
617fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {
633fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {
crates/core/tests/engine.rs +25 −0
@@ -82,6 +82,7 @@ struct Fake {
82 82 presence_answers: Mutex<Vec<Presence>>,
83 83 presence_subscriptions: Mutex<Vec<(String, Vec<String>, bool)>>,
84 84 hosted_requests: Mutex<Vec<String>>,
85 external_requests: Mutex<Vec<String>>,
85 86 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
86 87 extras_sent: Mutex<Vec<MessageExtras>>,
87 88 folder_requests: Mutex<usize>,
@@ -577,6 +578,11 @@ impl Remote for Handle {
577 578 Ok(())
578 579 }
579 580
581 async fn external_image(&self, url: &str) -> Result<Photo> {
582 self.external_requests.lock().unwrap().push(url.to_owned());
583 self.hosted_content(url).await
584 }
585
580 586 async fn hosted_content(&self, url: &str) -> Result<Photo> {
581 587 self.hosted_requests.lock().unwrap().push(url.to_owned());
582 588 if url.contains("broken") {
@@ -2213,6 +2219,25 @@ async fn images_are_fetched_once_cached_and_announced() {
2213 2219 assert_eq!((stored.width, stored.height), (Some(40), Some(20)));
2214 2220 }
2215 2221
2222 #[tokio::test]
2223 async fn gif_and_sticker_images_load_without_graph_and_keep_their_cache_key() {
2224 let fake = Arc::new(Fake::default());
2225 let engine = chat_engine(&fake, small_pages()).await;
2226 let proxied = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/content?url=https%3a%2f%2fstatics.teams.cdn.office.net%2fx%2fa.png";
2227 let image = teams_core::ImageRef {
2228 id: "x".to_owned(),
2229 url: proxied.to_owned(),
2230 width: None,
2231 height: None,
2232 };
2233 engine.fetch_image(&image).await.unwrap();
2234 assert_eq!(
2235 *fake.external_requests.lock().unwrap(),
2236 ["https://statics.teams.cdn.office.net/x/a.png"]
2237 );
2238 assert!(engine.image(proxied).is_some());
2239 }
2240
2216 2241 #[tokio::test]
2217 2242 async fn a_failed_image_fetch_is_an_error_and_can_be_retried() {
2218 2243 let fake = Arc::new(Fake::default());
@@ -82,6 +82,7 @@ struct Fake {
82 presence_answers: Mutex<Vec<Presence>>,
82 presence_answers: Mutex<Vec<Presence>>,
83 presence_subscriptions: Mutex<Vec<(String, Vec<String>, bool)>>,
83 presence_subscriptions: Mutex<Vec<(String, Vec<String>, bool)>>,
84 hosted_requests: Mutex<Vec<String>>,
84 hosted_requests: Mutex<Vec<String>>,
85 external_requests: Mutex<Vec<String>>,
85 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
86 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
86 extras_sent: Mutex<Vec<MessageExtras>>,
87 extras_sent: Mutex<Vec<MessageExtras>>,
87 folder_requests: Mutex<usize>,
88 folder_requests: Mutex<usize>,
@@ -577,6 +578,11 @@ impl Remote for Handle {
577 Ok(())
578 Ok(())
578 }
579 }
579
580
581 async fn external_image(&self, url: &str) -> Result<Photo> {
582 self.external_requests.lock().unwrap().push(url.to_owned());
583 self.hosted_content(url).await
584 }
585
580 async fn hosted_content(&self, url: &str) -> Result<Photo> {
586 async fn hosted_content(&self, url: &str) -> Result<Photo> {
581 self.hosted_requests.lock().unwrap().push(url.to_owned());
587 self.hosted_requests.lock().unwrap().push(url.to_owned());
582 if url.contains("broken") {
588 if url.contains("broken") {
@@ -2213,6 +2219,25 @@ async fn images_are_fetched_once_cached_and_announced() {
2213 assert_eq!((stored.width, stored.height), (Some(40), Some(20)));
2219 assert_eq!((stored.width, stored.height), (Some(40), Some(20)));
2214}
2220}
2215
2221
2222#[tokio::test]
2223async fn gif_and_sticker_images_load_without_graph_and_keep_their_cache_key() {
2224 let fake = Arc::new(Fake::default());
2225 let engine = chat_engine(&fake, small_pages()).await;
2226 let proxied = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/content?url=https%3a%2f%2fstatics.teams.cdn.office.net%2fx%2fa.png";
2227 let image = teams_core::ImageRef {
2228 id: "x".to_owned(),
2229 url: proxied.to_owned(),
2230 width: None,
2231 height: None,
2232 };
2233 engine.fetch_image(&image).await.unwrap();
2234 assert_eq!(
2235 *fake.external_requests.lock().unwrap(),
2236 ["https://statics.teams.cdn.office.net/x/a.png"]
2237 );
2238 assert!(engine.image(proxied).is_some());
2239}
2240
2216#[tokio::test]
2241#[tokio::test]
2217async fn a_failed_image_fetch_is_an_error_and_can_be_retried() {
2242async fn a_failed_image_fetch_is_an_error_and_can_be_retried() {
2218 let fake = Arc::new(Fake::default());
2243 let fake = Arc::new(Fake::default());
crates/graph/src/content.rs +11 −0
@@ -7,6 +7,7 @@ use crate::people::decode_binary;
7 7
8 8 const CHAT_PATH: &str = "/v1.0/chats/";
9 9 const CHANNEL_PATH: &str = "/v1.0/teams/";
10 const EXTERNAL_IMAGE_SCOPE: &str = "Chat.Read";
10 11
11 12 impl Graph {
12 13 /// Binary GET of a Graph hosted content URL (`.../hostedContents/{id}/$value`).
@@ -21,6 +22,16 @@ impl Graph {
21 22 .remove(0);
22 23 decode_binary(url, answer)
23 24 }
25
26 /// Anonymous binary GET of a public image URL (GIF or sticker CDN), run inside the page.
27 pub async fn download_external_image(&self, url: &str) -> Result<Photo> {
28 let request = Request::anonymous_binary_get(url, Vec::new());
29 let answer = self
30 .session()
31 .send(request, &Scope::graph(EXTERNAL_IMAGE_SCOPE))
32 .await?;
33 decode_binary(url, answer)
34 }
24 35 }
25 36
26 37 pub fn hosted_content_scope(url: &str) -> Option<Scope> {
@@ -7,6 +7,7 @@ use crate::people::decode_binary;
7
7
8const CHAT_PATH: &str = "/v1.0/chats/";
8const CHAT_PATH: &str = "/v1.0/chats/";
9const CHANNEL_PATH: &str = "/v1.0/teams/";
9const CHANNEL_PATH: &str = "/v1.0/teams/";
10const EXTERNAL_IMAGE_SCOPE: &str = "Chat.Read";
10
11
11impl Graph {
12impl Graph {
12 /// Binary GET of a Graph hosted content URL (`.../hostedContents/{id}/$value`).
13 /// Binary GET of a Graph hosted content URL (`.../hostedContents/{id}/$value`).
@@ -21,6 +22,16 @@ impl Graph {
21 .remove(0);
22 .remove(0);
22 decode_binary(url, answer)
23 decode_binary(url, answer)
23 }
24 }
25
26 /// Anonymous binary GET of a public image URL (GIF or sticker CDN), run inside the page.
27 pub async fn download_external_image(&self, url: &str) -> Result<Photo> {
28 let request = Request::anonymous_binary_get(url, Vec::new());
29 let answer = self
30 .session()
31 .send(request, &Scope::graph(EXTERNAL_IMAGE_SCOPE))
32 .await?;
33 decode_binary(url, answer)
34 }
24}
35}
25
36
26pub fn hosted_content_scope(url: &str) -> Option<Scope> {
37pub fn hosted_content_scope(url: &str) -> Option<Scope> {