├── .gitignore
├── Cargo.lock
├── Cargo.toml
├── LICENSE
├── README.md
├── docs
└── assets
│ ├── ccanvas-structure.png
│ ├── ccanvas-structure.svg
│ ├── idea.png
│ └── idea.xcf
└── src
├── lib.rs
├── main.rs
├── structs
├── component
│ ├── discriminator.rs
│ ├── focus.rs
│ ├── mod.rs
│ ├── passes.rs
│ ├── process.rs
│ ├── space.rs
│ ├── subscription.rs
│ └── subscriptions.rs
├── data
│ ├── collection.rs
│ ├── mod.rs
│ ├── packet.rs
│ ├── pool.rs
│ ├── storage.rs
│ └── unevaluated.rs
├── error.rs
├── events
│ ├── event.rs
│ ├── keyevent.rs
│ ├── listeners.rs
│ ├── mod.rs
│ ├── mouseevent.rs
│ └── suppressor.rs
├── mod.rs
├── requests
│ ├── mod.rs
│ ├── render_request.rs
│ ├── request.rs
│ └── requestcontent.rs
└── responses
│ ├── event_serde.rs
│ ├── mod.rs
│ ├── response.rs
│ ├── response_error.rs
│ ├── response_success.rs
│ └── responsecontent.rs
├── term
├── commands.rs
├── enter.rs
├── exit.rs
└── mod.rs
├── traits
├── component.rs
└── mod.rs
└── values.rs
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 |
--------------------------------------------------------------------------------
/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "addr2line"
7 | version = "0.21.0"
8 | source = "registry+https://github.com/rust-lang/crates.io-index"
9 | checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb"
10 | dependencies = [
11 | "gimli",
12 | ]
13 |
14 | [[package]]
15 | name = "adler"
16 | version = "1.0.2"
17 | source = "registry+https://github.com/rust-lang/crates.io-index"
18 | checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
19 |
20 | [[package]]
21 | name = "async-trait"
22 | version = "0.1.74"
23 | source = "registry+https://github.com/rust-lang/crates.io-index"
24 | checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
25 | dependencies = [
26 | "proc-macro2",
27 | "quote",
28 | "syn",
29 | ]
30 |
31 | [[package]]
32 | name = "backtrace"
33 | version = "0.3.69"
34 | source = "registry+https://github.com/rust-lang/crates.io-index"
35 | checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837"
36 | dependencies = [
37 | "addr2line",
38 | "cc",
39 | "cfg-if",
40 | "libc",
41 | "miniz_oxide",
42 | "object",
43 | "rustc-demangle",
44 | ]
45 |
46 | [[package]]
47 | name = "bitflags"
48 | version = "1.3.2"
49 | source = "registry+https://github.com/rust-lang/crates.io-index"
50 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
51 |
52 | [[package]]
53 | name = "bitflags"
54 | version = "2.4.1"
55 | source = "registry+https://github.com/rust-lang/crates.io-index"
56 | checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07"
57 |
58 | [[package]]
59 | name = "bytes"
60 | version = "1.5.0"
61 | source = "registry+https://github.com/rust-lang/crates.io-index"
62 | checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
63 |
64 | [[package]]
65 | name = "cc"
66 | version = "1.0.83"
67 | source = "registry+https://github.com/rust-lang/crates.io-index"
68 | checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0"
69 | dependencies = [
70 | "libc",
71 | ]
72 |
73 | [[package]]
74 | name = "ccanvas"
75 | version = "0.2.0"
76 | dependencies = [
77 | "async-trait",
78 | "dirs",
79 | "libc",
80 | "log",
81 | "nix",
82 | "serde",
83 | "serde_json",
84 | "simplelog",
85 | "termion",
86 | "tokio",
87 | ]
88 |
89 | [[package]]
90 | name = "cfg-if"
91 | version = "1.0.0"
92 | source = "registry+https://github.com/rust-lang/crates.io-index"
93 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
94 |
95 | [[package]]
96 | name = "deranged"
97 | version = "0.3.11"
98 | source = "registry+https://github.com/rust-lang/crates.io-index"
99 | checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4"
100 | dependencies = [
101 | "powerfmt",
102 | ]
103 |
104 | [[package]]
105 | name = "dirs"
106 | version = "5.0.1"
107 | source = "registry+https://github.com/rust-lang/crates.io-index"
108 | checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"
109 | dependencies = [
110 | "dirs-sys",
111 | ]
112 |
113 | [[package]]
114 | name = "dirs-sys"
115 | version = "0.4.1"
116 | source = "registry+https://github.com/rust-lang/crates.io-index"
117 | checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"
118 | dependencies = [
119 | "libc",
120 | "option-ext",
121 | "redox_users",
122 | "windows-sys",
123 | ]
124 |
125 | [[package]]
126 | name = "getrandom"
127 | version = "0.2.11"
128 | source = "registry+https://github.com/rust-lang/crates.io-index"
129 | checksum = "fe9006bed769170c11f845cf00c7c1e9092aeb3f268e007c3e760ac68008070f"
130 | dependencies = [
131 | "cfg-if",
132 | "libc",
133 | "wasi",
134 | ]
135 |
136 | [[package]]
137 | name = "gimli"
138 | version = "0.28.1"
139 | source = "registry+https://github.com/rust-lang/crates.io-index"
140 | checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253"
141 |
142 | [[package]]
143 | name = "hermit-abi"
144 | version = "0.3.3"
145 | source = "registry+https://github.com/rust-lang/crates.io-index"
146 | checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7"
147 |
148 | [[package]]
149 | name = "itoa"
150 | version = "1.0.10"
151 | source = "registry+https://github.com/rust-lang/crates.io-index"
152 | checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c"
153 |
154 | [[package]]
155 | name = "libc"
156 | version = "0.2.151"
157 | source = "registry+https://github.com/rust-lang/crates.io-index"
158 | checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4"
159 |
160 | [[package]]
161 | name = "libredox"
162 | version = "0.0.1"
163 | source = "registry+https://github.com/rust-lang/crates.io-index"
164 | checksum = "85c833ca1e66078851dba29046874e38f08b2c883700aa29a03ddd3b23814ee8"
165 | dependencies = [
166 | "bitflags 2.4.1",
167 | "libc",
168 | "redox_syscall",
169 | ]
170 |
171 | [[package]]
172 | name = "libredox"
173 | version = "0.0.2"
174 | source = "registry+https://github.com/rust-lang/crates.io-index"
175 | checksum = "3af92c55d7d839293953fcd0fda5ecfe93297cfde6ffbdec13b41d99c0ba6607"
176 | dependencies = [
177 | "bitflags 2.4.1",
178 | "libc",
179 | "redox_syscall",
180 | ]
181 |
182 | [[package]]
183 | name = "log"
184 | version = "0.4.20"
185 | source = "registry+https://github.com/rust-lang/crates.io-index"
186 | checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
187 |
188 | [[package]]
189 | name = "memchr"
190 | version = "2.6.4"
191 | source = "registry+https://github.com/rust-lang/crates.io-index"
192 | checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167"
193 |
194 | [[package]]
195 | name = "miniz_oxide"
196 | version = "0.7.1"
197 | source = "registry+https://github.com/rust-lang/crates.io-index"
198 | checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7"
199 | dependencies = [
200 | "adler",
201 | ]
202 |
203 | [[package]]
204 | name = "mio"
205 | version = "0.8.10"
206 | source = "registry+https://github.com/rust-lang/crates.io-index"
207 | checksum = "8f3d0b296e374a4e6f3c7b0a1f5a51d748a0d34c85e7dc48fc3fa9a87657fe09"
208 | dependencies = [
209 | "libc",
210 | "wasi",
211 | "windows-sys",
212 | ]
213 |
214 | [[package]]
215 | name = "nix"
216 | version = "0.27.1"
217 | source = "registry+https://github.com/rust-lang/crates.io-index"
218 | checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053"
219 | dependencies = [
220 | "bitflags 2.4.1",
221 | "cfg-if",
222 | "libc",
223 | ]
224 |
225 | [[package]]
226 | name = "num_cpus"
227 | version = "1.16.0"
228 | source = "registry+https://github.com/rust-lang/crates.io-index"
229 | checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43"
230 | dependencies = [
231 | "hermit-abi",
232 | "libc",
233 | ]
234 |
235 | [[package]]
236 | name = "num_threads"
237 | version = "0.1.6"
238 | source = "registry+https://github.com/rust-lang/crates.io-index"
239 | checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44"
240 | dependencies = [
241 | "libc",
242 | ]
243 |
244 | [[package]]
245 | name = "numtoa"
246 | version = "0.1.0"
247 | source = "registry+https://github.com/rust-lang/crates.io-index"
248 | checksum = "b8f8bdf33df195859076e54ab11ee78a1b208382d3a26ec40d142ffc1ecc49ef"
249 |
250 | [[package]]
251 | name = "object"
252 | version = "0.32.1"
253 | source = "registry+https://github.com/rust-lang/crates.io-index"
254 | checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0"
255 | dependencies = [
256 | "memchr",
257 | ]
258 |
259 | [[package]]
260 | name = "option-ext"
261 | version = "0.2.0"
262 | source = "registry+https://github.com/rust-lang/crates.io-index"
263 | checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
264 |
265 | [[package]]
266 | name = "pin-project-lite"
267 | version = "0.2.13"
268 | source = "registry+https://github.com/rust-lang/crates.io-index"
269 | checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
270 |
271 | [[package]]
272 | name = "powerfmt"
273 | version = "0.2.0"
274 | source = "registry+https://github.com/rust-lang/crates.io-index"
275 | checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
276 |
277 | [[package]]
278 | name = "proc-macro2"
279 | version = "1.0.75"
280 | source = "registry+https://github.com/rust-lang/crates.io-index"
281 | checksum = "907a61bd0f64c2f29cd1cf1dc34d05176426a3f504a78010f08416ddb7b13708"
282 | dependencies = [
283 | "unicode-ident",
284 | ]
285 |
286 | [[package]]
287 | name = "quote"
288 | version = "1.0.35"
289 | source = "registry+https://github.com/rust-lang/crates.io-index"
290 | checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
291 | dependencies = [
292 | "proc-macro2",
293 | ]
294 |
295 | [[package]]
296 | name = "redox_syscall"
297 | version = "0.4.1"
298 | source = "registry+https://github.com/rust-lang/crates.io-index"
299 | checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"
300 | dependencies = [
301 | "bitflags 1.3.2",
302 | ]
303 |
304 | [[package]]
305 | name = "redox_termios"
306 | version = "0.1.3"
307 | source = "registry+https://github.com/rust-lang/crates.io-index"
308 | checksum = "20145670ba436b55d91fc92d25e71160fbfbdd57831631c8d7d36377a476f1cb"
309 |
310 | [[package]]
311 | name = "redox_users"
312 | version = "0.4.4"
313 | source = "registry+https://github.com/rust-lang/crates.io-index"
314 | checksum = "a18479200779601e498ada4e8c1e1f50e3ee19deb0259c25825a98b5603b2cb4"
315 | dependencies = [
316 | "getrandom",
317 | "libredox 0.0.1",
318 | "thiserror",
319 | ]
320 |
321 | [[package]]
322 | name = "rustc-demangle"
323 | version = "0.1.23"
324 | source = "registry+https://github.com/rust-lang/crates.io-index"
325 | checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
326 |
327 | [[package]]
328 | name = "ryu"
329 | version = "1.0.16"
330 | source = "registry+https://github.com/rust-lang/crates.io-index"
331 | checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c"
332 |
333 | [[package]]
334 | name = "serde"
335 | version = "1.0.193"
336 | source = "registry+https://github.com/rust-lang/crates.io-index"
337 | checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89"
338 | dependencies = [
339 | "serde_derive",
340 | ]
341 |
342 | [[package]]
343 | name = "serde_derive"
344 | version = "1.0.193"
345 | source = "registry+https://github.com/rust-lang/crates.io-index"
346 | checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3"
347 | dependencies = [
348 | "proc-macro2",
349 | "quote",
350 | "syn",
351 | ]
352 |
353 | [[package]]
354 | name = "serde_json"
355 | version = "1.0.109"
356 | source = "registry+https://github.com/rust-lang/crates.io-index"
357 | checksum = "cb0652c533506ad7a2e353cce269330d6afd8bdfb6d75e0ace5b35aacbd7b9e9"
358 | dependencies = [
359 | "itoa",
360 | "ryu",
361 | "serde",
362 | ]
363 |
364 | [[package]]
365 | name = "signal-hook-registry"
366 | version = "1.4.1"
367 | source = "registry+https://github.com/rust-lang/crates.io-index"
368 | checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1"
369 | dependencies = [
370 | "libc",
371 | ]
372 |
373 | [[package]]
374 | name = "simplelog"
375 | version = "0.12.1"
376 | source = "registry+https://github.com/rust-lang/crates.io-index"
377 | checksum = "acee08041c5de3d5048c8b3f6f13fafb3026b24ba43c6a695a0c76179b844369"
378 | dependencies = [
379 | "log",
380 | "termcolor",
381 | "time",
382 | ]
383 |
384 | [[package]]
385 | name = "syn"
386 | version = "2.0.47"
387 | source = "registry+https://github.com/rust-lang/crates.io-index"
388 | checksum = "1726efe18f42ae774cc644f330953a5e7b3c3003d3edcecf18850fe9d4dd9afb"
389 | dependencies = [
390 | "proc-macro2",
391 | "quote",
392 | "unicode-ident",
393 | ]
394 |
395 | [[package]]
396 | name = "termcolor"
397 | version = "1.1.3"
398 | source = "registry+https://github.com/rust-lang/crates.io-index"
399 | checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"
400 | dependencies = [
401 | "winapi-util",
402 | ]
403 |
404 | [[package]]
405 | name = "termion"
406 | version = "2.0.3"
407 | source = "registry+https://github.com/rust-lang/crates.io-index"
408 | checksum = "c4648c7def6f2043b2568617b9f9b75eae88ca185dbc1f1fda30e95a85d49d7d"
409 | dependencies = [
410 | "libc",
411 | "libredox 0.0.2",
412 | "numtoa",
413 | "redox_termios",
414 | ]
415 |
416 | [[package]]
417 | name = "thiserror"
418 | version = "1.0.56"
419 | source = "registry+https://github.com/rust-lang/crates.io-index"
420 | checksum = "d54378c645627613241d077a3a79db965db602882668f9136ac42af9ecb730ad"
421 | dependencies = [
422 | "thiserror-impl",
423 | ]
424 |
425 | [[package]]
426 | name = "thiserror-impl"
427 | version = "1.0.56"
428 | source = "registry+https://github.com/rust-lang/crates.io-index"
429 | checksum = "fa0faa943b50f3db30a20aa7e265dbc66076993efed8463e8de414e5d06d3471"
430 | dependencies = [
431 | "proc-macro2",
432 | "quote",
433 | "syn",
434 | ]
435 |
436 | [[package]]
437 | name = "time"
438 | version = "0.3.31"
439 | source = "registry+https://github.com/rust-lang/crates.io-index"
440 | checksum = "f657ba42c3f86e7680e53c8cd3af8abbe56b5491790b46e22e19c0d57463583e"
441 | dependencies = [
442 | "deranged",
443 | "itoa",
444 | "libc",
445 | "num_threads",
446 | "powerfmt",
447 | "serde",
448 | "time-core",
449 | "time-macros",
450 | ]
451 |
452 | [[package]]
453 | name = "time-core"
454 | version = "0.1.2"
455 | source = "registry+https://github.com/rust-lang/crates.io-index"
456 | checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3"
457 |
458 | [[package]]
459 | name = "time-macros"
460 | version = "0.2.16"
461 | source = "registry+https://github.com/rust-lang/crates.io-index"
462 | checksum = "26197e33420244aeb70c3e8c78376ca46571bc4e701e4791c2cd9f57dcb3a43f"
463 | dependencies = [
464 | "time-core",
465 | ]
466 |
467 | [[package]]
468 | name = "tokio"
469 | version = "1.35.0"
470 | source = "registry+https://github.com/rust-lang/crates.io-index"
471 | checksum = "841d45b238a16291a4e1584e61820b8ae57d696cc5015c459c229ccc6990cc1c"
472 | dependencies = [
473 | "backtrace",
474 | "bytes",
475 | "libc",
476 | "mio",
477 | "num_cpus",
478 | "pin-project-lite",
479 | "signal-hook-registry",
480 | "windows-sys",
481 | ]
482 |
483 | [[package]]
484 | name = "unicode-ident"
485 | version = "1.0.12"
486 | source = "registry+https://github.com/rust-lang/crates.io-index"
487 | checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
488 |
489 | [[package]]
490 | name = "wasi"
491 | version = "0.11.0+wasi-snapshot-preview1"
492 | source = "registry+https://github.com/rust-lang/crates.io-index"
493 | checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
494 |
495 | [[package]]
496 | name = "winapi"
497 | version = "0.3.9"
498 | source = "registry+https://github.com/rust-lang/crates.io-index"
499 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
500 | dependencies = [
501 | "winapi-i686-pc-windows-gnu",
502 | "winapi-x86_64-pc-windows-gnu",
503 | ]
504 |
505 | [[package]]
506 | name = "winapi-i686-pc-windows-gnu"
507 | version = "0.4.0"
508 | source = "registry+https://github.com/rust-lang/crates.io-index"
509 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
510 |
511 | [[package]]
512 | name = "winapi-util"
513 | version = "0.1.6"
514 | source = "registry+https://github.com/rust-lang/crates.io-index"
515 | checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596"
516 | dependencies = [
517 | "winapi",
518 | ]
519 |
520 | [[package]]
521 | name = "winapi-x86_64-pc-windows-gnu"
522 | version = "0.4.0"
523 | source = "registry+https://github.com/rust-lang/crates.io-index"
524 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
525 |
526 | [[package]]
527 | name = "windows-sys"
528 | version = "0.48.0"
529 | source = "registry+https://github.com/rust-lang/crates.io-index"
530 | checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
531 | dependencies = [
532 | "windows-targets",
533 | ]
534 |
535 | [[package]]
536 | name = "windows-targets"
537 | version = "0.48.5"
538 | source = "registry+https://github.com/rust-lang/crates.io-index"
539 | checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
540 | dependencies = [
541 | "windows_aarch64_gnullvm",
542 | "windows_aarch64_msvc",
543 | "windows_i686_gnu",
544 | "windows_i686_msvc",
545 | "windows_x86_64_gnu",
546 | "windows_x86_64_gnullvm",
547 | "windows_x86_64_msvc",
548 | ]
549 |
550 | [[package]]
551 | name = "windows_aarch64_gnullvm"
552 | version = "0.48.5"
553 | source = "registry+https://github.com/rust-lang/crates.io-index"
554 | checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
555 |
556 | [[package]]
557 | name = "windows_aarch64_msvc"
558 | version = "0.48.5"
559 | source = "registry+https://github.com/rust-lang/crates.io-index"
560 | checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
561 |
562 | [[package]]
563 | name = "windows_i686_gnu"
564 | version = "0.48.5"
565 | source = "registry+https://github.com/rust-lang/crates.io-index"
566 | checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
567 |
568 | [[package]]
569 | name = "windows_i686_msvc"
570 | version = "0.48.5"
571 | source = "registry+https://github.com/rust-lang/crates.io-index"
572 | checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
573 |
574 | [[package]]
575 | name = "windows_x86_64_gnu"
576 | version = "0.48.5"
577 | source = "registry+https://github.com/rust-lang/crates.io-index"
578 | checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
579 |
580 | [[package]]
581 | name = "windows_x86_64_gnullvm"
582 | version = "0.48.5"
583 | source = "registry+https://github.com/rust-lang/crates.io-index"
584 | checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
585 |
586 | [[package]]
587 | name = "windows_x86_64_msvc"
588 | version = "0.48.5"
589 | source = "registry+https://github.com/rust-lang/crates.io-index"
590 | checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
591 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "ccanvas"
3 | version = "0.2.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tokio = { version = "1", features = [ "rt", "rt-multi-thread", "sync", "fs", "process" ]}
10 | serde = { version = "1", features = [ "derive" ] }
11 | serde_json = "1"
12 | termion = "2"
13 | async-trait = "0.1"
14 | nix = { version = "0.27", features = [ "signal" ] }
15 | libc = "0.2"
16 |
17 | log = { version = "0.4", optional = true}
18 | simplelog = { version = "0.12", optional = true}
19 | dirs = { version = "5.0", optional = true }
20 |
21 | [features]
22 | default = []
23 | log = ["dep:log", "dep:simplelog", "dep:dirs"]
24 |
25 | [profile.release]
26 | strip = true
27 | lto = true
28 | opt-level = 3
29 | panic = "abort"
30 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ccanvas
2 |
3 | ccanvas allows multiple programs to draw on the same terminal in an async/non-blocking manner. To create a ccanvas component, see [libccanvas](https://github.com/Siriusmart/libccanvas).
4 |
5 | > **ccanvas uses unix sockets**, which may not be available on windows.
6 |
7 | ## Showcase
8 |
9 | Click on the image for video.
10 |
11 | [](https://gmtex.siri.sh/fs/1/Dump/Showcases/ccanvas-snake.webm)
12 |
13 | [Source](https://github.com/Siriusmart/libccanvas/tree/master/examples/snake)
14 |
15 | ## Backstory
16 |
17 | The [**`youtube-tui`**](https://github.com/Siriusmart/youtube-tui/) was my first TUI project, one major issues is that the whole program freezes when waiting for server response of a video. This is because it uses a **blocking event loop** as so:
18 |
19 | 1. Render current state to screen.
20 | 2. Do something - such as loading a video.
21 | 3. Repeat.
22 |
23 | This is problematic if the task takes a long time to complete, as it blocks all incoming events, including pressing `q` which exit the TUI.
24 |
25 | At the same time I was also facing the unsolvable problem of inter-component communication, I hacked together a solution which utilises shared memory, but it was far from the ideal message-based communication.
26 |
27 | ## Goals
28 |
29 | - To create a TUI framework that is non-blocking by default.
30 | - To create a component based TUI framework, where each component is a separate program.
31 | - To create a component based TUI framework, where each component have the option to communicate with each other using messages, shared memory, or shared storage.
32 |
33 | ## Implementation
34 |
35 | ### Components
36 |
37 | ccanvas is structured into "components"
38 |
39 | - a ***space*** can contain any number of child components.
40 | - a ***process*** represents a real process running.
41 |
42 | > A space can focus on itself, or one child space.
43 |
44 | Each component is referenced by its unique identifying ***discriminator***, which is just a path of numbers, such as `/1/2/3/4`. `/1` is called the ***master space***.
45 |
46 | - New spaces can be created and new processes can be spawned in.
47 | - Any component can be ***dropped*** and removed.
48 | - To exit the canvas, call ***drop*** on `/1.`
49 |
50 | ### Events
51 |
52 | ccanvas receive "events" from 3 sources.
53 |
54 | - Terminal events - key presses, mouse click, resizes, etc.
55 | - Component requests - messages to be passed, render requests, etc.
56 | - Generated events - registering subscriptions, message broadcasts, etc.
57 |
58 | All 3 of these event sources are funnelled into a single ***event stream***, where they are handled by a non-blocking event loop, here's how it works:
59 |
60 | 1. Events enters the canvas through different sources.
61 | 2. All events are funnelled into a single ***event stream***.
62 | 3. All events are passed into the ***master space***.
63 |
64 | The space will then decide where should the event be passed to. First it will pass to all the processes subscribed to the event, and then it will pass to the ***focused space*** (if there is one).
65 |
66 | ## TODO
67 |
68 | One more feature needed before I work on a window manager component - list components in a space.
69 |
--------------------------------------------------------------------------------
/docs/assets/ccanvas-structure.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ccanvas/ccanvas_old/1b3b7a30722b7c7282a175560d6dc7446283527f/docs/assets/ccanvas-structure.png
--------------------------------------------------------------------------------
/docs/assets/ccanvas-structure.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
626 |
--------------------------------------------------------------------------------
/docs/assets/idea.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ccanvas/ccanvas_old/1b3b7a30722b7c7282a175560d6dc7446283527f/docs/assets/idea.png
--------------------------------------------------------------------------------
/docs/assets/idea.xcf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ccanvas/ccanvas_old/1b3b7a30722b7c7282a175560d6dc7446283527f/docs/assets/idea.xcf
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | pub mod structs;
2 | pub mod term;
3 | pub mod traits;
4 | pub mod values;
5 |
6 | pub use structs::Error;
7 |
--------------------------------------------------------------------------------
/src/main.rs:
--------------------------------------------------------------------------------
1 | use std::{collections::BTreeMap, sync::Arc, time::Duration};
2 |
3 | use ccanvas::{
4 | structs::Space,
5 | term::{commands, enter, exit, init},
6 | };
7 | use tokio::runtime::Runtime;
8 |
9 | fn main() {
10 | let commands = commands();
11 |
12 | let runtime = Runtime::new().unwrap();
13 |
14 | runtime.block_on(init());
15 |
16 | // creates new master space
17 | let master = Arc::new(runtime.block_on(Space::new("master".to_string())));
18 | let handle = runtime.spawn(Space::listen(master.clone()));
19 |
20 | for command in commands {
21 | if let Err(e) = runtime.block_on(master.spawn(
22 | command[0].clone(),
23 | command[1].clone(),
24 | command[2..].to_vec(),
25 | BTreeMap::default(),
26 | )) {
27 | // there is no reason to continue if spawning the component failed
28 | // might be a type, or whatever
29 | eprintln!("{e}");
30 | runtime.shutdown_timeout(Duration::from_secs(0));
31 | return;
32 | }
33 | }
34 |
35 | enter();
36 | runtime.block_on(handle).unwrap();
37 | runtime.block_on(exit());
38 |
39 | // get rid of everyting, kills all processes, etc
40 | runtime.shutdown_timeout(Duration::from_secs(0));
41 | }
42 |
--------------------------------------------------------------------------------
/src/structs/component/discriminator.rs:
--------------------------------------------------------------------------------
1 | use std::sync::Mutex;
2 |
3 | use serde::{Deserialize, Serialize};
4 | use tokio::sync::OnceCell;
5 |
6 | static DISCRIM: OnceCell> = OnceCell::const_new_with(Mutex::new(0));
7 | /// get a unique discriminator chunk
8 | pub fn discrim() -> u32 {
9 | let mut discrim = DISCRIM.get().unwrap().lock().unwrap();
10 | *discrim += 1;
11 | *discrim
12 | }
13 |
14 | /// a unique path id for every component
15 | #[derive(Default, PartialEq, Eq, Clone, Debug, Serialize, Deserialize, Hash)]
16 | pub struct Discriminator(pub Vec);
17 |
18 | impl Discriminator {
19 | /// create new child component
20 | pub fn new_child(&self) -> Self {
21 | let mut new_discrim = self.0.to_vec();
22 | new_discrim.push(discrim());
23 | Self(new_discrim)
24 | }
25 |
26 | /// returns internal vec
27 | pub fn as_vec(&self) -> &Vec {
28 | &self.0
29 | }
30 |
31 | /// check if one component is a child of another
32 | pub fn is_parent_of(&self, other: &Self) -> bool {
33 | other.0.starts_with(&self.0) && self.0.len() < other.0.len()
34 | }
35 |
36 | /// truncate path length
37 | pub fn truncate(mut self, len: usize) -> Self {
38 | self.0.truncate(len);
39 | self
40 | }
41 |
42 | /// return immediate chaild to pass to
43 | pub fn immediate_child(&self, child: Self) -> Option {
44 | self.is_parent_of(&child)
45 | .then(|| child.truncate(self.0.len() + 1))
46 | }
47 |
48 | /// returns the immediate parent
49 | /// None if component is top level [1]
50 | pub fn immediate_parent(self) -> Option {
51 | (!self.0.is_empty()).then(|| {
52 | let len = self.0.len();
53 | self.truncate(len - 1)
54 | })
55 | }
56 |
57 | /// returns discriminator of master space
58 | pub fn master() -> Self {
59 | Self(vec![1])
60 | }
61 |
62 | /// check if discriminator is empty (would be invalid)
63 | pub fn is_empty(&self) -> bool {
64 | self.0.is_empty()
65 | }
66 |
67 | /// check if self starts with other
68 | pub fn starts_with(&self, other: &Self) -> bool {
69 | self.0.starts_with(&other.0)
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/structs/component/focus.rs:
--------------------------------------------------------------------------------
1 | use super::Discriminator;
2 |
3 | /// if the space is focusing on itself or a child subspace
4 | #[derive(PartialEq, Eq, Clone)]
5 | pub enum Focus {
6 | /// render self, dont pass events further down
7 | This,
8 | /// render child, pass events to it
9 | Children(Discriminator),
10 | }
11 |
12 | impl Default for Focus {
13 | fn default() -> Self {
14 | Self::This
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/structs/component/mod.rs:
--------------------------------------------------------------------------------
1 | mod discriminator;
2 | pub use discriminator::*;
3 |
4 | mod focus;
5 | pub use focus::*;
6 |
7 | mod passes;
8 | pub use passes::*;
9 |
10 | mod process;
11 | pub use process::*;
12 |
13 | mod space;
14 | pub use space::*;
15 |
16 | mod subscription;
17 | pub use subscription::*;
18 |
19 | mod subscriptions;
20 | pub use subscriptions::*;
21 |
--------------------------------------------------------------------------------
/src/structs/component/passes.rs:
--------------------------------------------------------------------------------
1 | use std::{
2 | cmp::Ordering,
3 | collections::{hash_map::Entry, HashMap},
4 | };
5 |
6 | use super::{Discriminator, Subscription};
7 |
8 | /// a single subscription item
9 | #[derive(Eq, Clone, Debug)]
10 | pub struct PassItem {
11 | /// 0 is highest
12 | /// None is lowest
13 | /// if there are clashes, first entry will recieve the signal first
14 | priority: Option,
15 | /// discrim of process
16 | discrim: Discriminator,
17 | }
18 |
19 | impl PassItem {
20 | /// get discrim of self
21 | pub fn discrim(&self) -> &Discriminator {
22 | &self.discrim
23 | }
24 |
25 | /// return priority of self
26 | pub fn priority(&self) -> Option {
27 | self.priority
28 | }
29 |
30 | /// convenience function to create new self
31 | pub fn new(discrim: Discriminator, priority: Option) -> Self {
32 | Self { priority, discrim }
33 | }
34 | }
35 |
36 | impl PartialEq for PassItem {
37 | fn eq(&self, other: &Self) -> bool {
38 | self.discrim == other.discrim
39 | }
40 | }
41 |
42 | impl PartialOrd for PassItem {
43 | fn partial_cmp(&self, other: &Self) -> Option {
44 | Some(self.cmp(other))
45 | }
46 | }
47 |
48 | impl Ord for PassItem {
49 | // to make lower numbers come first, Nones come last
50 | fn cmp(&self, other: &Self) -> std::cmp::Ordering {
51 | match (self.priority, other.priority) {
52 | (a, b) if a == b => Ordering::Equal,
53 | (None, None) => Ordering::Equal,
54 | (Some(_), None) => Ordering::Less,
55 | (None, Some(_)) => Ordering::Greater,
56 | (Some(a), Some(b)) => a.cmp(&b),
57 | }
58 | }
59 | }
60 |
61 | /// stores which subspaces/subprocesses have subscribed to events
62 | /// and pass events only to them in order of priority
63 | #[derive(Default)]
64 | pub struct Passes {
65 | /// real content of the struct
66 | subscriptions: HashMap>,
67 | }
68 |
69 | impl Passes {
70 | /// add pass item
71 | pub fn subscribe(&mut self, subscription: Subscription, item: PassItem) {
72 | if let Subscription::Multiple { subs } = subscription {
73 | subs.into_iter().for_each(|(sub, priority)| {
74 | self.subscribe(
75 | sub,
76 | PassItem {
77 | priority,
78 | discrim: item.discrim.clone(),
79 | },
80 | )
81 | });
82 | return;
83 | }
84 |
85 | let items = self.subscriptions.entry(subscription).or_default();
86 |
87 | // remove duplicates
88 | if let Some(index) = items.iter().position(|x| x.discrim() == item.discrim()) {
89 | items.remove(index);
90 | }
91 |
92 | // put it in the right place
93 | // according to priority
94 | for i in 0..items.len() {
95 | if items[i].priority > item.priority {
96 | items.insert(i, item);
97 | return;
98 | }
99 | }
100 |
101 | items.push(item);
102 | }
103 |
104 | /// remove pass item
105 | pub fn unsubscribe(&mut self, subscription: Subscription, discrim: &Discriminator) -> bool {
106 | let mut items = if let Entry::Occupied(items) = self.subscriptions.entry(subscription) {
107 | items
108 | } else {
109 | return false;
110 | };
111 |
112 | if let Some(index) = items.get().iter().position(|x| x.discrim() == discrim) {
113 | items.get_mut().remove(index);
114 | if items.get().is_empty() {
115 | items.remove_entry();
116 | }
117 | return true;
118 | }
119 |
120 | false
121 | }
122 |
123 | /// unsubscribe all subscriptions of that component
124 | /// used when the component is to be dropped
125 | pub fn unsub_all(&mut self, discrim: &Discriminator) {
126 | let mut to_drop = Vec::new();
127 | self.subscriptions.iter_mut().for_each(|(key, items)| {
128 | if let Some(index) = items.iter().position(|x| x.discrim() == discrim) {
129 | items.remove(index);
130 | if items.is_empty() {
131 | to_drop.push(key.clone())
132 | }
133 | }
134 | });
135 |
136 | to_drop.iter().for_each(|key| {
137 | let _ = self.subscriptions.remove(key);
138 | })
139 | }
140 |
141 | /// list subscribers of all the subscriptions specified
142 | /// sorted + no duplicates
143 | pub fn subscribers(&self, subscription: &[Subscription]) -> Vec {
144 | let default = Vec::default(); // wow im so good at going around ownership checks
145 | let mut subscribers = subscription
146 | .iter()
147 | .flat_map(|sub| self.subscriptions.get(sub).unwrap_or(&default))
148 | .collect::>();
149 |
150 | // they are now according to priority
151 | // but there may be duplicates
152 | subscribers.sort();
153 |
154 | // only take the highest priority
155 | // if a component has multiple subscriptions on this event
156 | let mut out = Vec::new();
157 | subscribers.into_iter().for_each(|sub| {
158 | if !out.contains(sub) {
159 | // if its error
160 | // it means its not there
161 | // this works because it is sorted at all times
162 | out.push(sub.to_owned())
163 | }
164 | });
165 |
166 | out
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/src/structs/component/process.rs:
--------------------------------------------------------------------------------
1 | use std::{
2 | collections::{hash_map::Entry, BTreeMap, HashMap},
3 | env,
4 | ffi::OsString,
5 | io::{Read, Write},
6 | os::unix::net::{UnixListener, UnixStream},
7 | process::Stdio,
8 | sync::Arc,
9 | };
10 |
11 | use async_trait::async_trait;
12 | use tokio::{
13 | process::{Child, Command},
14 | sync::{
15 | mpsc::{self, UnboundedSender},
16 | oneshot, Mutex, OnceCell,
17 | },
18 | task::JoinHandle,
19 | };
20 |
21 | use crate::{traits::Component, values::FOCUSED};
22 |
23 | use crate::structs::*;
24 |
25 | /// single runnable process
26 | pub struct Process {
27 | /// name of the current process
28 | label: String,
29 |
30 | /// unique identifier of the current process
31 | discrim: Discriminator,
32 |
33 | /// data storage for self
34 | pool: Arc>,
35 |
36 | /// shared storage folder for self
37 | storage: Storage,
38 |
39 | /// command that was ran
40 | command: Vec,
41 |
42 | /// process handle
43 | child: Arc>,
44 |
45 | /// handle to the task responsible for listening to requests
46 | listener: JoinHandle<()>,
47 |
48 | /// handle to the task responsible for responding
49 | responder: JoinHandle<()>,
50 |
51 | /// path to response socket
52 | res: UnboundedSender,
53 |
54 | /// event confirm recieve senders
55 | confirm_handles: Arc>>>,
56 |
57 | /// channel suppressors
58 | suppressors: Arc>,
59 | }
60 |
61 | impl PartialEq for Process {
62 | fn eq(&self, other: &Self) -> bool {
63 | self.discrim == other.discrim
64 | }
65 | }
66 |
67 | static ENVS: OnceCell> = OnceCell::const_new();
68 |
69 | impl Process {
70 | /// spawns a new process with command
71 | pub async fn spawn(
72 | label: String,
73 | parent: &Discriminator,
74 | command: String,
75 | args: Vec,
76 | env: BTreeMap,
77 | ) -> Result {
78 | let discrim = parent.new_child();
79 | let storage = Storage::new(&discrim).await;
80 |
81 | // a new sender is pushed to the map whenever something is sent to the component
82 | // the sender returns a boolean, if true then the event will not be captured, vice versa
83 | // the important part is that this will hold the process until a confirmation message is
84 | // recieved
85 | let confirm_handles: Arc>>> =
86 | Arc::new(Mutex::new(HashMap::default()));
87 |
88 | // the component should send requests to this path
89 | let socket_path = storage.path().join("requests.sock");
90 | Storage::remove_if_exist(&socket_path).await.unwrap();
91 | // creates a socket and listens to it
92 | let socket = tokio::task::block_in_place(|| UnixListener::bind(socket_path).unwrap());
93 | let child = Arc::new(Mutex::new(
94 | Command::new(&command)
95 | .envs(
96 | ENVS.get_or_init(|| async {
97 | tokio::task::spawn_blocking(|| env::vars_os().collect::>())
98 | .await
99 | .unwrap()
100 | })
101 | .await
102 | .clone()
103 | .into_iter(),
104 | )
105 | .envs(env.iter())
106 | .envs(std::env::vars_os())
107 | .env("CCANVAS_COMPONENT", "1")
108 | .kill_on_drop(true)
109 | .args(&args)
110 | .current_dir(storage.path())
111 | .stdin(Stdio::null())
112 | .stdout(Stdio::null())
113 | .stderr(Stdio::null())
114 | .spawn()?,
115 | ));
116 |
117 | let (responder_send, mut responder_recv): (UnboundedSender, _) =
118 | mpsc::unbounded_channel();
119 |
120 | let (set_socket_send, set_socket_recv): (oneshot::Sender<()>, _) = oneshot::channel();
121 |
122 | // the responder task recieve Response
123 | // serialise it and send it to the component, if it specified a socket to send to
124 | let responder = {
125 | let confirm_handles = confirm_handles.clone();
126 | let child = child.clone();
127 | let discrim = discrim.clone();
128 | tokio::spawn(async move {
129 | // by default there is no socket
130 | let mut socket = None;
131 | let mut socket_confirm = Some(set_socket_send);
132 |
133 | while let Some(res) = responder_recv.recv().await {
134 | let confirm_handles = confirm_handles.clone();
135 | // this special "response" is recieved when a SetSocket request
136 | // is sent by the component
137 | if let ResponseContent::SetSocket(path) = res.content() {
138 | socket = Some(path.to_owned());
139 | if socket_confirm.is_some() {
140 | let _ = std::mem::take(&mut socket_confirm).unwrap().send(());
141 | }
142 | continue;
143 | }
144 |
145 | // only send a message when a socket is specified
146 | if let Some(socket) = &socket {
147 | #[cfg(feature = "log")]
148 | log::info!("{discrim:?} sent {res:?}");
149 | let socket = socket.clone();
150 | let child = child.clone();
151 | let discrim = discrim.clone();
152 | tokio::spawn(async move {
153 | // check if the child process has crashed
154 | if child.lock().await.try_wait().unwrap().is_some() {
155 | Event::send(Event::RequestPacket(
156 | Packet::new(Request::new(
157 | discrim.clone().immediate_parent().unwrap(),
158 | RequestContent::Drop {
159 | // if true, then tell the parent space to drop it
160 | discrim: Some(discrim),
161 | },
162 | ))
163 | .0,
164 | ))
165 | }
166 |
167 | #[cfg(feature = "log")]
168 | log::debug!("sent {res:?}");
169 |
170 | if let Ok(mut stream) = UnixStream::connect(socket) {
171 | stream
172 | .write_all(serde_json::to_vec(&res).unwrap().as_slice())
173 | .unwrap();
174 | stream.flush().unwrap();
175 | } else {
176 | // if send failed, it is impossible to get a response message
177 | // so manually remove it to trigger an undelivered response
178 | confirm_handles.lock().await.remove(&res.id());
179 | }
180 | });
181 | }
182 | }
183 | })
184 | };
185 |
186 | // the listener listens to event and handles it, that all
187 | let listener = {
188 | let discrim = discrim.clone();
189 | let confirm_handles = confirm_handles.clone();
190 | let responder = responder_send.clone();
191 | let storage = storage.clone();
192 | tokio::spawn(async move {
193 | let mut incoming = socket.incoming();
194 | while let Some(stream) = tokio::task::block_in_place(|| incoming.next()) {
195 | // give up if the stream is errorneous
196 | let mut stream = match stream {
197 | Ok(stream) => stream,
198 | Err(_) => continue,
199 | };
200 |
201 | let mut msg = String::new();
202 | // another chance to give up
203 | if stream.read_to_string(&mut msg).is_err() {
204 | continue;
205 | }
206 |
207 | // a third chance to give up
208 | let mut request: Request = match serde_json::from_str(&msg) {
209 | Ok(req) => req,
210 | Err(_) => continue,
211 | };
212 |
213 | #[cfg(feature = "log")]
214 | log::info!("{discrim:?} recieved {request:?}");
215 |
216 | // modify requests
217 | match request.content_mut() {
218 | RequestContent::Watch { label } => {
219 | // convert a Watch into a WatchInternal
220 | *request.content_mut() = RequestContent::WatchInternal(WatchInternal {
221 | label: std::mem::take(label),
222 | sender: responder.clone(),
223 | watcher: discrim.clone(),
224 | })
225 | }
226 | RequestContent::ConfirmRecieve { id, pass } => {
227 | // if the request is a confirmation to a response
228 | // then confirm the response and unblock the self.pass() thing
229 | // by sending a message
230 | let confirm_handles = confirm_handles.clone();
231 | let id = *id;
232 | let pass = *pass;
233 | tokio::spawn(async move {
234 | if let Entry::Occupied(entry) =
235 | confirm_handles.lock().await.entry(id)
236 | {
237 | let _ = entry.remove_entry().1.send(pass);
238 | }
239 | });
240 | continue;
241 | }
242 | RequestContent::Subscribe {
243 | channel,
244 | priority,
245 | component: _,
246 | } => {
247 | // first add the channel to self as a record
248 | // and send a register event to the master space
249 | // which is eventually get sent to the parent space
250 | // and get added as into the passes
251 | *request.content_mut() = RequestContent::Subscribe {
252 | channel: channel.clone(),
253 | priority: *priority,
254 | component: Some(discrim.clone()),
255 | };
256 | *request.target_mut() = discrim.clone().immediate_parent().unwrap();
257 | let _ = responder.send(Response::new_with_request(
258 | ResponseContent::Success {
259 | content: ResponseSuccess::SubscribeAdded,
260 | },
261 | *request.id(),
262 | ));
263 | }
264 | RequestContent::Unsubscribe {
265 | channel,
266 | component: _,
267 | } => {
268 | // first add the channel to self as a record
269 | // and send a register event to the master space
270 | // which is eventually get sent to the parent space
271 | // and get added as into the passes
272 | *request.content_mut() = RequestContent::Unsubscribe {
273 | channel: channel.clone(),
274 | component: Some(discrim.clone()),
275 | };
276 | *request.target_mut() = discrim.clone().immediate_parent().unwrap();
277 | }
278 | RequestContent::SetSocket { path } => {
279 | // these requests goes to self
280 | let _ = responder.send(Response::new_with_request(
281 | ResponseContent::SetSocket(storage.path().join(path)),
282 | *request.id(),
283 | ));
284 |
285 | let _ = responder.send(Response::new_with_request(
286 | ResponseContent::Success {
287 | // this can never fail
288 | content: ResponseSuccess::ListenerSet {
289 | discrim: discrim.clone(),
290 | },
291 | },
292 | *request.id(), // this is a response
293 | ));
294 | continue;
295 | }
296 | RequestContent::GetState { label } => {
297 | // get state of self
298 | // will implement getting state of other components
299 | // TODO
300 | let val = match label {
301 | StateValue::Focused => {
302 | serde_json::to_value(FOCUSED.get().unwrap()).unwrap()
303 | }
304 | StateValue::IsFocused => serde_json::to_value(
305 | FOCUSED.get().unwrap().lock().unwrap().starts_with(&discrim),
306 | )
307 | .unwrap(),
308 | StateValue::TermSize => {
309 | #[derive(serde::Serialize)]
310 | struct TermSize {
311 | x: u32,
312 | y: u32,
313 | }
314 | let (x, y) = termion::terminal_size().unwrap();
315 | serde_json::to_value(TermSize {
316 | x: x as u32,
317 | y: y as u32,
318 | })
319 | .unwrap()
320 | }
321 | StateValue::WorkingDir => {
322 | serde_json::to_value(env::current_dir().unwrap()).unwrap()
323 | }
324 | };
325 |
326 | let _ = responder.send(Response::new_with_request(
327 | ResponseContent::Success {
328 | content: ResponseSuccess::Value { value: val },
329 | },
330 | *request.id(),
331 | ));
332 |
333 | continue;
334 | }
335 | RequestContent::Drop { discrim: to_drop } => {
336 | // this goes to parent space
337 | let to_drop = to_drop.as_ref().unwrap_or(&discrim).clone();
338 | *request.target_mut() = to_drop.clone().immediate_parent().unwrap();
339 | *request.content_mut() = RequestContent::Drop {
340 | discrim: Some(to_drop),
341 | };
342 | }
343 | RequestContent::Render { .. } => {
344 | // this goes to master space
345 | *request.target_mut() = Discriminator::master()
346 | }
347 | RequestContent::Spawn { .. } => {
348 | // this goes to master space only when target is not specified
349 | if request.target().is_empty() {
350 | *request.target_mut() = discrim.clone().immediate_parent().unwrap();
351 | }
352 | }
353 | RequestContent::Unwatch { watcher, .. } => *watcher = discrim.clone(),
354 | // mark self as sender
355 | RequestContent::Message { sender, target, .. } => {
356 | *sender = discrim.clone();
357 |
358 | // or else it will crash for this bad request
359 | if target.is_empty() {
360 | *target = Discriminator::master()
361 | }
362 | }
363 | RequestContent::NewSpace { .. }
364 | | RequestContent::FocusAt
365 | | RequestContent::Suppress { .. }
366 | | RequestContent::Unsuppress { .. }
367 | | RequestContent::SetEntry { .. }
368 | | RequestContent::RemoveEntry { .. }
369 | | RequestContent::GetEntry { .. } => {}
370 | RequestContent::WatchInternal(_) => unreachable!("boom"),
371 | }
372 |
373 | let responder = responder.clone();
374 | tokio::task::spawn(async move {
375 | // otherwise, the request gets sended to the master space
376 | // and starts propagating downwards
377 | let res = request.send().await;
378 |
379 | // send a response to the request
380 | // but requires no confirmation
381 | // because the response is already a sort of confirmation
382 | let _ = responder.send(res);
383 | });
384 | }
385 | })
386 | };
387 |
388 | set_socket_recv.await.unwrap();
389 |
390 | Ok(Self {
391 | child,
392 | label,
393 | storage,
394 | pool: Arc::new(Mutex::new(Pool::new(discrim.clone()))),
395 | discrim,
396 | command: [command].into_iter().chain(args).collect(),
397 | listener,
398 | responder,
399 | res: responder_send,
400 | confirm_handles,
401 | suppressors: Arc::new(Mutex::new(Suppressors::default())),
402 | })
403 | }
404 |
405 | pub async fn handle(&self, packet: &mut Packet) {
406 | match packet.get().content() {
407 | RequestContent::Suppress { channel, priority } => {
408 | let _ = packet.respond(Response::new_with_request(
409 | ResponseContent::Success {
410 | content: ResponseSuccess::Suppressed {
411 | id: self
412 | .suppressors
413 | .lock()
414 | .await
415 | .insert(channel.clone(), *priority),
416 | },
417 | },
418 | *packet.get().id(),
419 | ));
420 | }
421 | RequestContent::Unsuppress { channel, id } => {
422 | self.suppressors.lock().await.remove(channel.clone(), *id);
423 | let _ = packet.respond(Response::new_with_request(
424 | ResponseContent::Success {
425 | content: ResponseSuccess::Unsuppressed,
426 | },
427 | *packet.get().id(),
428 | ));
429 | }
430 | RequestContent::RemoveEntry { label } => {
431 | self.pool.lock().await.remove(label, &self.discrim);
432 | let _ = packet.respond(Response::new_with_request(
433 | ResponseContent::Success {
434 | content: ResponseSuccess::RemovedValue,
435 | },
436 | *packet.get().id(),
437 | ));
438 | }
439 | RequestContent::Message {
440 | content,
441 | sender,
442 | target,
443 | tag,
444 | } => {
445 | let mut event = Event::Message {
446 | sender: sender.clone(),
447 | target: target.clone(),
448 | content: content.clone(),
449 | tag: tag.clone(),
450 | };
451 | let _ = packet.respond(Response::new_with_request(
452 | ResponseContent::Success {
453 | content: ResponseSuccess::MessageDelivered,
454 | },
455 | *packet.get().id(),
456 | ));
457 | // unwraps the request, and pass to self as an event
458 | // which will then get sent to the client as a normal event
459 | let _ = self.pass(&mut event, None).await;
460 | }
461 | // spawn should be passed to spaces, no processes
462 | RequestContent::Spawn { .. } => {
463 | let _ = packet.respond(Response::new_with_request(
464 | ResponseContent::Undelivered,
465 | *packet.get().id(),
466 | ));
467 | }
468 | RequestContent::GetEntry { label } => {
469 | // just return an entry from pool, nothing special
470 | let res = match self.pool.lock().await.get(label) {
471 | Some(value) => ResponseContent::Success {
472 | content: ResponseSuccess::Value { value },
473 | },
474 | None => ResponseContent::Error {
475 | content: ResponseError::EntryNotFound,
476 | },
477 | };
478 | let _ = packet.respond(Response::new_with_request(res, *packet.get().id()));
479 | }
480 | RequestContent::SetEntry { label, value } => {
481 | // set an entry, this never fails
482 | self.pool.lock().await.set(label, value.clone());
483 | let _ = packet.respond(Response::new_with_request(
484 | ResponseContent::Success {
485 | content: ResponseSuccess::ValueSet,
486 | },
487 | *packet.get().id(),
488 | ));
489 | }
490 | RequestContent::WatchInternal(watch) => {
491 | // add a watcher to an entry
492 | self.pool.lock().await.watch(
493 | watch.label.clone(),
494 | watch.sender.clone(),
495 | watch.watcher.clone(),
496 | );
497 | let _ = packet.respond(Response::new_with_request(
498 | ResponseContent::Success {
499 | content: ResponseSuccess::Watching,
500 | },
501 | *packet.get().id(),
502 | ));
503 | }
504 | RequestContent::Unwatch { label, watcher } => {
505 | // remove watcher from entry
506 | let res = if self
507 | .pool
508 | .lock()
509 | .await
510 | .unwatch(label, watcher, self.discrim.clone())
511 | {
512 | ResponseContent::Success {
513 | content: ResponseSuccess::Unwatched,
514 | }
515 | } else {
516 | ResponseContent::Error {
517 | content: ResponseError::EntryNotFound,
518 | }
519 | };
520 | let _ = packet.respond(Response::new_with_request(res, *packet.get().id()));
521 | }
522 | // confirmreceive gets filtered out and handles in the listener loop
523 | // so we will never get it
524 | RequestContent::ConfirmRecieve { .. }
525 | | RequestContent::Watch { .. }
526 | | RequestContent::Unsubscribe { .. }
527 | | RequestContent::Drop { .. }
528 | | RequestContent::Subscribe { .. }
529 | | RequestContent::SetSocket { .. }
530 | | RequestContent::NewSpace { .. }
531 | | RequestContent::FocusAt
532 | | RequestContent::GetState { .. }
533 | | RequestContent::Render { .. } => {
534 | unreachable!("not a real request")
535 | }
536 | }
537 | }
538 |
539 | /// send a response and wait for confirmation
540 | pub async fn send_event(&self, resp: Response) -> oneshot::Receiver {
541 | let (tx, rx) = oneshot::channel();
542 | self.confirm_handles.lock().await.insert(resp.id(), tx);
543 | let _ = self.res.send(resp);
544 | rx
545 | }
546 |
547 | pub async fn suppress_level(&self, channels: &[Subscription]) -> Option {
548 | self.suppressors.lock().await.suppress_level(channels)
549 | }
550 | }
551 |
552 | #[async_trait]
553 | impl Component for Process {
554 | fn label(&self) -> &str {
555 | &self.label
556 | }
557 |
558 | fn discrim(&self) -> &Discriminator {
559 | &self.discrim
560 | }
561 |
562 | fn storage(&self) -> &Storage {
563 | &self.storage
564 | }
565 |
566 | async fn pass(&self, event: &mut Event, _suppress_level: Option) -> Unevaluated {
567 | #[cfg(feature = "log")]
568 | log::debug!("{:?} got event {event:?}", self.discrim);
569 | // requestpacket is a request, not an event in a real sense
570 | // and it doesnt serialise into EventSerde either
571 | // so best just handle it out and filter it first
572 | if let Event::RequestPacket(packet) = event {
573 | self.handle(packet).await;
574 | return false.into();
575 | }
576 |
577 | let resp = Response::new(ResponseContent::Event {
578 | content: EventSerde::from_event(event),
579 | });
580 |
581 | let rx = self.send_event(resp).await;
582 | // dont block
583 | // or else it will keep parent.processes locked
584 | Unevaluated::Unevaluated(tokio::spawn(async move { rx.await.unwrap_or(true) }))
585 | }
586 | }
587 |
588 | impl Drop for Process {
589 | fn drop(&mut self) {
590 | self.responder.abort();
591 | self.listener.abort();
592 | }
593 | }
594 |
--------------------------------------------------------------------------------
/src/structs/component/space.rs:
--------------------------------------------------------------------------------
1 | use std::collections::BTreeMap;
2 | use std::error::Error;
3 | use std::sync::Arc;
4 |
5 | use async_trait::async_trait;
6 | use tokio::sync::Mutex;
7 |
8 | use crate::traits::Component;
9 |
10 | use crate::structs::*;
11 | use crate::values::{FOCUSED, SCREEN};
12 |
13 | /// the basic unit of display
14 | pub struct Space {
15 | /// name of the current space
16 | label: String,
17 |
18 | /// unique identifier of the current space - a "path" of u32s
19 | discrim: Discriminator,
20 |
21 | /// data storage for children
22 | pool: Arc>,
23 |
24 | /// shared storage folder for space children
25 | storage: Storage,
26 |
27 | /// spaces the current space contains
28 | subspaces: Arc>>,
29 |
30 | /// currently in use space, could be self or children
31 | focus: Arc>,
32 |
33 | /// process event subscriptions in this space
34 | passes: Arc>,
35 |
36 | /// process pool
37 | processes: Arc>>,
38 |
39 | /// channel suppressors
40 | suppressors: Arc>,
41 | }
42 |
43 | impl Space {
44 | pub async fn new(label: String) -> Self {
45 | Self::new_with_parent(label, &Discriminator::default()).await
46 | }
47 |
48 | /// create new self with parent discriminator
49 | async fn new_with_parent(label: String, parent_discrim: &Discriminator) -> Self {
50 | let discrim = parent_discrim.new_child();
51 | Self {
52 | storage: Storage::new(&discrim).await,
53 | label,
54 | pool: Arc::new(Mutex::new(Pool::new(discrim.clone()))),
55 | discrim,
56 | subspaces: Arc::new(Mutex::new(Collection::default())),
57 | focus: Arc::new(Mutex::new(Focus::default())),
58 | passes: Arc::new(Mutex::new(Passes::default())),
59 | processes: Arc::new(Mutex::new(Collection::default())),
60 | suppressors: Arc::new(Mutex::new(Suppressors::default())),
61 | }
62 | }
63 |
64 | /// start listening to all events, only the top level,
65 | /// "master" space should do this
66 | pub async fn listen(arc: Arc) {
67 | let mut listener = Event::start();
68 |
69 | while let Some(mut event) = listener.recv().await {
70 | // drop for quitting the entire application
71 | if let Event::RequestPacket(req) = &mut event {
72 | if req.get().content()
73 | == &(RequestContent::Drop {
74 | discrim: Some(Discriminator(vec![1])),
75 | })
76 | && req.get().target().0.is_empty()
77 | {
78 | return;
79 | }
80 | }
81 |
82 | let arc = arc.clone();
83 | // pass the event to master space
84 | tokio::spawn(async move {
85 | arc.pass(&mut event, None).await;
86 | });
87 | }
88 | }
89 |
90 | /// insert a new process
91 | pub async fn spawn(
92 | &self,
93 | label: String,
94 | command: String,
95 | args: Vec,
96 | env: BTreeMap,
97 | ) -> Result<(), Box> {
98 | self.processes
99 | .lock()
100 | .await
101 | .insert(Process::spawn(label, &self.discrim, command, args, env).await?);
102 | Ok(())
103 | }
104 | }
105 |
106 | #[async_trait]
107 | impl Component for Space {
108 | fn label(&self) -> &str {
109 | &self.label
110 | }
111 |
112 | fn discrim(&self) -> &Discriminator {
113 | &self.discrim
114 | }
115 |
116 | fn storage(&self) -> &Storage {
117 | &self.storage
118 | }
119 |
120 | async fn pass(&self, event: &mut Event, suppress_level: Option) -> Unevaluated {
121 | #[cfg(feature = "log")]
122 | log::debug!("{:?} got event {event:?}", self.discrim);
123 | match event {
124 | // if the target is self
125 | Event::RequestPacket(req) if req.get().target() == self.discrim() => {
126 | match req.get().content() {
127 | RequestContent::Suppress { channel, priority } => {
128 | let _ = req.respond(Response::new_with_request(
129 | ResponseContent::Success {
130 | content: ResponseSuccess::Suppressed {
131 | id: self
132 | .suppressors
133 | .lock()
134 | .await
135 | .insert(channel.clone(), *priority),
136 | },
137 | },
138 | *req.get().id(),
139 | ));
140 | }
141 | RequestContent::Unsuppress { channel, id } => {
142 | self.suppressors.lock().await.remove(channel.clone(), *id);
143 | let _ = req.respond(Response::new_with_request(
144 | ResponseContent::Success {
145 | content: ResponseSuccess::Unsuppressed,
146 | },
147 | *req.get().id(),
148 | ));
149 | }
150 | RequestContent::RemoveEntry { label } => {
151 | self.pool.lock().await.remove(label, &self.discrim);
152 | let _ = req.respond(Response::new_with_request(
153 | ResponseContent::Success {
154 | content: ResponseSuccess::RemovedValue,
155 | },
156 | *req.get().id(),
157 | ));
158 | }
159 | RequestContent::Unwatch { label, watcher } => {
160 | // remove watche from pool entry
161 | let res =
162 | if self
163 | .pool
164 | .lock()
165 | .await
166 | .unwatch(label, watcher, self.discrim.clone())
167 | {
168 | ResponseContent::Success {
169 | content: ResponseSuccess::Unwatched,
170 | }
171 | } else {
172 | ResponseContent::Error {
173 | content: ResponseError::EntryNotFound,
174 | }
175 | };
176 | let _ = req.respond(Response::new_with_request(res, *req.get().id()));
177 | }
178 | RequestContent::SetEntry { label, value } => {
179 | // set value of a pool entry
180 | // this never fails
181 | self.pool.lock().await.set(label, value.clone());
182 | let _ = req.respond(Response::new_with_request(
183 | ResponseContent::Success {
184 | content: ResponseSuccess::ValueSet,
185 | },
186 | *req.get().id(),
187 | ));
188 | }
189 | RequestContent::WatchInternal(watch) => {
190 | // add a watch item
191 | self.pool.lock().await.watch(
192 | watch.label.clone(),
193 | watch.sender.clone(),
194 | watch.watcher.clone(),
195 | );
196 | let _ = req.respond(Response::new_with_request(
197 | ResponseContent::Success {
198 | content: ResponseSuccess::Watching,
199 | },
200 | *req.get().id(),
201 | ));
202 | }
203 | RequestContent::GetEntry { label } => {
204 | let res = match self.pool.lock().await.get(label) {
205 | Some(value) => ResponseContent::Success {
206 | content: ResponseSuccess::Value { value },
207 | },
208 | None => ResponseContent::Error {
209 | content: ResponseError::EntryNotFound,
210 | },
211 | };
212 | let _ = req.respond(Response::new_with_request(res, *req.get().id()));
213 | }
214 | RequestContent::FocusAt => {
215 | // switch focus to that space, and only that space
216 | #[cfg(feature = "log")]
217 | log::debug!("{:?} locking focus", self.discrim);
218 | let mut focus = self.focus.lock().await;
219 | #[cfg(feature = "log")]
220 | log::debug!("{:?} locked focus", self.discrim);
221 | if let Focus::Children(discrim) = &*focus {
222 | #[cfg(feature = "log")]
223 | log::debug!("{:?} locking subspaces", self.discrim);
224 | self.subspaces
225 | .lock()
226 | .await
227 | .find_by_discrim(discrim)
228 | .unwrap()
229 | .pass(&mut Event::Unfocus, None)
230 | .await;
231 | #[cfg(feature = "log")]
232 | log::debug!("{:?} locked subspaces", self.discrim);
233 | #[cfg(feature = "log")]
234 | log::debug!("{:?} unlocked subspaces", self.discrim);
235 | *focus = Focus::This;
236 | }
237 | #[cfg(feature = "log")]
238 | log::debug!("{:?} unlocked focus", self.discrim);
239 |
240 | *FOCUSED.get().unwrap().lock().unwrap() = self.discrim.clone();
241 | let _ = req.respond(Response::new_with_request(
242 | ResponseContent::Success {
243 | content: ResponseSuccess::FocusChanged,
244 | },
245 | *req.get().id(),
246 | ));
247 |
248 | return false.into();
249 | }
250 | RequestContent::NewSpace { label } => {
251 | // just add a new entry to subspaces
252 | let space = Space::new_with_parent(label.clone(), &self.discrim).await;
253 | let _ = req.respond(Response::new_with_request(
254 | ResponseContent::Success {
255 | content: ResponseSuccess::SpaceCreated {
256 | discrim: space.discrim.clone(),
257 | },
258 | },
259 | *req.get().id(),
260 | ));
261 | self.subspaces.lock().await.insert(space);
262 | }
263 | // spawn a new process
264 | RequestContent::Spawn {
265 | command,
266 | args,
267 | label,
268 | env,
269 | } => {
270 | // check if spawning process succeed
271 | match Process::spawn(
272 | label.clone(),
273 | &self.discrim,
274 | command.clone(),
275 | args.clone(),
276 | env.clone(),
277 | )
278 | .await
279 | {
280 | Ok(process) => {
281 | let _ = req.respond(Response::new_with_request(
282 | ResponseContent::Success {
283 | content: ResponseSuccess::Spawned {
284 | discrim: process.discrim().clone(),
285 | },
286 | },
287 | *req.get().id(),
288 | ));
289 | self.processes.lock().await.insert(process);
290 | }
291 | Err(_) => {
292 | let _ = req.respond(Response::new_with_request(
293 | ResponseContent::Error {
294 | content: ResponseError::SpawnFailed,
295 | },
296 | *req.get().id(),
297 | ));
298 | }
299 | }
300 | }
301 | // add an item to passes
302 | RequestContent::Subscribe {
303 | channel,
304 | priority,
305 | component: Some(discrim),
306 | } => {
307 | // checks if the discrim is to a valid process
308 | if let Some(child) = self.discrim.immediate_child(discrim.clone()) {
309 | if self.processes.lock().await.contains(&child) {
310 | // if its a process, subscribe to the event right here
311 | self.passes.lock().await.subscribe(
312 | channel.clone(),
313 | PassItem::new(discrim.clone(), *priority),
314 | );
315 | let _ = req.respond(Response::new_with_request(
316 | ResponseContent::Success {
317 | content: ResponseSuccess::SubscribeAdded,
318 | },
319 | *req.get().id(),
320 | ));
321 | } else {
322 | // or else just throw a not found
323 | let _ = req.respond(Response::new_with_request(
324 | ResponseContent::Error {
325 | content: ResponseError::ComponentNotFound,
326 | },
327 | *req.get().id(),
328 | ));
329 | }
330 | }
331 | }
332 | // remove an item from
333 | RequestContent::Unsubscribe {
334 | channel,
335 | component: Some(discrim),
336 | } => {
337 | // checks if the discrim is to a valid process
338 | if let Some(child) = self.discrim.immediate_child(discrim.clone()) {
339 | if self.processes.lock().await.contains(&child) {
340 | // if its a process, subscribe to the event right here
341 | self.passes
342 | .lock()
343 | .await
344 | .unsubscribe(channel.clone(), discrim);
345 | let _ = req.respond(Response::new_with_request(
346 | ResponseContent::Success {
347 | content: ResponseSuccess::SubscribeRemoved,
348 | },
349 | *req.get().id(),
350 | ));
351 | } else {
352 | // or else just throw a not found
353 | let _ = req.respond(Response::new_with_request(
354 | ResponseContent::Error {
355 | content: ResponseError::ComponentNotFound,
356 | },
357 | *req.get().id(),
358 | ));
359 | }
360 | }
361 | }
362 | RequestContent::Drop { discrim } => {
363 | // drop (remove) a child component
364 | if let Some(child) = self.discrim.immediate_child(discrim.clone().unwrap())
365 | {
366 | if self.processes.lock().await.remove(&child) {
367 | // if its a process, then remove all of its passes
368 | self.passes.lock().await.unsub_all(&child);
369 | } else if self.subspaces.lock().await.remove(&child) {
370 | if *self.focus.lock().await == Focus::Children(child) {
371 | // if the removed space is currently focused, then switch focus
372 | // to parent space
373 | *self.focus.lock().await = Focus::This
374 | }
375 | } else {
376 | let _ = req.respond(Response::new_with_request(
377 | ResponseContent::Error {
378 | content: ResponseError::ComponentNotFound,
379 | },
380 | *req.get().id(),
381 | ));
382 | return false.into();
383 | }
384 | let _ = req.respond(Response::new_with_request(
385 | ResponseContent::Success {
386 | content: ResponseSuccess::Dropped,
387 | },
388 | *req.get().id(),
389 | ));
390 | }
391 | }
392 | RequestContent::Render { content, flush } => {
393 | // does rendering stuff, no explainations needed
394 | let flush = *flush;
395 | let content = content.clone();
396 | tokio::task::spawn_blocking(move || {
397 | content.draw(
398 | SCREEN.get().unwrap().lock().unwrap().as_mut().unwrap(),
399 | flush,
400 | )
401 | })
402 | .await
403 | .unwrap();
404 |
405 | let _ = req.respond(Response::new_with_request(
406 | ResponseContent::Success {
407 | content: ResponseSuccess::Rendered,
408 | },
409 | *req.get().id(),
410 | ));
411 | }
412 | RequestContent::Message {
413 | content,
414 | sender,
415 | target,
416 | tag,
417 | } => {
418 | // heres all the things needed to construct an event
419 | let sender = sender.clone();
420 | let target = target.clone();
421 | let content = content.clone();
422 | let tag = tag.clone();
423 |
424 | let _ = req.respond(Response::new_with_request(
425 | ResponseContent::Success {
426 | content: ResponseSuccess::MessageDelivered,
427 | },
428 | *req.get().id(),
429 | ));
430 |
431 | // now pass the event to self
432 | *event = Event::Message {
433 | sender,
434 | target,
435 | content,
436 | tag,
437 | };
438 |
439 | self.pass(event, None).await;
440 | }
441 | RequestContent::GetState { .. }
442 | | RequestContent::Watch { .. }
443 | | RequestContent::Subscribe {
444 | component: None, ..
445 | }
446 | | RequestContent::Unsubscribe {
447 | component: None, ..
448 | } => unreachable!("impossible requests"),
449 | RequestContent::ConfirmRecieve { .. } | RequestContent::SetSocket { .. } => {
450 | unreachable!("not requests to spaces")
451 | }
452 | }
453 |
454 | return false.into();
455 | } // do stuff
456 | Event::RequestPacket(req) => {
457 | // pass the event to "next immediate child"
458 | // aka the next item it should pass to in order to get the request
459 | // to its intended target
460 | if let Some(child) = self.discrim.immediate_child(req.get().target().clone()) {
461 | if req.get().content() == &RequestContent::FocusAt {
462 | let mut focus = self.focus.lock().await;
463 | let subspaces = self.subspaces.lock().await;
464 |
465 | if !subspaces.contains(&child) {
466 | let _ = req.respond(Response::new_with_request(
467 | ResponseContent::Error {
468 | content: ResponseError::ComponentNotFound,
469 | },
470 | *req.get().id(),
471 | ));
472 | }
473 |
474 | if let Focus::Children(focused) = &*focus {
475 | if req.get().target().starts_with(focused) {
476 | let subspace = subspaces.find_by_discrim_arc(&child).unwrap();
477 | subspace.pass(event, None).await;
478 | } else {
479 | subspaces
480 | .find_by_discrim(focused)
481 | .unwrap()
482 | .pass(&mut Event::Unfocus, None)
483 | .await;
484 | *focus = Focus::Children(child.clone());
485 |
486 | let child = subspaces.find_by_discrim(&child).unwrap();
487 | // this kinda defeats the point of non blocking
488 | // as this might block
489 | // but it shouldnt, and let's just pray on it that its true
490 | //
491 | // event must come after the actual focus or else it might get
492 | // passed to the wrong components
493 | child.pass(event, None).await.evaluate().await;
494 | child.pass(&mut Event::Focus, None).await;
495 | }
496 | } else {
497 | *focus = Focus::Children(child.clone());
498 | let child = subspaces.find_by_discrim(&child).unwrap();
499 | child.pass(event, None).await.evaluate().await;
500 | child.pass(&mut Event::Focus, None).await;
501 | }
502 |
503 | return false.into();
504 | }
505 |
506 | // no 2 components are the same, so order shouldnt matter
507 | if let Some(proc) = self.processes.lock().await.find_by_discrim(&child) {
508 | if let Some(subscriptions) = req.get().subscriptions() {
509 | if self
510 | .passes
511 | .lock()
512 | .await
513 | .subscribers(&subscriptions)
514 | .iter()
515 | .any(|item| item.discrim() == proc.discrim())
516 | {
517 | proc.pass(event, None).await;
518 | } else {
519 | let _ = req.respond(Response::new_with_request(
520 | ResponseContent::Undelivered,
521 | *req.get().id(),
522 | ));
523 | }
524 | } else {
525 | proc.pass(event, None).await;
526 | }
527 | } else if let Some(space) =
528 | self.subspaces.lock().await.find_by_discrim_arc(&child)
529 | {
530 | space.pass(event, None).await;
531 | } else {
532 | let _ = req.respond(Response::new(ResponseContent::Undelivered));
533 | }
534 |
535 | return false.into();
536 | }
537 | // otherwise self is not a parent to the target component
538 | // and something went wrong
539 | }
540 | _ => {}
541 | }
542 |
543 | #[cfg(feature = "log")]
544 | log::debug!("got here 1");
545 |
546 | let subscriptions = event.subscriptions();
547 | // all components listening to this event
548 | let targets = self.passes.lock().await.subscribers(&subscriptions);
549 |
550 | #[cfg(feature = "log")]
551 | log::debug!("got here 2");
552 | let suppressors_mutex = self.suppressors.clone();
553 | let suppressors = self.suppressors.lock().await;
554 | #[cfg(feature = "log")]
555 | log::debug!("got here 3");
556 | let mut current_suppress_level =
557 | match (suppressors.suppress_level(&subscriptions), suppress_level) {
558 | (Some(a), Some(b)) => Some(a.min(b)),
559 | (Some(c), None) | (None, Some(c)) => Some(c),
560 | (None, None) => None,
561 | };
562 | let mut suppressor_state = suppressors.state_id();
563 |
564 | let processes = self.processes.clone();
565 | let mut event = event.clone();
566 | let subspaces = self.subspaces.clone();
567 | let focus = self.focus.clone();
568 | let uneval = tokio::spawn(async move {
569 | // repeat until someone decide to capture the event
570 | for target in targets {
571 | let suppressors = suppressors_mutex.lock().await;
572 | let new_state = suppressors.state_id();
573 | if new_state != suppressor_state {
574 | current_suppress_level =
575 | match (suppressors.suppress_level(&subscriptions), suppress_level) {
576 | (Some(a), Some(b)) => Some(a.min(b)),
577 | (Some(c), None) | (None, Some(c)) => Some(c),
578 | (None, None) => None,
579 | };
580 | suppressor_state = new_state;
581 | }
582 |
583 | if current_suppress_level.is_some_and(|current_suppress_level| {
584 | !target
585 | .priority()
586 | .is_some_and(|target| target <= current_suppress_level)
587 | }) {
588 | continue;
589 | }
590 |
591 | drop(suppressors);
592 |
593 | #[cfg(feature = "log")]
594 | log::debug!("passing {event:?} to {target:?}");
595 | let process = processes
596 | .lock()
597 | .await
598 | .find_by_discrim_arc(target.discrim())
599 | .unwrap();
600 |
601 | let suppress_level = match (
602 | current_suppress_level,
603 | process.suppress_level(&subscriptions).await,
604 | ) {
605 | (Some(a), Some(b)) => Some(a.min(b)),
606 | (Some(c), None) | (None, Some(c)) => Some(c),
607 | (None, None) => None,
608 | };
609 |
610 | let res = process.pass(&mut event, suppress_level).await;
611 | let res = res.evaluate().await;
612 | if !res {
613 | #[cfg(feature = "log")]
614 | log::debug!("event {event:?} captured by {target:?}");
615 | return false;
616 | }
617 | }
618 |
619 | if event == Event::Focus {
620 | return false;
621 | }
622 |
623 | // if all went well then continue to pass down into subspaces
624 | let focus = focus.lock().await.clone();
625 | if let Focus::Children(discrim) = focus {
626 | let subspace = subspaces
627 | .lock()
628 | .await
629 | .find_by_discrim_arc(&discrim)
630 | .unwrap();
631 | subspace
632 | .pass(&mut event, suppress_level)
633 | .await
634 | .evaluate()
635 | .await;
636 | }
637 |
638 | true
639 | });
640 |
641 | Unevaluated::Unevaluated(uneval)
642 | }
643 | }
644 |
--------------------------------------------------------------------------------
/src/structs/component/subscription.rs:
--------------------------------------------------------------------------------
1 | use serde::{Deserialize, Serialize};
2 |
3 | use crate::structs::{KeyCode, KeyEvent, KeyModifier, MouseType};
4 |
5 | use super::Discriminator;
6 |
7 | /// a single subscription item, such as a key press event
8 | #[derive(Hash, PartialEq, Eq, Serialize, Deserialize, Debug, Clone)]
9 | #[serde(tag = "type")]
10 | pub enum Subscription {
11 | /// Every, single, event
12 | #[serde(rename = "everything")]
13 | Everything,
14 | /// subscribes to all key press events
15 | #[serde(rename = "all key presses")]
16 | AllKeyPresses,
17 | /// all mouse click and drag events
18 | #[serde(rename = "all mouse events")]
19 | AllMouseEvents,
20 | /// subscribe to all messages from other components
21 | #[serde(rename = "all messages")]
22 | AllMessages,
23 | /// a specific key event
24 | #[serde(rename = "specific key press")]
25 | SpecificKeyPress { key: KeyEvent },
26 | /// all key events with that key modifier
27 | #[serde(rename = "specific key modifier")]
28 | SpecificKeyModifier { modifier: KeyModifier },
29 | /// all key events with that key modifier
30 | #[serde(rename = "specific key code")]
31 | SpecificKeyCode { code: KeyCode },
32 | /// a specific mouse event
33 | #[serde(rename = "specific mouse event")]
34 | SpecificMouseEvent { mouse: MouseType },
35 | /// a specific message from someone
36 | #[serde(rename = "specific message")]
37 | SpecificMessage { source: Discriminator },
38 | /// a specific message with tag
39 | #[serde(rename = "specific message tag")]
40 | SpecificMessageTag { tag: String },
41 | /// screen resize events
42 | #[serde(rename = "screen resize")]
43 | ScreenResize,
44 | #[serde(rename = "focused")]
45 | /// current space focused
46 | Focused,
47 | #[serde(rename = "unfocused")]
48 | /// current space unfocused
49 | Unfocused,
50 |
51 | #[serde(rename = "multiple")]
52 | /// subscribe to multiple channels at once
53 | Multiple {
54 | subs: Vec<(Subscription, Option)>,
55 | },
56 | }
57 |
--------------------------------------------------------------------------------
/src/structs/component/subscriptions.rs:
--------------------------------------------------------------------------------
1 | use std::collections::HashSet;
2 |
3 | use super::Subscription;
4 |
5 | /// multiple subscriptions that a process can have
6 | pub type Subscriptions = HashSet;
7 |
--------------------------------------------------------------------------------
/src/structs/data/collection.rs:
--------------------------------------------------------------------------------
1 | use std::collections::HashMap;
2 | use std::sync::Arc;
3 |
4 | use crate::structs::Discriminator;
5 | use crate::traits::Component;
6 |
7 | /// a collection of component items
8 | pub struct Collection {
9 | // items: HashMap>>,
10 | items: HashMap>,
11 | }
12 |
13 | impl Collection {
14 | /// return all elements with that label
15 | pub async fn find_all_by_label(&self, label: &str) -> Vec<&T> {
16 | self.items
17 | .iter()
18 | .filter_map(|(_, value)| {
19 | if label == value.label() {
20 | Some(value.as_ref())
21 | } else {
22 | None
23 | }
24 | })
25 | .collect()
26 | }
27 |
28 | /// return max one element with matching discriminator
29 | pub fn find_by_discrim(&self, discrim: &Discriminator) -> Option<&T> {
30 | self.items.get(discrim).map(|item| item.as_ref())
31 | }
32 |
33 | /// return max one element with matching discriminator, returning an arc
34 | pub fn find_by_discrim_arc(&self, discrim: &Discriminator) -> Option> {
35 | self.items.get(discrim).cloned()
36 | }
37 |
38 | /// return max one element with matching discriminator (mutable)
39 | // pub fn find_by_discrim_mut(&mut self, discrim: &Discriminator) -> Option<&mut T> {
40 | // self.items.get_mut(discrim)
41 | // }
42 |
43 | /// check if the item is in collection
44 | pub fn contains(&self, discrim: &Discriminator) -> bool {
45 | self.items.contains_key(discrim)
46 | }
47 |
48 | /// insert an item and return handle to it
49 | pub fn insert(&mut self, item: T) {
50 | self.items.insert(item.discrim().clone(), Arc::new(item));
51 | }
52 |
53 | /// removes an item by discrim
54 | pub fn remove(&mut self, discrim: &Discriminator) -> bool {
55 | self.items.remove(discrim).is_some()
56 | }
57 | }
58 |
59 | impl Default for Collection {
60 | fn default() -> Self {
61 | Self {
62 | items: HashMap::default(),
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/structs/data/mod.rs:
--------------------------------------------------------------------------------
1 | mod collection;
2 | pub use collection::*;
3 |
4 | mod packet;
5 | pub use packet::*;
6 |
7 | mod pool;
8 | pub use pool::*;
9 |
10 | mod storage;
11 | pub use storage::*;
12 |
13 | mod unevaluated;
14 | pub use unevaluated::*;
15 |
--------------------------------------------------------------------------------
/src/structs/data/packet.rs:
--------------------------------------------------------------------------------
1 | use tokio::sync::oneshot;
2 |
3 | /// a packet of info, expecting response
4 | #[derive(Debug)]
5 | pub struct Packet {
6 | /// actual packet data
7 | message: T,
8 | /// a "callback" sender
9 | responder: Option>,
10 | }
11 |
12 | impl Packet {
13 | /// create a packet and a receiver handle
14 | pub fn new(message: T) -> (Self, oneshot::Receiver) {
15 | let (tx, rx) = oneshot::channel();
16 |
17 | (
18 | Self {
19 | message,
20 | responder: Some(tx),
21 | },
22 | rx,
23 | )
24 | }
25 |
26 | /// returns inner conent
27 | pub fn get(&self) -> &T {
28 | &self.message
29 | }
30 |
31 | /// respond to packet sender, and return Ok if sent successfully
32 | pub fn respond(&mut self, res: R) -> Result<(), crate::Error> {
33 | if let Some(resp) = std::mem::take(&mut self.responder) {
34 | // this allows &mut Self to use
35 | // this function
36 | let _ = resp.send(res);
37 | Ok(())
38 | } else {
39 | Err(crate::Error::PacketDoubleResp)
40 | }
41 | }
42 | }
43 |
44 | impl PartialEq for Packet {
45 | fn eq(&self, _other: &Self) -> bool {
46 | false // no 2 packets are the same
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/structs/data/pool.rs:
--------------------------------------------------------------------------------
1 | use std::collections::{hash_map::Entry, HashMap};
2 |
3 | use serde_json::Value;
4 | use tokio::sync::mpsc::UnboundedSender;
5 |
6 | use crate::structs::{Discriminator, EventSerde, Response, ResponseContent};
7 |
8 | /// pool of key-value pairs for shared or private access
9 | pub struct Pool {
10 | discrim: Discriminator,
11 | map: HashMap,
12 | }
13 |
14 | impl Pool {
15 | /// create a new pool using discrim
16 | pub fn new(discrim: Discriminator) -> Self {
17 | Self {
18 | discrim,
19 | map: HashMap::default(),
20 | }
21 | }
22 |
23 | /// get a key value, similar to a regular hashap
24 | pub fn get(&mut self, label: &str) -> Option {
25 | self.map
26 | .get(label)
27 | .map(|item| item.value.as_ref().unwrap().clone())
28 | }
29 |
30 | /// set a value, this will call all the watchers
31 | pub fn set(&mut self, label: &str, value: Value) {
32 | match self.map.entry(label.to_string()) {
33 | Entry::Occupied(mut entry) => entry.get_mut().set(label, value, &self.discrim),
34 | Entry::Vacant(entry) => {
35 | let _ = entry.insert(PoolItem::new(value));
36 | }
37 | }
38 | }
39 |
40 | /// remove a value, this will call all the watchers
41 | /// return false if no such entry exist
42 | pub fn remove(&mut self, label: &str, discrim: &Discriminator) {
43 | if let Some(entry) = self.map.get_mut(label) {
44 | entry.remove(label, discrim);
45 | if entry.is_empty() {
46 | self.map.remove(label);
47 | }
48 | }
49 | }
50 |
51 | /// insert a watch to an entry
52 | /// return false if no such entry exist
53 | pub fn watch(
54 | &mut self,
55 | label: String,
56 | listener: UnboundedSender,
57 | discrim: Discriminator,
58 | ) {
59 | self.map.entry(label).or_default().watch(discrim, listener);
60 | }
61 |
62 | /// remove watche from entry
63 | pub fn unwatch(
64 | &mut self,
65 | label: &str,
66 | discrim: &Discriminator,
67 | self_discrim: Discriminator,
68 | ) -> bool {
69 | match self.map.get_mut(label) {
70 | Some(entry) => {
71 | entry.unwatch(discrim, label.to_string(), self_discrim);
72 |
73 | if entry.is_empty() {
74 | self.map.remove(label);
75 | }
76 | true
77 | }
78 | None => false,
79 | }
80 | }
81 | }
82 |
83 | #[derive(Default)]
84 | /// a single entry in pool
85 | pub struct PoolItem {
86 | /// the actual value of the entry
87 | value: Option,
88 | /// watchers of the entry
89 | listener: HashMap>,
90 | }
91 |
92 | impl PoolItem {
93 | /// create new self with a value
94 | pub fn new(value: Value) -> Self {
95 | Self {
96 | value: Some(value),
97 | listener: HashMap::new(),
98 | }
99 | }
100 |
101 | pub fn value(&self) -> &Option {
102 | &self.value
103 | }
104 |
105 | /// add watcher to self
106 | pub fn watch(&mut self, discrim: Discriminator, sender: UnboundedSender) {
107 | self.listener.insert(discrim, sender);
108 | }
109 |
110 | /// remove watcher from self
111 | pub fn unwatch(&mut self, discrim: &Discriminator, label: String, self_discrim: Discriminator) {
112 | if let Some(watcher) = self.listener.remove(discrim) {
113 | let _ = watcher.send(Response::new(ResponseContent::Event {
114 | content: EventSerde::ValueRemoved {
115 | label,
116 | discrim: self_discrim,
117 | },
118 | }));
119 | }
120 | }
121 |
122 | /// create an entry, override existing value
123 | /// never fails
124 | /// call all watchers and remove the dead ones
125 | pub fn set(&mut self, label: &str, value: Value, discrim: &Discriminator) {
126 | self.value = Some(value.clone());
127 |
128 | let mut dead_senders = Vec::new();
129 | self.listener.iter().for_each(|(_, listener)| {
130 | if listener
131 | .send(Response::new(ResponseContent::Event {
132 | content: EventSerde::ValueUpdated {
133 | label: label.to_string(),
134 | new: value.clone(),
135 | discrim: discrim.clone(),
136 | },
137 | }))
138 | .is_err()
139 | {
140 | dead_senders.push(discrim.clone())
141 | }
142 | });
143 |
144 | dead_senders.iter().for_each(|key| {
145 | let _ = self.listener.remove(key);
146 | })
147 | }
148 |
149 | /// remove an entry
150 | pub fn remove(&mut self, label: &str, self_discrim: &Discriminator) {
151 | self.value = None;
152 |
153 | self.listener.values().for_each(|listener| {
154 | let _ = listener.send(Response::new(ResponseContent::Event {
155 | content: EventSerde::ValueRemoved {
156 | label: label.to_string(),
157 | discrim: self_discrim.clone(),
158 | },
159 | }));
160 | })
161 | }
162 |
163 | /// returns true if there is absolutely nothing to keep in this entry
164 | pub fn is_empty(&self) -> bool {
165 | self.value.is_none() && self.listener.is_empty()
166 | }
167 | }
168 |
--------------------------------------------------------------------------------
/src/structs/data/storage.rs:
--------------------------------------------------------------------------------
1 | use std::{
2 | error::Error,
3 | path::{Path, PathBuf},
4 | };
5 |
6 | use tokio::fs;
7 |
8 | use crate::structs::Discriminator;
9 | use crate::values::ROOT;
10 |
11 | /// wrapper struct for storage of a single component
12 | #[derive(Clone)]
13 | pub struct Storage {
14 | // absolute path to directory
15 | path: PathBuf,
16 | }
17 |
18 | impl Storage {
19 | /// creates a new struct and the corresponding directory
20 | pub async fn new(discrim: &Discriminator) -> Self {
21 | let path = ROOT.get().unwrap().join(PathBuf::from_iter(
22 | discrim.as_vec().iter().map(u32::to_string),
23 | ));
24 |
25 | if !fs::try_exists(&path).await.unwrap() {
26 | fs::create_dir_all(&path).await.unwrap();
27 | }
28 |
29 | Self { path }
30 | }
31 |
32 | /// returns absolute path to storage
33 | pub fn path(&self) -> &Path {
34 | &self.path
35 | }
36 |
37 | /// remove a file or directory at path if it exists
38 | pub async fn remove_if_exist(path: &Path) -> Result<(), Box> {
39 | if fs::try_exists(path).await? {
40 | if fs::metadata(path).await?.is_dir() {
41 | fs::remove_dir_all(&path).await?;
42 | } else {
43 | fs::remove_file(&path).await?;
44 | }
45 | }
46 |
47 | Ok(())
48 | }
49 | }
50 |
51 | impl Drop for Storage {
52 | fn drop(&mut self) {
53 | let path = self.path.clone();
54 | let _ = std::fs::remove_dir_all(path);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/structs/data/unevaluated.rs:
--------------------------------------------------------------------------------
1 | use tokio::task::JoinHandle;
2 |
3 | /// a potentially unevaluated value
4 | /// this is returned to prevent deadlocks in awaits
5 | pub enum Unevaluated {
6 | /// a concrete, evaluated value
7 | Concrete(T),
8 | /// an unevaluated value
9 | Unevaluated(JoinHandle),
10 | }
11 |
12 | impl Unevaluated {
13 | /// returns the evaluated value
14 | /// waits until it is evaluated, if not
15 | pub async fn evaluate(self) -> T {
16 | match self {
17 | Self::Concrete(value) => value,
18 | Self::Unevaluated(handle) => handle.await.unwrap(),
19 | }
20 | }
21 | }
22 |
23 | impl From for Unevaluated {
24 | fn from(value: T) -> Self {
25 | Self::Concrete(value)
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/structs/error.rs:
--------------------------------------------------------------------------------
1 | use std::{error, fmt};
2 |
3 | use serde::Serialize;
4 |
5 | /// crate error values
6 | #[derive(Debug, Serialize)]
7 | pub enum Error {
8 | /// no specified error messages
9 | /// typically generated by C bindings
10 | /// where they just return an unhelpful error code
11 | #[serde(rename = "unspecified")]
12 | Unspecified,
13 |
14 | /// unsupported termion event
15 | #[serde(rename = "unsupported event")]
16 | UnsupportedEvent(Vec),
17 |
18 | /// unsupported termion key event
19 | #[serde(rename = "unsupported key")]
20 | UnsupportedKey,
21 |
22 | /// packets can only respond to sender once
23 | #[serde(rename = "packet double response")]
24 | PacketDoubleResp,
25 |
26 | #[serde(rename = "undelivered")]
27 | Undelivered,
28 | }
29 |
30 | impl fmt::Display for Error {
31 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 | match self {
33 | Self::Unspecified => f.write_str("unspecified error"),
34 | Self::UnsupportedEvent(bytes) => {
35 | f.write_fmt(format_args!("unsupported event {bytes:?}"))
36 | }
37 | Self::UnsupportedKey => f.write_str("unsupported key"),
38 | Self::PacketDoubleResp => f.write_str("packet double sending response"),
39 | Self::Undelivered => f.write_str("undelivered"),
40 | }
41 | }
42 | }
43 |
44 | impl error::Error for Error {}
45 |
--------------------------------------------------------------------------------
/src/structs/events/event.rs:
--------------------------------------------------------------------------------
1 | use crate::structs::{Discriminator, Packet, Request, Response, Subscription};
2 |
3 | use super::{KeyEvent, MouseEvent};
4 |
5 | use serde_json::Value;
6 | use termion::event::Event as TermionEvent;
7 |
8 | /// a basic, generic unit of event
9 | #[derive(Debug, PartialEq)]
10 | pub enum Event {
11 | /// keyboard event
12 | KeyPress(KeyEvent),
13 | /// events related to mouse down
14 | MouseEvent(MouseEvent),
15 | /// screen resize event (should trigger a rerender)
16 | ScreenResize(u32, u32),
17 | /// request that requires a response
18 | RequestPacket(Packet),
19 | /// message sent from a component
20 | Focus,
21 | Unfocus,
22 | Message {
23 | sender: Discriminator,
24 | target: Discriminator,
25 | content: Value,
26 | tag: String,
27 | },
28 | }
29 |
30 | impl TryFrom for Event {
31 | fn try_from(value: TermionEvent) -> Result {
32 | match value {
33 | TermionEvent::Key(keyevent) => Ok(Self::KeyPress(KeyEvent::try_from(keyevent)?)),
34 | TermionEvent::Mouse(mouseevent) => Ok(Self::MouseEvent(MouseEvent::from(mouseevent))),
35 | TermionEvent::Unsupported(bytes) => Err(crate::Error::UnsupportedEvent(bytes)),
36 | }
37 | }
38 |
39 | type Error = crate::Error;
40 | }
41 |
42 | impl Clone for Event {
43 | fn clone(&self) -> Self {
44 | match self {
45 | Self::KeyPress(key) => Self::KeyPress(*key),
46 | Self::MouseEvent(mouse) => Self::MouseEvent(*mouse),
47 | Self::ScreenResize(x, y) => Self::ScreenResize(*x, *y),
48 | Self::Focus => Self::Focus,
49 | Self::Unfocus => Self::Unfocus,
50 | Self::Message {
51 | sender,
52 | target,
53 | content,
54 | tag,
55 | } => Self::Message {
56 | sender: sender.clone(),
57 | target: target.clone(),
58 | content: content.clone(),
59 | tag: tag.clone(),
60 | },
61 | Self::RequestPacket(_) => panic!("bad clone"),
62 | }
63 | }
64 | }
65 |
66 | impl Event {
67 | pub fn subscriptions(&self) -> Vec {
68 | match self {
69 | Self::KeyPress(key) => vec![
70 | Subscription::Everything,
71 | Subscription::AllKeyPresses,
72 | Subscription::SpecificKeyPress { key: *key },
73 | Subscription::SpecificKeyCode { code: key.code },
74 | Subscription::SpecificKeyModifier {
75 | modifier: key.modifier,
76 | },
77 | ],
78 | Self::Message { sender, tag, .. } => vec![
79 | Subscription::Everything,
80 | Subscription::AllMessages,
81 | Subscription::SpecificMessage {
82 | source: sender.clone(),
83 | },
84 | Subscription::SpecificMessageTag { tag: tag.clone() },
85 | ],
86 | Self::MouseEvent(mouse) => vec![
87 | Subscription::Everything,
88 | Subscription::AllMouseEvents,
89 | Subscription::SpecificMouseEvent {
90 | mouse: mouse.mousetype,
91 | },
92 | ],
93 | Self::ScreenResize(..) => vec![Subscription::Everything, Subscription::ScreenResize],
94 | Self::Focus { .. } => vec![Subscription::Everything, Subscription::Focused],
95 | Self::Unfocus => vec![Subscription::Everything, Subscription::Unfocused],
96 | Self::RequestPacket(_) => Vec::new(),
97 | }
98 | }
99 |
100 | pub fn from_packet(packet: Packet) -> Self {
101 | Self::RequestPacket(packet)
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/src/structs/events/keyevent.rs:
--------------------------------------------------------------------------------
1 | use serde::{Deserialize, Serialize};
2 | use termion::event::Key as TermionKey;
3 |
4 | /// a single keyboard event
5 | #[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Hash)]
6 | pub struct KeyEvent {
7 | /// the keycode represented by the characetr
8 | pub code: KeyCode,
9 | /// key modifiers (e.g. ctrl)
10 | pub modifier: KeyModifier,
11 | }
12 |
13 | impl TryFrom for KeyEvent {
14 | fn try_from(value: TermionKey) -> Result {
15 | match value {
16 | TermionKey::Alt(c) => Ok(Self::new(KeyCode::Char(c), KeyModifier::Alt)),
17 | TermionKey::Ctrl(c) => Ok(Self::new(KeyCode::Char(c), KeyModifier::Ctrl)),
18 | TermionKey::__IsNotComplete => Err(crate::Error::UnsupportedKey),
19 | key => Ok(Self::new(
20 | KeyCode::try_from(key).unwrap(),
21 | KeyModifier::None,
22 | )),
23 | }
24 | }
25 |
26 | type Error = crate::Error;
27 | }
28 |
29 | impl KeyEvent {
30 | pub fn new(code: KeyCode, modifier: KeyModifier) -> Self {
31 | Self { code, modifier }
32 | }
33 | }
34 |
35 | /// a unique key (non modifier keys)
36 | #[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Hash)]
37 | pub enum KeyCode {
38 | /// Backspace.
39 | #[serde(rename = "backspace")]
40 | Backspace,
41 | /// Left arrow.
42 | #[serde(rename = "left")]
43 | Left,
44 | /// Right arrow.
45 | #[serde(rename = "right")]
46 | Right,
47 | /// Up arrow.
48 | #[serde(rename = "up")]
49 | Up,
50 | /// Down arrow.
51 | #[serde(rename = "down")]
52 | Down,
53 | /// Home key.
54 | #[serde(rename = "home")]
55 | Home,
56 | /// End key.
57 | #[serde(rename = "end")]
58 | End,
59 | /// Page Up key.
60 | #[serde(rename = "pageup")]
61 | PageUp,
62 | /// Page Down key.
63 | #[serde(rename = "pagedown")]
64 | PageDown,
65 | /// Backward Tab key.
66 | #[serde(rename = "backtab")]
67 | BackTab,
68 | /// Delete key.
69 | #[serde(rename = "delete")]
70 | Delete,
71 | /// Insert key.
72 | #[serde(rename = "insert")]
73 | Insert,
74 | /// Function keys.
75 | ///
76 | /// Only function keys 1 through 12 are supported.
77 | #[serde(rename = "f")]
78 | F(u8),
79 | /// Normal character.
80 | #[serde(rename = "char")]
81 | Char(char),
82 | /// Null byte.
83 | #[serde(rename = "null")]
84 | Null,
85 | /// Esc key.
86 | #[serde(rename = "esc")]
87 | Esc,
88 | }
89 |
90 | impl TryFrom for KeyCode {
91 | fn try_from(value: TermionKey) -> Result {
92 | match value {
93 | TermionKey::Up => Ok(Self::Up),
94 | TermionKey::End => Ok(Self::End),
95 | TermionKey::F(f) => Ok(Self::F(f)),
96 | TermionKey::Esc => Ok(Self::Esc),
97 | TermionKey::Left => Ok(Self::Left),
98 | TermionKey::Down => Ok(Self::Down),
99 | TermionKey::Home => Ok(Self::Home),
100 | TermionKey::Null => Ok(Self::Null),
101 | TermionKey::Right => Ok(Self::Right),
102 | TermionKey::PageUp => Ok(Self::PageUp),
103 | TermionKey::Delete => Ok(Self::Delete),
104 | TermionKey::Insert => Ok(Self::Insert),
105 | TermionKey::BackTab => Ok(Self::BackTab),
106 | TermionKey::PageDown => Ok(Self::PageDown),
107 | TermionKey::Backspace => Ok(Self::Backspace),
108 | TermionKey::Char(c) => Ok(Self::Char(c)),
109 | TermionKey::Alt(_) | TermionKey::Ctrl(_) | TermionKey::__IsNotComplete => {
110 | Err(crate::Error::UnsupportedKey)
111 | }
112 | }
113 | }
114 |
115 | type Error = crate::Error;
116 | }
117 |
118 | /// modifier keys that only exist as modifiers to the real key code
119 | ///
120 | /// no shift, as it is not a real modifier
121 | /// check if shift might be pressed yourself using is_upper_case
122 | #[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Hash)]
123 | pub enum KeyModifier {
124 | #[serde(rename = "alt")]
125 | Alt,
126 | /// note that certain keys may not be modifiable with ctrl, due to limitations of terminals.
127 | #[serde(rename = "ctrl")]
128 | Ctrl,
129 | #[serde(rename = "none")]
130 | None,
131 | }
132 |
--------------------------------------------------------------------------------
/src/structs/events/listeners.rs:
--------------------------------------------------------------------------------
1 | use std::io::stdin;
2 |
3 | use nix::sys::signal::{self, SigHandler, Signal};
4 | use termion::input::TermRead;
5 | use tokio::sync::{
6 | mpsc::{self, UnboundedReceiver, UnboundedSender},
7 | OnceCell,
8 | };
9 |
10 | use super::Event;
11 |
12 | /// a copy of the broadcast sender
13 | ///
14 | /// make a clone of it and you can start broadcasting events
15 | /// or you can subscribe to it and get a reciever to the broadcast
16 | static EVENTS: OnceCell> = OnceCell::const_new();
17 |
18 | impl Event {
19 | /// kick start the event broadcaster
20 | /// should only be called once for the entire duration of the program
21 | pub fn start() -> UnboundedReceiver {
22 | // can only be started once
23 | if EVENTS.get().is_some() {
24 | panic!("events broadcast has already been started");
25 | }
26 |
27 | let (tx, rx): (UnboundedSender, UnboundedReceiver) =
28 | mpsc::unbounded_channel();
29 | {
30 | let tx = tx.clone();
31 | tokio::task::spawn_blocking(move || {
32 | stdin()
33 | .events()
34 | // filter out events that cannot be converted into event
35 | .filter_map(|event| -> Option {
36 | let event = event;
37 | if let Ok(event) = event {
38 | if let Ok(event) = event.try_into() {
39 | return Some(event);
40 | }
41 | }
42 | None
43 | })
44 | .for_each(|event| {
45 | // send events to master space
46 | let _ = tx.send(event);
47 | })
48 | });
49 | }
50 |
51 | extern "C" fn handle_resize(_: libc::c_int) {
52 | // send a screen resize event when it is resized
53 | let (x, y) = termion::terminal_size().unwrap();
54 | let _ = EVENTS
55 | .get()
56 | .unwrap()
57 | .send(Event::ScreenResize(x as u32, y as u32));
58 | }
59 |
60 | // listen for SIGWINCH, as it is the only way to listen for window resize event
61 | // without pulling in huge dependencies
62 | let sig_action = signal::SigAction::new(
63 | SigHandler::Handler(handle_resize),
64 | signal::SaFlags::empty(),
65 | signal::SigSet::empty(),
66 | );
67 | unsafe {
68 | signal::sigaction(Signal::SIGWINCH, &sig_action).unwrap();
69 | }
70 |
71 | // also let other codes send events
72 | EVENTS.set(tx).unwrap();
73 |
74 | rx
75 | }
76 |
77 | /// send an event to the main event stream
78 | pub fn send(event: Event) {
79 | EVENTS.get().unwrap().send(event).unwrap();
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/structs/events/mod.rs:
--------------------------------------------------------------------------------
1 | mod event;
2 | pub use event::*;
3 |
4 | mod keyevent;
5 | pub use keyevent::*;
6 |
7 | mod mouseevent;
8 | pub use mouseevent::*;
9 |
10 | mod suppressor;
11 | pub use suppressor::*;
12 |
13 | mod listeners;
14 |
--------------------------------------------------------------------------------
/src/structs/events/mouseevent.rs:
--------------------------------------------------------------------------------
1 | use serde::{Deserialize, Serialize};
2 | use termion::event;
3 |
4 | /// a single mouse event
5 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize)]
6 | pub struct MouseEvent {
7 | /// where the mouse event is
8 | x: u32,
9 | y: u32,
10 | /// what kind of event it is
11 | pub mousetype: MouseType,
12 | }
13 |
14 | impl From for MouseEvent {
15 | fn from(value: event::MouseEvent) -> Self {
16 | match value {
17 | event::MouseEvent::Hold(x, y) => Self {
18 | x: x as u32 - 1,
19 | y: y as u32 - 1,
20 | mousetype: MouseType::Hold,
21 | },
22 | event::MouseEvent::Release(x, y) => Self {
23 | x: x as u32 - 1,
24 | y: y as u32 - 1,
25 | mousetype: MouseType::Release,
26 | },
27 | event::MouseEvent::Press(mousetype, x, y) => Self {
28 | x: x as u32 - 1,
29 | y: y as u32 - 1,
30 | mousetype: mousetype.into(),
31 | },
32 | }
33 | }
34 | }
35 |
36 | /// what kind of mouse event it is
37 | #[derive(Hash, PartialEq, Eq, Serialize, Deserialize, Debug, Clone, Copy)]
38 | pub enum MouseType {
39 | #[serde(rename = "left")]
40 | /// The left mouse button.
41 | Left,
42 | #[serde(rename = "right")]
43 | /// The right mouse button.
44 | Right,
45 | #[serde(rename = "middle")]
46 | /// The middle mouse button.
47 | Middle,
48 | #[serde(rename = "wheelup")]
49 | /// Mouse wheel is going up.
50 | ///
51 | /// This event is typically only used with Mouse::Press.
52 | WheelUp,
53 | #[serde(rename = "wheeldown")]
54 | /// Mouse wheel is going down.
55 | ///
56 | /// This event is typically only used with Mouse::Press.
57 | WheelDown,
58 | #[serde(rename = "release")]
59 | /// mouse release
60 | Release,
61 | #[serde(rename = "hold")]
62 | /// is only emitted when u move the mouse, and only applies to left click
63 | Hold,
64 | }
65 |
66 | impl From for MouseType {
67 | fn from(value: event::MouseButton) -> Self {
68 | match value {
69 | event::MouseButton::Left => Self::Left,
70 | event::MouseButton::Right => Self::Right,
71 | event::MouseButton::Middle => Self::Middle,
72 | event::MouseButton::WheelUp => Self::WheelUp,
73 | event::MouseButton::WheelDown => Self::WheelDown,
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/structs/events/suppressor.rs:
--------------------------------------------------------------------------------
1 | use std::{collections::HashMap, sync::Mutex};
2 |
3 | use tokio::sync::OnceCell;
4 |
5 | use crate::structs::Subscription;
6 |
7 | #[derive(Default)]
8 | pub struct Suppressors {
9 | map: HashMap>,
10 | state_id: u32,
11 | }
12 |
13 | impl Suppressors {
14 | pub fn insert(&mut self, subscription: Subscription, priority: u32) -> u32 {
15 | self.state_id += 1;
16 | let channel = self.map.entry(subscription).or_default();
17 | let item = SuppressItem::new(priority);
18 | let id = item.id;
19 |
20 | for (i, suppressor) in channel.iter().enumerate() {
21 | if suppressor.priority < item.priority {
22 | channel.insert(i, item);
23 | return id;
24 | }
25 | }
26 |
27 | channel.push(item);
28 | id
29 | }
30 |
31 | pub fn remove(&mut self, subscription: Subscription, id: u32) -> bool {
32 | self.state_id += 1;
33 | if let Some(channel) = self.map.get_mut(&subscription) {
34 | if let Some(index) = channel.iter().position(|item| item.id == id) {
35 | channel.remove(index);
36 | if channel.is_empty() {
37 | self.map.remove(&subscription);
38 | }
39 |
40 | return true;
41 | }
42 | }
43 |
44 | false
45 | }
46 |
47 | pub fn suppress_level(&self, channels: &[Subscription]) -> Option {
48 | channels
49 | .iter()
50 | .filter_map(|channel| {
51 | self.map
52 | .get(channel)
53 | .map(|item| item.first().unwrap().priority)
54 | })
55 | .max()
56 | }
57 |
58 | pub fn state_id(&self) -> u32 {
59 | self.state_id
60 | }
61 | }
62 |
63 | pub struct SuppressItem {
64 | pub priority: u32,
65 | pub id: u32,
66 | }
67 |
68 | static SUPPRESSOR_ID: OnceCell> = OnceCell::const_new_with(Mutex::new(0));
69 |
70 | fn gen_id() -> u32 {
71 | let mut id = SUPPRESSOR_ID.get().unwrap().lock().unwrap();
72 | *id += 1;
73 | *id
74 | }
75 |
76 | impl SuppressItem {
77 | pub fn new(priority: u32) -> Self {
78 | Self {
79 | priority,
80 | id: gen_id(),
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/structs/mod.rs:
--------------------------------------------------------------------------------
1 | mod events;
2 | pub use events::*;
3 |
4 | mod requests;
5 | pub use requests::*;
6 |
7 | mod error;
8 | pub use error::*;
9 |
10 | mod responses;
11 | pub use responses::*;
12 |
13 | mod component;
14 | pub use component::*;
15 |
16 | mod data;
17 | pub use data::*;
18 |
--------------------------------------------------------------------------------
/src/structs/requests/mod.rs:
--------------------------------------------------------------------------------
1 | mod request;
2 | pub use request::*;
3 |
4 | mod requestcontent;
5 | pub use requestcontent::*;
6 |
7 | mod render_request;
8 | pub use render_request::*;
9 |
--------------------------------------------------------------------------------
/src/structs/requests/render_request.rs:
--------------------------------------------------------------------------------
1 | use serde::Deserialize;
2 | use std::io::Write;
3 | use termion::{color, cursor};
4 |
5 | use crate::values::Term;
6 |
7 | #[derive(Deserialize, Clone, PartialEq, Eq, Debug)]
8 | #[serde(tag = "type")]
9 | pub enum RenderRequest {
10 | #[serde(rename = "set char")]
11 | /// set a character at a specific location
12 | SetChar { x: u32, y: u32, c: char },
13 | #[serde(rename = "set colouredchar")]
14 | /// set a character at a specific locaton with fg and bg colours
15 | SetCharColoured {
16 | x: u32,
17 | y: u32,
18 | c: char,
19 | fg: Colour,
20 | bg: Colour,
21 | },
22 | #[serde(rename = "flush")]
23 | /// flush all changes
24 | Flush,
25 | #[serde(rename = "set cursorstyle")]
26 | /// change cursor style
27 | SetCursorStyle { style: CursorStyle },
28 | #[serde(rename = "hide cursor")]
29 | /// hide cursor
30 | HideCursor,
31 | #[serde(rename = "show cursor")]
32 | /// show cursor
33 | ShowCursor,
34 |
35 | #[serde(rename = "clear all")]
36 | /// clear entire screen
37 | ClearAll,
38 |
39 | #[serde(rename = "clear area")]
40 | /// clear a specified area
41 | ClearArea {
42 | x: u32,
43 | y: u32,
44 | width: u32,
45 | height: u32,
46 | },
47 |
48 | #[serde(rename = "render multiple")]
49 | /// complete multiple render tasks at the same time - e.g. stacking changes
50 | RenderMultiple { tasks: Vec },
51 | }
52 |
53 | impl RenderRequest {
54 | pub fn draw(&self, term: &mut Term, mut flush: bool) {
55 | match self {
56 | Self::ClearArea {
57 | x,
58 | y,
59 | width,
60 | height,
61 | } => {
62 | write!(
63 | term,
64 | "{}{}",
65 | color::Fg(termion::color::Reset),
66 | color::Bg(termion::color::Reset)
67 | )
68 | .unwrap();
69 | for y in *y..*y + *height {
70 | for x in *x..*x + *width {
71 | write!(
72 | term,
73 | "{} ",
74 | termion::cursor::Goto(x as u16 + 1, y as u16 + 1)
75 | )
76 | .unwrap();
77 | }
78 | }
79 | }
80 | Self::SetChar { x, y, c } => {
81 | write!(
82 | term,
83 | "{}{c}",
84 | termion::cursor::Goto(*x as u16 + 1, *y as u16 + 1)
85 | )
86 | .unwrap();
87 | }
88 | Self::SetCharColoured { x, y, c, fg, bg } => {
89 | write!(
90 | term,
91 | "{}{}{}{c}{}{}",
92 | color::Fg(*fg),
93 | color::Bg(*bg),
94 | termion::cursor::Goto(*x as u16 + 1, *y as u16 + 1),
95 | color::Fg(termion::color::Reset),
96 | color::Bg(termion::color::Reset),
97 | )
98 | .unwrap();
99 | }
100 | Self::Flush => flush = true,
101 | Self::SetCursorStyle { style } => match style {
102 | CursorStyle::BlinkingBar => write!(term, "{}", cursor::BlinkingBar),
103 | CursorStyle::BlinkingBlock => write!(term, "{}", cursor::BlinkingBlock),
104 | CursorStyle::BlinkingUnderline => write!(term, "{}", cursor::BlinkingUnderline),
105 | CursorStyle::SteadyBar => {
106 | write!(term, "{}", cursor::SteadyBar)
107 | }
108 | CursorStyle::SteadyBlock => write!(term, "{}", cursor::SteadyBlock),
109 | CursorStyle::SteadyUnderline => write!(term, "{}", cursor::SteadyUnderline),
110 | }
111 | .unwrap(),
112 | Self::HideCursor => write!(term, "{}", cursor::Hide).unwrap(),
113 | Self::ShowCursor => write!(term, "{}", cursor::Show).unwrap(),
114 | Self::RenderMultiple { tasks } => {
115 | for task in tasks.clone() {
116 | task.draw(term, false);
117 | }
118 | }
119 | Self::ClearAll => write!(term, "{}", termion::clear::All).unwrap(),
120 | }
121 |
122 | if flush {
123 | term.flush().unwrap();
124 | }
125 | }
126 | }
127 |
128 | #[derive(Deserialize, Clone, PartialEq, Eq, Debug)]
129 | pub enum CursorStyle {
130 | #[serde(rename = "blinking bar")]
131 | BlinkingBar,
132 | #[serde(rename = "blinking block")]
133 | BlinkingBlock,
134 | #[serde(rename = "blinking underline")]
135 | BlinkingUnderline,
136 | #[serde(rename = "steady bar")]
137 | SteadyBar,
138 | #[serde(rename = "steady block")]
139 | SteadyBlock,
140 | #[serde(rename = "steady underline")]
141 | SteadyUnderline,
142 | }
143 |
144 | #[derive(Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
145 | #[serde(tag = "type")]
146 | pub enum Colour {
147 | #[serde(rename = "black")]
148 | Black,
149 | #[serde(rename = "blue")]
150 | Blue,
151 | #[serde(rename = "cyan")]
152 | Cyan,
153 | #[serde(rename = "green")]
154 | Green,
155 | #[serde(rename = "magenta")]
156 | Magenta,
157 | #[serde(rename = "red")]
158 | Red,
159 | #[serde(rename = "white")]
160 | White,
161 | #[serde(rename = "yellow")]
162 | Yellow,
163 |
164 | #[serde(rename = "lightblack")]
165 | LightBlack,
166 | #[serde(rename = "lightblue")]
167 | LightBlue,
168 | #[serde(rename = "lightcyan")]
169 | LightCyan,
170 | #[serde(rename = "lightgreen")]
171 | LightGreen,
172 | #[serde(rename = "lightmagenta")]
173 | LightMagenta,
174 | #[serde(rename = "lightred")]
175 | LightRed,
176 | #[serde(rename = "lightwhite")]
177 | LightWhite,
178 | #[serde(rename = "lightyellow")]
179 | LightYellow,
180 |
181 | #[serde(rename = "reset")]
182 | Reset,
183 | #[serde(rename = "ansi")]
184 | Ansi { value: u8 },
185 | #[serde(rename = "rgb")]
186 | Rgb { red: u8, green: u8, blue: u8 },
187 | }
188 |
189 | impl termion::color::Color for Colour {
190 | fn write_fg(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
191 | match self {
192 | Self::Black => termion::color::Black.write_fg(f),
193 | Self::Blue => termion::color::Blue.write_fg(f),
194 | Self::Cyan => termion::color::Cyan.write_fg(f),
195 | Self::Green => termion::color::Green.write_fg(f),
196 | Self::Red => termion::color::Red.write_fg(f),
197 | Self::Magenta => termion::color::Magenta.write_fg(f),
198 | Self::White => termion::color::White.write_fg(f),
199 | Self::Yellow => termion::color::Yellow.write_fg(f),
200 |
201 | Self::LightBlack => termion::color::LightBlack.write_fg(f),
202 | Self::LightBlue => termion::color::LightBlue.write_fg(f),
203 | Self::LightCyan => termion::color::LightCyan.write_fg(f),
204 | Self::LightGreen => termion::color::LightGreen.write_fg(f),
205 | Self::LightMagenta => termion::color::LightMagenta.write_fg(f),
206 | Self::LightRed => termion::color::LightRed.write_fg(f),
207 | Self::LightWhite => termion::color::LightWhite.write_fg(f),
208 | Self::LightYellow => termion::color::LightYellow.write_fg(f),
209 |
210 | Self::Reset => termion::color::Reset.write_fg(f),
211 | Self::Rgb { red, green, blue } => termion::color::Rgb(*red, *green, *blue).write_fg(f),
212 | Self::Ansi { value } => termion::color::AnsiValue(*value).write_fg(f),
213 | }
214 | }
215 |
216 | fn write_bg(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
217 | match self {
218 | Self::Black => termion::color::Black.write_bg(f),
219 | Self::Blue => termion::color::Blue.write_bg(f),
220 | Self::Cyan => termion::color::Cyan.write_bg(f),
221 | Self::Green => termion::color::Green.write_bg(f),
222 | Self::Red => termion::color::Red.write_bg(f),
223 | Self::Magenta => termion::color::Magenta.write_bg(f),
224 | Self::White => termion::color::White.write_bg(f),
225 | Self::Yellow => termion::color::Yellow.write_bg(f),
226 |
227 | Self::LightBlack => termion::color::LightBlack.write_bg(f),
228 | Self::LightBlue => termion::color::LightBlue.write_bg(f),
229 | Self::LightCyan => termion::color::LightCyan.write_bg(f),
230 | Self::LightGreen => termion::color::LightGreen.write_bg(f),
231 | Self::LightMagenta => termion::color::LightMagenta.write_bg(f),
232 | Self::LightRed => termion::color::LightRed.write_bg(f),
233 | Self::LightWhite => termion::color::LightWhite.write_bg(f),
234 | Self::LightYellow => termion::color::LightYellow.write_bg(f),
235 |
236 | Self::Reset => termion::color::Reset.write_bg(f),
237 | Self::Rgb { red, green, blue } => termion::color::Rgb(*red, *green, *blue).write_bg(f),
238 | Self::Ansi { value } => termion::color::AnsiValue(*value).write_bg(f),
239 | }
240 | }
241 | }
242 |
--------------------------------------------------------------------------------
/src/structs/requests/request.rs:
--------------------------------------------------------------------------------
1 | use std::sync::Mutex;
2 |
3 | use crate::structs::{Discriminator, Event, Packet, Response, ResponseContent, Subscription};
4 |
5 | use super::RequestContent;
6 | use serde::Deserialize;
7 | use tokio::sync::OnceCell;
8 |
9 | /// a signal that comes from a subprocess
10 | #[derive(Deserialize, Debug, Clone)]
11 | pub struct Request {
12 | /// reciever
13 | target: Discriminator,
14 | /// the content of the request
15 | content: RequestContent,
16 | /// confirmation identifier
17 | id: u32,
18 | }
19 |
20 | /// for generated requests not coming from a process
21 | static REQ_ALTID: OnceCell> = OnceCell::const_new_with(Mutex::new(u32::MAX));
22 |
23 | fn req_id() -> u32 {
24 | let mut id = REQ_ALTID.get().unwrap().lock().unwrap();
25 | *id -= 1;
26 | *id
27 | }
28 |
29 | impl Request {
30 | /// construct new self
31 | pub fn new(target: Discriminator, content: RequestContent) -> Self {
32 | Self {
33 | target,
34 | content,
35 | id: req_id(),
36 | }
37 | }
38 | /// returns discrim of target component
39 | pub fn target(&self) -> &Discriminator {
40 | &self.target
41 | }
42 |
43 | /// returns discrim of target component (mutable)
44 | pub fn target_mut(&mut self) -> &mut Discriminator {
45 | &mut self.target
46 | }
47 |
48 | /// returns RequestContent (mutable)
49 | pub fn content_mut(&mut self) -> &mut RequestContent {
50 | &mut self.content
51 | }
52 |
53 | /// returns RequestContent
54 | pub fn content(&self) -> &RequestContent {
55 | &self.content
56 | }
57 |
58 | /// send self to master space, and wait for response
59 | pub async fn send(self) -> Response {
60 | let (packet, recv) = Packet::new(self);
61 | Event::send(Event::from_packet(packet));
62 |
63 | if let Ok(res) = recv.await {
64 | res
65 | } else {
66 | Response::new(ResponseContent::Undelivered)
67 | }
68 | }
69 |
70 | /// get request id
71 | pub fn id(&self) -> &u32 {
72 | &self.id
73 | }
74 |
75 | /// returns subscriptions that would want to take in self
76 | pub fn subscriptions(&self) -> Option> {
77 | match &self.content {
78 | RequestContent::Message { sender, tag, .. } => Some(vec![
79 | Subscription::AllMessages,
80 | Subscription::SpecificMessage {
81 | source: sender.clone(),
82 | },
83 | Subscription::SpecificMessageTag { tag: tag.clone() },
84 | ]),
85 | _ => None,
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/structs/requests/requestcontent.rs:
--------------------------------------------------------------------------------
1 | use std::{collections::BTreeMap, path::PathBuf};
2 |
3 | use serde::Deserialize;
4 | use serde_json::Value;
5 | use tokio::sync::mpsc::UnboundedSender;
6 |
7 | use crate::structs::{Discriminator, Response, Subscription};
8 |
9 | use super::RenderRequest;
10 |
11 | /// variations of requests
12 | #[derive(Deserialize, Clone, PartialEq, Eq, Debug)]
13 | #[serde(tag = "type")]
14 | pub enum RequestContent {
15 | #[serde(rename = "confirm recieve")]
16 | /// confirm that an event has been recieved
17 | ConfirmRecieve {
18 | /// event id
19 | id: u32,
20 | /// true = does not capture event
21 | pass: bool,
22 | },
23 |
24 | #[serde(rename = "subscribe")]
25 | /// add subscription to a channel with priority
26 | Subscribe {
27 | channel: Subscription,
28 | priority: Option,
29 | component: Option,
30 | },
31 |
32 | #[serde(rename = "Unsubscribe")]
33 | /// remove subscription from a channel
34 | Unsubscribe {
35 | channel: Subscription,
36 | component: Option,
37 | },
38 | #[serde(rename = "set socket")]
39 | /// sent responses to this socket
40 | SetSocket {
41 | path: PathBuf,
42 | },
43 |
44 | #[serde(rename = "drop")]
45 | /// remove a single component
46 | Drop {
47 | discrim: Option,
48 | },
49 |
50 | #[serde(rename = "render")]
51 | /// render something to the terminal
52 | Render {
53 | content: RenderRequest,
54 | flush: bool,
55 | },
56 |
57 | #[serde(rename = "spawn")]
58 | /// spawn a new process
59 | Spawn {
60 | command: String,
61 | args: Vec,
62 | label: String,
63 | env: BTreeMap,
64 | },
65 |
66 | #[serde(rename = "message")]
67 | /// send a message to another component
68 | /// if target specifies a space,
69 | /// all components under that space will recieve the message
70 | Message {
71 | content: Value,
72 | sender: Discriminator,
73 | target: Discriminator,
74 | tag: String,
75 | },
76 |
77 | /// create a new space at a space
78 | #[serde(rename = "new space")]
79 | NewSpace {
80 | label: String,
81 | },
82 |
83 | /// focus a specific space
84 | #[serde(rename = "focus at")]
85 | FocusAt,
86 |
87 | /// get a state value
88 | #[serde(rename = "get state")]
89 | GetState {
90 | label: StateValue,
91 | },
92 |
93 | /// get value of an entry
94 | #[serde(rename = "get entry")]
95 | GetEntry {
96 | label: String,
97 | },
98 |
99 | /// remove an entry
100 | #[serde(rename = "remove entry")]
101 | RemoveEntry {
102 | label: String,
103 | },
104 |
105 | /// get value of an entry
106 | #[serde(rename = "set entry")]
107 | SetEntry {
108 | label: String,
109 | value: Value,
110 | },
111 |
112 | /// watch a certain value in pool
113 | #[serde(rename = "watch")]
114 | Watch {
115 | label: String,
116 | },
117 |
118 | /// watch a certain value in pool
119 | #[serde(rename = "unwatch")]
120 | Unwatch {
121 | label: String,
122 | watcher: Discriminator,
123 | },
124 |
125 | /// suppress a channel
126 | #[serde(rename = "suppress")]
127 | Suppress {
128 | channel: Subscription,
129 | priority: u32,
130 | },
131 |
132 | /// unsuppress a channel
133 | #[serde(rename = "unsuppress")]
134 | Unsuppress {
135 | channel: Subscription,
136 | id: u32,
137 | },
138 |
139 | WatchInternal(WatchInternal),
140 | }
141 |
142 | /// variations of requests
143 | #[derive(Deserialize, Clone, PartialEq, Eq, Debug)]
144 | pub enum StateValue {
145 | #[serde(rename = "focused")]
146 | Focused,
147 | #[serde(rename = "is focused")]
148 | IsFocused,
149 | #[serde(rename = "term size")]
150 | TermSize,
151 | #[serde(rename = "working dir")]
152 | WorkingDir,
153 | }
154 |
155 | #[derive(Debug, Clone)]
156 | pub struct WatchInternal {
157 | pub label: String,
158 | pub sender: UnboundedSender,
159 | pub watcher: Discriminator,
160 | }
161 |
162 | impl PartialEq for WatchInternal {
163 | fn eq(&self, _: &Self) -> bool {
164 | false
165 | }
166 | }
167 |
168 | impl Eq for WatchInternal {}
169 |
170 | // this will never get called, so dw about it
171 | impl<'de> Deserialize<'de> for WatchInternal {
172 | fn deserialize(_: D) -> Result
173 | where
174 | D: serde::Deserializer<'de>,
175 | {
176 | panic!("no")
177 | }
178 |
179 | fn deserialize_in_place(_: D, _: &mut Self) -> Result<(), D::Error>
180 | where
181 | D: serde::Deserializer<'de>,
182 | {
183 | panic!("no")
184 | }
185 | }
186 |
--------------------------------------------------------------------------------
/src/structs/responses/event_serde.rs:
--------------------------------------------------------------------------------
1 | use crate::structs::{Discriminator, Event, KeyEvent, MouseEvent};
2 |
3 | use serde::Serialize;
4 | use serde_json::Value;
5 |
6 | #[derive(Serialize, Clone, PartialEq, Debug)]
7 | #[serde(tag = "type")]
8 | pub enum EventSerde {
9 | /// keyboard event
10 | #[serde(rename = "key")]
11 | Key(KeyEvent),
12 | /// mouse event
13 | #[serde(rename = "mouse")]
14 | Mouse(MouseEvent),
15 | /// screen resize event (should trigger a rerender)
16 | #[serde(rename = "resize")]
17 | Resize { width: u32, height: u32 },
18 | /// message passed from another process
19 | #[serde(rename = "message")]
20 | Message {
21 | sender: Discriminator,
22 | target: Discriminator,
23 | content: Value,
24 | tag: String,
25 | },
26 | #[serde(rename = "focused")]
27 | Focused,
28 | #[serde(rename = "unfocused")]
29 | Unfocused,
30 | #[serde(rename = "value updated")]
31 | ValueUpdated {
32 | label: String,
33 | new: Value,
34 | discrim: Discriminator,
35 | },
36 | #[serde(rename = "value removed")]
37 | ValueRemoved {
38 | label: String,
39 | discrim: Discriminator,
40 | },
41 | }
42 |
43 | impl EventSerde {
44 | pub fn from_event(value: &Event) -> Self {
45 | match value {
46 | Event::KeyPress(key) => Self::Key(*key),
47 | Event::ScreenResize(width, height) => Self::Resize {
48 | width: *width,
49 | height: *height,
50 | },
51 | Event::MouseEvent(mouse) => Self::Mouse(*mouse),
52 | Event::Message {
53 | sender,
54 | target,
55 | content,
56 | tag,
57 | } => Self::Message {
58 | sender: sender.clone(),
59 | target: target.clone(),
60 | content: content.clone(),
61 | tag: tag.clone(),
62 | },
63 | Event::Focus { .. } => Self::Focused,
64 | Event::Unfocus => Self::Unfocused,
65 | Event::RequestPacket(_) => unreachable!("should not happend"),
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/structs/responses/mod.rs:
--------------------------------------------------------------------------------
1 | mod response;
2 | pub use response::*;
3 |
4 | mod responsecontent;
5 | pub use responsecontent::*;
6 |
7 | mod event_serde;
8 | pub use event_serde::*;
9 |
10 | mod response_error;
11 | pub use response_error::*;
12 |
13 | mod response_success;
14 | pub use response_success::*;
15 |
--------------------------------------------------------------------------------
/src/structs/responses/response.rs:
--------------------------------------------------------------------------------
1 | use std::sync::Mutex;
2 |
3 | use serde::Serialize;
4 | use tokio::sync::OnceCell;
5 |
6 | use super::ResponseContent;
7 |
8 | static RESPONSE_ID: OnceCell> = OnceCell::const_new_with(Mutex::new(0));
9 |
10 | fn resp_id() -> u32 {
11 | let mut id = RESPONSE_ID.get().unwrap().lock().unwrap();
12 | *id += 1;
13 | *id
14 | }
15 |
16 | /// a return signal back to a subprocess
17 | #[derive(Serialize, Clone, PartialEq, Debug)]
18 | pub struct Response {
19 | /// the content of the response
20 | content: ResponseContent,
21 |
22 | /// send a confirmation to the server using this id
23 | /// to confirm recieved
24 | id: u32,
25 |
26 | /// request id for confirmation
27 | #[serde(skip_serializing_if = "Option::is_none")]
28 | request: Option,
29 | }
30 |
31 | impl Response {
32 | /// construct new self
33 | pub fn new(content: ResponseContent) -> Self {
34 | Self {
35 | content,
36 | id: resp_id(),
37 | request: None,
38 | }
39 | }
40 |
41 | /// construct new self as a response to a request
42 | pub fn new_with_request(content: ResponseContent, request: u32) -> Self {
43 | Self {
44 | content,
45 | id: resp_id(),
46 | request: Some(request),
47 | }
48 | }
49 |
50 | /// get id of self
51 | pub fn id(&self) -> u32 {
52 | self.id
53 | }
54 |
55 | /// get content of self
56 | pub fn content(&self) -> &ResponseContent {
57 | &self.content
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/structs/responses/response_error.rs:
--------------------------------------------------------------------------------
1 | use serde::Serialize;
2 |
3 | #[derive(Serialize, Clone, PartialEq, Debug)]
4 | #[serde(tag = "type")]
5 | pub enum ResponseError {
6 | /// target component is not found
7 | #[serde(rename = "component not found")]
8 | ComponentNotFound,
9 | /// spawning process failed
10 | #[serde(rename = "spawn failed")]
11 | SpawnFailed,
12 | /// pool entry not found
13 | #[serde(rename = "entry not found")]
14 | EntryNotFound,
15 | }
16 |
--------------------------------------------------------------------------------
/src/structs/responses/response_success.rs:
--------------------------------------------------------------------------------
1 | use serde::Serialize;
2 | use serde_json::Value;
3 |
4 | use crate::structs::Discriminator;
5 |
6 | #[derive(Serialize, Clone, PartialEq, Debug)]
7 | #[serde(tag = "type")]
8 | pub enum ResponseSuccess {
9 | /// subscription added
10 | #[serde(rename = "subscribe added")]
11 | SubscribeAdded,
12 |
13 | /// subscription removed
14 | #[serde(rename = "subscribe removed")]
15 | SubscribeRemoved,
16 |
17 | /// listener socket set
18 | #[serde(rename = "listener set")]
19 | ListenerSet { discrim: Discriminator },
20 |
21 | /// component dropped
22 | #[serde(rename = "dropped")]
23 | Dropped,
24 |
25 | /// render task completed
26 | #[serde(rename = "rendered")]
27 | Rendered,
28 |
29 | /// process spawned with discrim
30 | #[serde(rename = "spawned")]
31 | Spawned { discrim: Discriminator },
32 |
33 | /// message delivered ot target
34 | #[serde(rename = "message delivered")]
35 | MessageDelivered,
36 |
37 | /// space created with discrim
38 | #[serde(rename = "space created")]
39 | SpaceCreated { discrim: Discriminator },
40 |
41 | /// focus changed successfully
42 | #[serde(rename = "focus changed")]
43 | FocusChanged,
44 |
45 | /// got state
46 | #[serde(rename = "value")]
47 | Value { value: Value },
48 |
49 | /// set value
50 | #[serde(rename = "value set")]
51 | ValueSet,
52 |
53 | /// value removed
54 | #[serde(rename = "removed value")]
55 | RemovedValue,
56 |
57 | /// now watching a value
58 | #[serde(rename = "watching")]
59 | Watching,
60 |
61 | /// unwatched a value
62 | #[serde(rename = "unwatched")]
63 | Unwatched,
64 |
65 | /// suppressing a channel
66 | #[serde(rename = "suppressed")]
67 | Suppressed { id: u32 },
68 |
69 | /// unsuppressing a channel
70 | #[serde(rename = "unsuppressed")]
71 | Unsuppressed,
72 | }
73 |
--------------------------------------------------------------------------------
/src/structs/responses/responsecontent.rs:
--------------------------------------------------------------------------------
1 | use std::path::PathBuf;
2 |
3 | use serde::Serialize;
4 |
5 | use super::{EventSerde, ResponseError, ResponseSuccess};
6 |
7 | #[derive(Serialize, Clone, PartialEq, Debug)]
8 | #[serde(tag = "type")]
9 | pub enum ResponseContent {
10 | #[serde(rename = "undelivered")]
11 | Undelivered,
12 |
13 | #[serde(rename = "event")]
14 | Event { content: EventSerde },
15 |
16 | #[serde(rename = "error")]
17 | Error { content: ResponseError },
18 |
19 | #[serde(rename = "success")]
20 | Success { content: ResponseSuccess },
21 |
22 | /// will not recieve this
23 | #[serde(rename = "set socket")]
24 | SetSocket(PathBuf),
25 | }
26 |
--------------------------------------------------------------------------------
/src/term/commands.rs:
--------------------------------------------------------------------------------
1 | use std::process;
2 |
3 | pub fn commands() -> Vec> {
4 | let args: Vec = std::env::args().skip(1).collect();
5 |
6 | let mut commands = Vec::new();
7 | let mut command = Vec::new();
8 |
9 | for arg in args.into_iter() {
10 | if arg == "$" {
11 | if command.len() < 2 {
12 | println!("Bad arguments: expect `ccanvas [label] [command] (args..)`");
13 | process::exit(-1);
14 | }
15 | commands.push(std::mem::take(&mut command));
16 | continue;
17 | }
18 |
19 | command.push(arg)
20 | }
21 |
22 | if !command.is_empty() {
23 | if command.len() < 2 {
24 | println!("Bad arguments: expect `ccanvas [label] [command] (args..)`");
25 | process::exit(-1);
26 | }
27 | commands.push(std::mem::take(&mut command));
28 | }
29 |
30 | if commands.is_empty() {
31 | println!("Bad arguments: expect `ccanvas [label] [command] (args..)`");
32 | process::exit(-1);
33 | }
34 |
35 | commands
36 | }
37 |
--------------------------------------------------------------------------------
/src/term/enter.rs:
--------------------------------------------------------------------------------
1 | use std::{
2 | fs,
3 | io::{stdout, Write},
4 | path::PathBuf,
5 | process,
6 | sync::Mutex,
7 | };
8 |
9 | use termion::{input::MouseTerminal, raw::IntoRawMode, screen::IntoAlternateScreen};
10 |
11 | use crate::{
12 | structs::{Discriminator, Storage},
13 | values::{FOCUSED, ROOT, SCREEN},
14 | };
15 |
16 | /// run when entering
17 | pub async fn init() {
18 | let root = PathBuf::from("/tmp")
19 | .join("ccanvas")
20 | .join(process::id().to_string());
21 |
22 | Storage::remove_if_exist(&root).await.unwrap();
23 |
24 | fs::create_dir_all(&root).unwrap();
25 | ROOT.set(root).unwrap();
26 |
27 | #[cfg(feature = "log")]
28 | {
29 | let log_file = dirs::data_dir().unwrap().join("ccanvas.log");
30 | simplelog::WriteLogger::init(
31 | log::LevelFilter::Trace,
32 | simplelog::ConfigBuilder::new()
33 | .set_max_level(log::LevelFilter::Trace)
34 | .set_location_level(log::LevelFilter::Trace)
35 | .build(),
36 | std::fs::OpenOptions::new()
37 | .write(true)
38 | .create(true)
39 | .truncate(true)
40 | .open(log_file)
41 | .unwrap(),
42 | )
43 | .unwrap();
44 | }
45 | }
46 |
47 | pub fn enter() {
48 | let mut screen = MouseTerminal::from(
49 | stdout()
50 | .into_raw_mode()
51 | .unwrap()
52 | .into_alternate_screen()
53 | .unwrap(),
54 | );
55 | write!(screen, "{}", termion::clear::All).unwrap();
56 | screen.flush().unwrap();
57 | FOCUSED.set(Mutex::new(Discriminator::master())).unwrap();
58 | let _ = SCREEN.set(Mutex::new(Some(screen)));
59 | }
60 |
--------------------------------------------------------------------------------
/src/term/exit.rs:
--------------------------------------------------------------------------------
1 | use nix::sys::signal::{self, SigHandler, Signal};
2 |
3 | use crate::values::{ROOT, SCREEN};
4 | use std::{fs, io::Write};
5 |
6 | /// run when exiting
7 | pub async fn exit() {
8 | write!(
9 | SCREEN.get().unwrap().lock().unwrap().as_mut().unwrap(),
10 | "{}{}{}",
11 | termion::cursor::Show,
12 | termion::cursor::Restore,
13 | termion::screen::ToMainScreen,
14 | )
15 | .unwrap();
16 |
17 | // changes the sig handler back to default
18 | unsafe {
19 | signal::sigaction(
20 | Signal::SIGWINCH,
21 | &signal::SigAction::new(
22 | SigHandler::SigDfl,
23 | signal::SaFlags::empty(),
24 | signal::SigSet::empty(),
25 | ),
26 | )
27 | .unwrap();
28 | }
29 |
30 | // drop screen so the term actually gets restored
31 | *SCREEN.get().unwrap().lock().unwrap() = None;
32 | fs::remove_dir_all(ROOT.get().unwrap()).unwrap();
33 | }
34 |
--------------------------------------------------------------------------------
/src/term/mod.rs:
--------------------------------------------------------------------------------
1 | mod enter;
2 | pub use enter::*;
3 |
4 | mod exit;
5 | pub use exit::*;
6 |
7 | mod commands;
8 | pub use commands::*;
9 |
--------------------------------------------------------------------------------
/src/traits/component.rs:
--------------------------------------------------------------------------------
1 | use async_trait::async_trait;
2 |
3 | use crate::structs::{Discriminator, Event, Storage, Unevaluated};
4 |
5 | #[async_trait]
6 | /// a unit of "something"
7 | pub trait Component {
8 | /// unique identifier of what it is
9 | fn label(&self) -> &str;
10 |
11 | /// unique identifier which one it is
12 | fn discrim(&self) -> &Discriminator;
13 |
14 | /// folder for shared storage
15 | fn storage(&self) -> &Storage;
16 |
17 | /// pass an event into a component
18 | /// returns true to pass event to next component, false otherwise
19 | async fn pass(&self, event: &mut Event, suppress_level: Option) -> Unevaluated;
20 | }
21 |
--------------------------------------------------------------------------------
/src/traits/mod.rs:
--------------------------------------------------------------------------------
1 | mod component;
2 | pub use component::*;
3 |
--------------------------------------------------------------------------------
/src/values.rs:
--------------------------------------------------------------------------------
1 | use std::{io::Stdout, path::PathBuf, sync::Mutex};
2 |
3 | use termion::{input::MouseTerminal, raw::RawTerminal, screen::AlternateScreen};
4 | use tokio::sync::OnceCell;
5 |
6 | use crate::structs::Discriminator;
7 |
8 | pub type Term = MouseTerminal>>;
9 |
10 | pub static FOCUSED: OnceCell> = OnceCell::const_new();
11 | pub static SCREEN: OnceCell>> = OnceCell::const_new();
12 | pub static ROOT: OnceCell = OnceCell::const_new();
13 |
--------------------------------------------------------------------------------