1
0
Fork 0

Compare commits

..

217 Commits

Author SHA1 Message Date
Zynh Ludwig a25e6ae626 rose-pine? 2024-09-06 03:53:04 -07:00
mistricky c2924bf6c9 [Release] 1.6.0 2024-07-30 07:40:38 +00:00
mistricky 4c25f276f6 [Update] generator link library on linux-x86_64 2024-07-30 07:40:15 +00:00
mistricky 5889223619 [Update] generator link library on mac-aarch64 2024-07-30 07:39:57 +00:00
mistricky dbfdd02bcc [Update] generator link library on mac-x86_64 2024-07-30 07:39:47 +00:00
Mist 87b2770f13
[Release] v1.6.0 2024-07-30 15:37:48 +08:00
mistricky 3f2ba7460b [Release] 1.5.2 2024-07-30 07:36:42 +00:00
The Mist 838cf0b66f
[Revert] v1.5.2 2024-07-30 15:35:42 +08:00
Uzair Aftab 538b717bb4
[Chore] update dependencies (#125)
* [Chore] Update dependencies

* [Chore]: Rename .cargo/config to .cargo/config.toml
2024-07-30 15:16:26 +08:00
mistricky beb628156d [Release] 1.6.0 2024-07-30 07:12:09 +00:00
Mist 2620e409f5
[Release] 1.6.0 2024-07-30 15:10:48 +08:00
The Mist ef8c9bca99
[Perf] wrap platform utils and refactor the logic to get default (#126)
save_path
2024-07-30 15:06:11 +08:00
github-actions[bot] a8bba8a5f1
chore: update contributors [skip ci] 2024-07-30 06:11:34 +00:00
Uzair Aftab f49e3bde85
[Feat] Default to `XDG_PICTURES_DIR` for save path (#124)
* [Feature] Use XDG_Picture_dir as fallback

* [Doc]: Add in new default behaviour for save_path
2024-07-30 14:11:20 +08:00
mistricky 06d8e345e7 [Release] 1.5.2 2024-07-10 06:20:05 +00:00
mistricky 73d836daf3 [Update] generator link library on linux-x86_64 2024-07-10 06:19:42 +00:00
mistricky 9860628c80 [Update] generator link library on mac-x86_64 2024-07-10 06:19:08 +00:00
mistricky e6b0aa4122 [Update] generator link library on mac-aarch64 2024-07-10 06:19:05 +00:00
Mist 2fc15dcb61
[Release] v1.5.2 2024-07-10 14:17:27 +08:00
The Mist 1edf45e582
[Fix] replace tab with spaces before take ascii snapshots (#120) 2024-07-10 14:16:20 +08:00
The Mist f70596a74b
[Doc] add more features 2024-07-08 21:05:02 +08:00
mistricky 6755ac6335 chore(docs): update TOC 2024-07-08 10:25:47 +00:00
The Mist de8f961e00
[Doc] windows installation chapter 2024-07-08 18:25:30 +08:00
mistricky 188f741c65 [Release] 1.5.1 2024-07-08 09:03:55 +00:00
mistricky 4b2aee0c40 [Update] generator link library on linux-x86_64 2024-07-08 09:03:30 +00:00
mistricky 68bb1cead8 [Update] generator link library on mac-aarch64 2024-07-08 09:03:10 +00:00
mistricky 8a7656adeb [Update] generator link library on mac-x86_64 2024-07-08 09:03:05 +00:00
Mist 3b7fc26930
[Release] v1.5.1 2024-07-08 17:01:21 +08:00
The Mist 06bba0f747
[Fix] copy not working on Linux (#117) 2024-07-08 16:59:35 +08:00
mistricky daa3d1e8f5 chore(docs): update TOC 2024-07-05 09:48:19 +00:00
The Mist 8346ee9a75
[Update] add usage instruction for CodeSnapASCII 2024-07-05 17:48:06 +08:00
mistricky 553621c0f0 [Update] generator link library on linux-x86_64 2024-07-05 09:20:53 +00:00
mistricky eb867dea3c [Release] 1.5.0 2024-07-05 09:04:00 +00:00
mistricky 19821e02ee [Update] generator link library on mac-aarch64 2024-07-05 09:03:37 +00:00
mistricky 9ce24006a8 [Update] generator link library on mac-x86_64 2024-07-05 09:03:14 +00:00
Mist bbbc36ce3d
[Release] v1.5.0 2024-07-05 17:01:26 +08:00
The Mist b3e3c23146
[Feat] support for take code snapshot in ASCII art format ^ ^ (#114)
* [Refactor] separate calc_wh_with_min_width from calc_wh

* [Feat] support take code snapshot as ascii art

* [Fix] incorrect line number

* [Feat] remove unused logger
2024-07-05 17:00:50 +08:00
The Mist 8f03a0795b
[Update] color of rust badge 2024-07-04 14:41:57 +08:00
The Mist 48aa5497b4
[Doc] change the `null` to `nil` in Lua code snippet (#113) 2024-07-04 14:23:29 +08:00
mistricky 6367c2d41b chore(docs): update TOC 2024-07-04 06:04:50 +00:00
mistricky dd03542f05 [Update] generator link library on mac-x86_64 2024-07-04 06:02:26 +00:00
mistricky bc2c8077ba [Release] 1.4.1 2024-07-04 05:53:55 +00:00
mistricky c2dc0f1f4d [Update] generator link library on linux-x86_64 2024-07-04 05:53:33 +00:00
mistricky ad17ca08e6 [Update] generator link library on mac-aarch64 2024-07-04 05:53:16 +00:00
Mist fbbe244045
[Release] v1.4.1 2024-07-04 13:51:30 +08:00
github-actions[bot] 020163be03
chore: update contributors [skip ci] 2024-07-04 05:50:17 +00:00
The Mist cb3d1a536e
[Feat] add `bg_x_padding`, `bg_y_padding` and `bg_padding` to allows users can customize background padding of snapshot (#112)
* [Feat] add config allow users can customize background padding

* [Update] rename config items which related background config

* [Update] add config to allow users customize the padding of background
2024-07-04 13:50:06 +08:00
The Mist 08d7588ea0
[Update] ignore all .so files (#111) 2024-07-03 16:59:40 +08:00
mistricky 24c0e3ba06 [Release] 1.4.0 2024-07-03 08:41:16 +00:00
mistricky cfddce68a1 [Update] generator link library on mac-x86_64 2024-07-03 08:40:55 +00:00
mistricky 44d9386fe0 [Update] generator link library on linux-x86_64 2024-07-03 08:40:47 +00:00
mistricky 4e35cc6b32 [Update] generator link library on mac-aarch64 2024-07-03 08:40:22 +00:00
Mist fceaf8e384
[Release] v1.4.0 2024-07-03 16:38:39 +08:00
The Mist 7be7336420
[Feat] add `has_background` config to control visibility of background component (#110)
* [Feat] add has_background config for control visiblity of background
component

* [Feat] add default has_background config
2024-07-03 16:35:41 +08:00
The Mist a223fd8829
[Update] remove redundancy description 2024-05-08 13:15:20 +08:00
mistricky 5ee4198f59 [Release] 1.3.1 2024-05-07 13:45:13 +00:00
Mist 94971dae40
[Release] v1.3.1 2024-05-07 21:42:27 +08:00
mistricky 076a5d5f63 chore(docs): update TOC 2024-05-07 13:41:09 +00:00
The Mist 978a18354c [Update] add usage for the show_workspace config item 2024-05-07 21:40:54 +08:00
Mist daf3dc6ee3 [Feat] add show_workspace config for display workspace in breadcrumbs 2024-05-07 21:40:54 +08:00
mistricky a2d59ef624 [Release] 1.3.0 2024-05-07 08:49:36 +00:00
mistricky 08e06664f8 [Update] generator link library on linux-x86_64 2024-05-07 08:49:13 +00:00
mistricky 2922793055 [Update] generator link library on mac-x86_64 2024-05-07 08:49:02 +00:00
mistricky c00a0cb081 [Update] generator link library on mac-aarch64 2024-05-07 08:48:44 +00:00
Mist 9ba92c2aa7
[Release] v1.3.0 2024-05-07 16:47:02 +08:00
The Mist 497e896f59 [Update] default config 2024-05-07 16:44:44 +08:00
Mist 19dd1d4817 [Feat] supports for allows users can custom min_width of snapshots 2024-05-07 16:44:44 +08:00
mistricky 8f9e6fa5aa chore(docs): update TOC 2024-05-07 08:07:01 +00:00
The Mist e45cc92739 [Update] add highlight code block chapter 2024-05-07 16:06:45 +08:00
Mist 70d7332479 [Update] height of float window 2024-05-07 16:06:45 +08:00
Mist be2992276e [Feat] use code lines instead of raw string 2024-05-07 16:06:45 +08:00
Mist 7a580d2106 [Feat] reduce the opacity of highlight block 2024-05-07 16:06:45 +08:00
The Mist 4c3b56c82e [Update] add demo for take code snapshot with highlighted code block 2024-05-07 16:06:45 +08:00
Mist 9836ad1163 [Feat] support highlight code block 2024-05-07 16:06:45 +08:00
mistricky 00e2156364 chore(docs): update TOC 2024-05-02 09:29:26 +00:00
The Mist 9a230ac6e9
[Feat] add contributors chapter 2024-05-02 17:29:09 +08:00
github-actions[bot] c2dbdf232a
chore: update contributors [skip ci] 2024-05-02 09:25:10 +00:00
Mist 7cabc1b6e0 [Feat] auto generate contributor list by github actions 2024-05-02 17:24:48 +08:00
Mist 6d0c0ae0c0 [Update] remove TOC title 2024-05-02 17:06:11 +08:00
mistricky ec5fcced8e chore(docs): update TOC 2024-05-02 09:00:36 +00:00
Mist 48f37b9b78 [Feat] add actions to generate TOC 2024-05-02 17:00:09 +08:00
The Mist 5c365e0328
[Update] remove br label 2024-04-27 20:05:01 +08:00
The Mist 4008ded6ed
[Feat] add more pretty badge 2024-04-27 20:03:58 +08:00
mistricky ef4b1b3e94 [Release] 1.2.0 2024-04-26 03:00:13 +00:00
mistricky 3eb0c9cda5 [Update] generator link library on linux-x86_64 2024-04-26 02:59:40 +00:00
mistricky 2b031b16d8 [Update] generator link library on mac-x86_64 2024-04-26 02:59:36 +00:00
mistricky d2e8d18dfa [Update] generator link library on mac-aarch64 2024-04-26 02:59:18 +00:00
Mist 1bffac81dc
[Release] v1.2.0 2024-04-26 10:57:22 +08:00
The Mist c4a13f0a74
[Update] support for display line number 2024-04-26 10:56:29 +08:00
The Mist 3b7dd6a3ad
[Feat] support line number & remove unused module (#91) 2024-04-26 01:01:17 +08:00
The Mist ef08881e1a
[Perf] cache the function that used to calculate width and height of (#90)
dynamic text
2024-04-25 21:38:03 +08:00
Mist 66206496f9 [Perf] find min indention of the line and remove the ssame indention
from subsequent lines
2024-04-25 18:02:51 +08:00
Mist 13d7118c06 [Perf] add comments for highlight logic 2024-04-25 18:02:51 +08:00
The Mist 2ff1247b2b
[Update] add keymappings examples & add lua version commands 2024-04-23 00:18:45 +08:00
mistricky ac73f9e543 [Release] 1.1.12 2024-04-15 14:43:33 +00:00
mistricky 2804c49c96 [Update] generator link library on mac-aarch64 2024-04-15 14:43:10 +00:00
mistricky ce010b0b72 [Update] generator link library on mac-x86_64 2024-04-15 14:42:35 +00:00
mistricky 6ff825ddcd [Update] generator link library on linux-x86_64 2024-04-15 14:39:42 +00:00
Mist 40720d360e
[Release] v1.1.12 2024-04-15 22:37:32 +08:00
The Mist ac30b071d2
[Fix] auto detect content which should use source syntax (#86) 2024-04-15 22:33:57 +08:00
OKURA Masafumi 727584b109
[Fix] correct Neovim version (#85)
I don't know, maybe it's common to call is v9, but officially it's 0.9.
2024-04-14 23:19:16 +08:00
mistricky 6f5544774c [Release] 1.1.11 2024-04-08 13:27:43 +00:00
mistricky a9fec6d205 [Update] generator link library on mac-x86_64 2024-04-08 13:27:16 +00:00
mistricky ef44d992c2 [Update] generator link library on mac-aarch64 2024-04-08 13:24:37 +00:00
mistricky 24ec019681 [Update] generator link library on linux-x86_64 2024-04-08 13:24:15 +00:00
Mist 7657e1d755
[Release] v1.1.11 2024-04-08 21:21:57 +08:00
Uzair Aftab d625c422e7
[Fix] Use SetExtLinux trait on linux platform (#79) 2024-04-08 20:59:54 +08:00
mistricky 0217f58e7c [Release] 1.1.10 2024-04-07 09:33:40 +00:00
mistricky 252ec79177 [Update] generator link library on mac-x86_64 2024-04-07 09:33:20 +00:00
mistricky 7a392e6204 [Update] generator link library on mac-aarch64 2024-04-07 09:31:50 +00:00
mistricky 08bcd5c809 [Update] generator link library on linux-x86_64 2024-04-07 09:31:13 +00:00
Mist 6b86b383aa
[Release] v1.1.10 2024-04-07 17:29:01 +08:00
The Mist 72d6a69ace
[Refactor] change the detect filetype strategy (#78) 2024-04-07 17:24:43 +08:00
The Mist 69ecdace3b
[Fix] replace all tab character with space for correct render text (#77) 2024-04-07 16:17:24 +08:00
mistricky 8d210e272e [Release] 1.1.9 2024-04-05 16:48:04 +00:00
Mist 96e79610ae
[Release] v1.1.9 2024-04-06 00:45:02 +08:00
Mist 4cdf8b6970
[Fix] remove the wait for action 2024-04-06 00:43:50 +08:00
Mist cb4b02d7e0
[Release] v1.1.8 2024-04-06 00:21:42 +08:00
The Mist 5389a958a2
[Update] usage of save_path 2024-04-06 00:16:01 +08:00
The Mist 42437163db
[Feat] use auto-generate filename when the filename is not specified (#72)
* [Chore] remove redundancy code

* [Feat] use auto-generate filename when the filename is not specified
2024-04-06 00:10:08 +08:00
The Mist 8bd3cd89e0
[Feat] support highlighting no extension file (#70) 2024-04-05 23:23:17 +08:00
The Mist 45804b3341
[Fix] extract build job as a separator workflow (#68) 2024-04-05 21:50:26 +08:00
JT Smith 42ee8bf327
[Update] README.md - fix references to incorrect package (#66) 2024-04-05 09:44:18 +08:00
mistricky 985e60931d [Release] 1.1.7 2024-04-04 15:07:59 +00:00
Mist 894a0834a6
[Release] v1.1.7 2024-04-04 23:04:47 +08:00
nadir-ishiguro 5edb1522c7
[Perf] replace shebang with Nix compatible version (#65) 2024-04-04 23:03:49 +08:00
mistricky e33120ffeb [Release] 1.1.6 2024-04-04 11:08:14 +00:00
Mist c62202af7b
[Release] v1.1.6 2024-04-04 19:04:48 +08:00
HANU 4938d6e479
add shebang for portability (#63) 2024-04-04 19:01:14 +08:00
Mist 3d684bb2b8
[Update] remove language from shell code block 2024-04-03 18:03:48 +08:00
Micya 3054519b58
Update README.md (#62) 2024-04-03 18:01:13 +08:00
Mist 0b0cb79bf8
[Update] default config & perf usage chapter 2024-04-03 17:49:26 +08:00
Mist f616da253f
[Update] add language to shell code block 2024-04-03 17:35:06 +08:00
Mist 1698892981
[Update] add contributors chapter & update the usage 2024-04-03 17:14:53 +08:00
Mist 8e7d77ea41
[Update] installation steps & migration chapter 2024-04-03 17:01:34 +08:00
mistricky a545d58b2b [Release] 1.1.5 2024-04-02 12:15:32 +00:00
mistricky 0b572ad0a1 [Update] generator link library on mac-aarch64 2024-04-02 12:15:09 +00:00
mistricky c5c7a51720 [Update] generator link library on mac-x86_64 2024-04-02 12:14:54 +00:00
mistricky 461d6b4f59 [Update] generator link library on linux-x86_64 2024-04-02 12:14:28 +00:00
Mist ccffcd9cd5 [Release] v1.1.5 2024-04-02 20:11:59 +08:00
Mist 2572f664cc
[Perf] use print instead of raise error directly (#61) 2024-04-02 20:04:37 +08:00
Mist efeb8d89e2
[Fix] dynamic import generator to avoid initial module not found error (#60) 2024-04-02 19:22:12 +08:00
Mist fefaaa12be
[Feat] add extension as argument (#57) 2024-04-02 18:18:37 +08:00
Mist 8e9b4489b6
[Feat] add more language highlighting using two-face (#56) 2024-04-02 17:56:40 +08:00
mistricky c10dd114ba [Release] 1.1.4 2024-04-02 07:39:16 +00:00
Mist 37a0766bbc [Release] v1.1.4 2024-04-02 14:47:39 +08:00
Mist 872529b42a
[Fix] release ci (#55) 2024-04-02 14:45:34 +08:00
mistricky 7fd0ea884a [Update] files based on generated files by template generator 2024-04-01 03:16:58 +00:00
mistricky b0a61dffd6 [Update] files based on generated files by template generator 2024-04-01 03:16:34 +00:00
mistricky a948e488a8 [Update] files based on generated files by template generator 2024-04-01 03:16:04 +00:00
mistricky 33612f15f4 [Update] files based on generated files by template generator 2024-04-01 03:15:48 +00:00
Mist 760abe224b [Release] v1.1.2 2024-04-01 11:13:08 +08:00
Mist 14d2445c32 [Feat] convert rgb hex color to rgba hex color 2024-03-31 18:19:23 +08:00
mrWinston 8a05bddadb [feat] support RGBA values as background color 2024-03-31 18:19:23 +08:00
Mist 6c753177e3
[Fix] condition render for mac window bar component (#54) 2024-03-31 17:48:14 +08:00
mistricky 70f1ff882c [Update] files based on generated files by template generator 2024-03-19 06:00:16 +00:00
mistricky 7e5960bbf7 [Update] files based on generated files by template generator 2024-03-19 05:59:51 +00:00
mistricky 511728141d [Update] files based on generated files by template generator 2024-03-19 05:59:21 +00:00
mistricky 9026ec6a75 [Update] files based on generated files by template generator 2024-03-19 05:59:09 +00:00
Mist f0418b6b70
[Release] v1.1.1 2024-03-19 13:57:06 +08:00
Marius Schulz 92f4eccf0d
[Fix] Enable wayland support for arboard (#51) 2024-03-19 13:52:09 +08:00
Mist a75018bbb5
[Update] features description 2024-03-17 23:09:48 +08:00
Mist 70265fcb68
[Update] description 2024-03-17 23:01:07 +08:00
mistricky 52192834f1 [Update] files based on generated files by template generator 2024-03-17 14:54:21 +00:00
mistricky b26df812c7 [Update] files based on generated files by template generator 2024-03-17 14:54:01 +00:00
mistricky 3eab79f3f9 [Update] files based on generated files by template generator 2024-03-17 14:53:55 +00:00
mistricky 55abaa8b08 [Update] files based on generated files by template generator 2024-03-17 14:53:29 +00:00
Mist da97b6cdee
[Release] v1.1.0 2024-03-17 22:51:35 +08:00
Mist 8d2c3714e1
[Update] add docs for use breadcrumbs 2024-03-17 22:49:56 +08:00
Mist 272e89ff8e [Feat] add breadcrumbs to display file path 2024-03-17 22:35:58 +08:00
mistricky 38ee8c463d [Update] files based on generated files by template generator 2024-03-17 12:28:07 +00:00
mistricky a06eac266c [Update] files based on generated files by template generator 2024-03-17 12:27:45 +00:00
mistricky caa4306c74 [Update] files based on generated files by template generator 2024-03-17 12:27:34 +00:00
mistricky 623b83225a [Update] files based on generated files by template generator 2024-03-17 12:25:04 +00:00
Mist ee5afb467d
[Release] v1.0.3 2024-03-17 20:23:14 +08:00
Mist 58bf7b9107
[Update] add example of background 2024-03-17 20:22:09 +08:00
Mist 08f6c48fae [Feat] add new bg color named dusk 2024-03-17 18:55:01 +08:00
Mist f3cbc3b901 [Feat] support bg_color config 2024-03-17 18:55:01 +08:00
Mist 3f57ce62fc [Feat] add more beautiful background themes 2024-03-17 18:55:01 +08:00
mistricky 7c38bea715 [Update] files based on generated files by template generator 2024-03-17 06:25:51 +00:00
mistricky 2b31c6e25f [Update] files based on generated files by template generator 2024-03-17 06:25:32 +00:00
Mist 2415082285
[Release] v1.0.2 2024-03-17 14:22:28 +08:00
Mist 17d9c1622c [Chore] force overwrite stale build file 2024-03-17 14:21:32 +08:00
Mist 123e6fb2f2 [Perf] remove dead_code warning from from_value of margin 2024-03-17 14:09:01 +08:00
Mist ccf108b440 [Feat] update apply generator script 2024-03-17 14:09:01 +08:00
Mist 9b9a11f42e
[Update] change the name of video 2024-03-17 12:46:52 +08:00
mistricky b8653a901a [Update] files based on generated files by template generator 2024-03-16 18:02:13 +00:00
Mist f2d3232734
[Release] v1.0.1 2024-03-17 01:59:37 +08:00
Mist c47cafd6ec
[Release] v1.0.1 2024-03-17 01:59:15 +08:00
Mist fed7cd3bb3
[Release] v1.0.1 2024-03-17 01:55:44 +08:00
mistricky b4fa56ba7e [Update] files based on generated files by template generator 2024-03-16 17:49:43 +00:00
mistricky d51c517933 [Update] files based on generated files by template generator 2024-03-16 17:49:39 +00:00
mistricky 3a7a74b4ed [Update] files based on generated files by template generator 2024-03-16 17:49:17 +00:00
Mist f7f816a844
[Release] v1.0.1 2024-03-17 01:47:19 +08:00
Mist b92e7706e6 [Perf] add path protection logic 2024-03-17 01:46:46 +08:00
Mist d35273cfae
[Update] replace banner with lua syntax 2024-03-17 01:30:33 +08:00
Mist 82e49a8be2
[Update] replace banner with more pretty one 2024-03-17 01:27:20 +08:00
mistricky 97a1a6ebb8 [Update] apply template 2024-03-16 17:17:21 +00:00
Mist cf3e2b0725
[Release] v1.0.0 2024-03-17 01:14:32 +08:00
mistricky 7fa862e83d [Update] files based on generated files by template generator 2024-03-16 17:09:17 +00:00
mistricky 232181d4ff [Update] files based on generated files by template generator 2024-03-16 17:08:58 +00:00
mistricky 2e4a804988 [Update] files based on generated files by template generator 2024-03-16 17:08:49 +00:00
Mist 08f0b24cf4
[Release] v1.0.0 (#43)
* [Update] apply template

* [Feat] update assets files (#35)

* [Update] README add packer install config

* [Feat] take snapshot via skia engine

* [Feat] title component

* [Feat] add watermark

* [Feat] update padding of code panel

* [Remove] pack ci script

* [Release] v1.0.0

* [Update] apply template

* [Chore] remove unused code

* [Update] readme

* [Release] v1.0.1

* [Update] apply template

* [Update] readme

* Update README.md

* [Feat] compile nvim-0.9 FFI

* [Release] v1.0.2

* [Update] apply template

* [Update] README.md

* [Feat] add multi platform support

* [Feat] add workflow for build target binary package

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Update] files based on generated files by template generator

* [Feat] build plugin after released

* [Delete] build.yml

* [Update] README

* [Release] v1.0.3

* [Update] README

* [Refactor] editor frame size calculation logic

* [Refactor] update margin of watermark

* [Feat] preset font family

* [Refactor] update component interface

* [Update] change theme to onedark

* [Refactor] redefine render_error and throw it to lua scope

* [Perf] build script

* [Refactor] abstract component concept & implement it for all widgets

* [Update] README.md

---------

Co-authored-by: mistricky <mistricky@users.noreply.github.com>
2024-03-17 01:07:12 +08:00
mistricky 53b3d2544a [Update] apply template 2024-03-14 12:13:04 +00:00
Mist 14327aada6
[Release] v0.0.11 (#34) 2024-02-26 14:45:08 +08:00
Mist 25c51f9569
[Update] redesign jobs dependencies graph (#33) 2024-02-26 14:43:08 +08:00
Mist bf50e50801
[Update] remove npm deps (#32) 2024-02-25 20:19:30 +08:00
mistricky 3ed72a3a39 [Update] apply template 2024-02-24 12:39:06 +00:00
Mist e4e6b691ff
[Release] v0.0.10 (#25) 2024-02-24 20:38:53 +08:00
Mist 8d83d91159
[Fix] code style by stylua 2024-02-24 20:22:53 +08:00
Marco 980751083b
[Fix] Better support for the Visual Line Mode
* [FIX] Better support for the Visual Line Mode

* [FIX] Removed VBlockMode + listen for ModeChanged now
2024-02-24 20:18:06 +08:00
mistricky d3fdcd343f [Update] build newest client package 2024-02-24 12:13:05 +00:00
Mist 45081e2fd7
[Feat] fix pack CI (#23)
* [Feat] fix pack CI

* [Fix] specify cache dependency path
2024-02-24 20:12:21 +08:00
Mist c8a66c60df
[Feat] add working directory to setup stage 2024-02-24 19:46:35 +08:00
Mist 4fcc544195
[Fix] pack CI 2024-02-24 19:45:06 +08:00
Mist d7e1cf0c83
[Update] upload packed client code 2024-02-24 19:42:01 +08:00
Mist ac7e7de7dd
[Feat] pack client on CI 2024-02-24 19:42:01 +08:00
108 changed files with 6002 additions and 35018 deletions

11
.cargo/config.toml Normal file
View File

@ -0,0 +1,11 @@
[target.x86_64-apple-darwin]
rustflags = [
"-C", "link-arg=-undefined",
"-C", "link-arg=dynamic_lookup",
]
[target.aarch64-apple-darwin]
rustflags = [
"-C", "link-arg=-undefined",
"-C", "link-arg=dynamic_lookup",
]

66
.github/workflows/build.yaml vendored Normal file
View File

@ -0,0 +1,66 @@
name: Build
on:
push:
paths:
project.toml
branches:
- main
permissions:
contents: write
jobs:
build:
name: ${{ matrix.platform.os_name }} with rust ${{ matrix.toolchain }}
runs-on: ${{ matrix.platform.os }}
strategy:
fail-fast: false
matrix:
platform:
- os_name: linux-x86_64
os: ubuntu-20.04
target: x86_64-unknown-linux-gnu
origin_dylib_suffix: so
dest_dylib_suffix: so
- os_name: mac-x86_64
os: macOS-latest
target: x86_64-apple-darwin
origin_dylib_suffix: dylib
dest_dylib_suffix: so
- os_name: mac-aarch64
os: macOS-latest
target: aarch64-apple-darwin
origin_dylib_suffix: dylib
dest_dylib_suffix: so
toolchain:
- stable
steps:
- uses: actions/checkout@v3
- name: Build link lib
uses: houseabsolute/actions-rust-cross@v0
with:
command: "build"
working-directory: ./generator
target: ${{ matrix.platform.target }}
toolchain: ${{ matrix.toolchain }}
args: "--release"
- name: Rename dynamic lib
run: cp -rf generator/target/${{ matrix.platform.target }}/release/libgenerator.${{ matrix.platform.origin_dylib_suffix }} lua/${{ matrix.platform.os_name }}generator.${{ matrix.platform.dest_dylib_suffix }}
- name: Commit changes
uses: EndBug/add-and-commit@v7
with:
message: '[Update] generator link library on ${{ matrix.platform.os_name }}'
pull_strategy: 'NO-PULL'
push: false
- name: Push changes
run: |
git pull --rebase
git push

19
.github/workflows/contributor_list.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: Auto Generate Contributor List
on:
push:
branches:
main
permissions:
contents: write
jobs:
generate-contributor-list:
name: Auto generate contributor list
runs-on: ubuntu-latest
steps:
- uses: wow-actions/contributors-list@v1
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
svgPath: CONTRIBUTORS.svg

21
.github/workflows/generate_toc.yml vendored Normal file
View File

@ -0,0 +1,21 @@
name: Generate TOC
on:
push:
paths:
README.md
branches:
main
permissions:
contents: write
jobs:
generate-toc:
name: TOC Generator
runs-on: ubuntu-latest
steps:
- uses: technote-space/toc-generator@v4
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TOC_TITLE: ''

View File

@ -1,11 +1,13 @@
name: Release name: Release
on: on:
push: workflow_run:
paths: workflows: [build]
project.toml types:
branches: - completed
- main
permissions:
contents: write
jobs: jobs:
release: release:
@ -13,20 +15,15 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ github.ref }}
- name: Setup python - name: Setup python
uses: actions/setup-python@v5 uses: actions/setup-python@v5
with: with:
python-version: "3.11" python-version: "3.11"
- name: Replace template
run: python3 scripts/replace-template.py
- name: Commit changes
uses: EndBug/add-and-commit@v9
with:
message: "[Update] apply template"
- name: Read version from project config - name: Read version from project config
id: read_toml id: read_toml
uses: SebRollen/toml-action@v1.0.2 uses: SebRollen/toml-action@v1.0.2
@ -34,6 +31,21 @@ jobs:
file: project.toml file: project.toml
field: project.version field: project.version
- name: Replace template
run: python3 scripts/replace-template.py
- name: Commit changes
uses: EndBug/add-and-commit@v7
with:
message: '[Release] ${{ steps.read_toml.outputs.value }}'
pull_strategy: 'NO-PULL'
push: false
- name: Push changes
run: |
git pull --rebase
git push
- name: Bump version and push tag - name: Bump version and push tag
id: tag_version id: tag_version
uses: mathieudutour/github-tag-action@v6.1 uses: mathieudutour/github-tag-action@v6.1

2
.gitignore vendored
View File

@ -19,4 +19,4 @@ node_modules
# build # build
output.css output.css
snap-server/public *.so

33
CONTRIBUTORS.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 3.0 MiB

407
README.md
View File

@ -1,51 +1,389 @@
![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/c8982b8c-c273-4257-9fef-f0f9134fd9a1) ![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/9fc40afc-cff8-4e18-a04f-e931d32a1fb7)
<p align="center"> <p align="center">
<img src="https://img.shields.io/badge/Neovim-57A143?logo=neovim&logoColor=fff&style=for-the-badge" alt="Neovim" /> <img src="https://img.shields.io/badge/For Neovim 0.9+-57A143?logo=neovim&logoColor=fff&style=for-the-badge" alt="Neovim" />
<img src="https://img.shields.io/badge/Made%20With%20Lua-2C2D72?logo=lua&logoColor=fff&style=for-the-badge" alt="made with lua" >
<img src="https://img.shields.io/github/actions/workflow/status/mistricky/codesnap.nvim/release.yml?style=for-the-badge&label=release" alt="release action status" /> <img src="https://img.shields.io/github/actions/workflow/status/mistricky/codesnap.nvim/release.yml?style=for-the-badge&label=release" alt="release action status" />
<img src="https://img.shields.io/github/actions/workflow/status/mistricky/codesnap.nvim/lint.yml?style=for-the-badge&label=Lint" alt="release action status" /> <img src="https://img.shields.io/github/actions/workflow/status/mistricky/codesnap.nvim/lint.yml?style=for-the-badge&label=Lint" alt="release action status" />
<a href="https://github.com/mistricky/codesnap.nvim/issues">
<img alt="Issues" src="https://img.shields.io/github/issues/mistricky/codesnap.nvim?style=for-the-badge&logo=github&color=%23ffbd5e">
</a>
<a href="https://github.com/mistricky/codesnap.nvim/blob/main/LICENSE">
<img alt="License" src="https://img.shields.io/github/license/mistricky/codesnap.nvim?style=for-the-badge&logo=github&color=%235ef1ff">
</a>
<a href="https://github.com/mistricky/codesnap.nvim/stars">
<img alt="stars" src="https://img.shields.io/github/stars/mistricky/codesnap.nvim?style=for-the-badge&logo=github&color=%23bd5eff">
</a>
<img src="https://img.shields.io/badge/Made%20With%20Lua-2C2D72?logo=lua&logoColor=fff&style=for-the-badge" alt="made with lua" >
<img src="https://img.shields.io/badge/Written%20in%20Rust-DEA584?logo=rust&logoColor=fff&style=for-the-badge" alt="written in rust" >
<a href="https://dotfyle.com/plugins/mistricky/codesnap.nvim">
<img src="https://dotfyle.com/plugins/mistricky/codesnap.nvim/shield?style=for-the-badge" />
</a>
</p> </p>
<h1 align="center">CodeSnap.nvim</h1> <h1 align="center">CodeSnap.nvim</h1>
<p align="center">📸 Snapshot plugin that can make pretty code snapshots with real-time previews for Neovim</p> <p align="center">📸 Snapshot plugin with rich features that can make pretty code snapshots for Neovim</p>
> [!NOTE] <!-- START doctoc generated TOC please keep comment here to allow auto update -->
> This plugin is currently in its early stages and may have some bugs, please feel free to submit issues and PRs. <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [🚣Migration](#migration)
- [✨Features](#features)
- [Prerequirements](#prerequirements)
- [Install](#install)
- [Compile from source](#compile-from-source)
- [Compile on ARM](#compile-on-arm)
- [Keymappings](#keymappings)
- [Windows Support](#windows-support)
- [Usage](#usage)
- [Copy into the clipboard](#copy-into-the-clipboard)
- [Copy into clipboard on Linux Wayland](#copy-into-clipboard-on-linux-wayland)
- [Save the snapshot](#save-the-snapshot)
- [Highlight code block](#highlight-code-block)
- [How to use](#how-to-use)
- [Take ASCII snapshot](#take-ascii-snapshot)
- [Specify language extension](#specify-language-extension)
- [Breadcrumbs](#breadcrumbs)
- [Show workspace in breadcrumbs](#show-workspace-in-breadcrumbs)
- [Custom path separator](#custom-path-separator)
- [Line number](#line-number)
- [Custom background](#custom-background)
- [Solid color background](#solid-color-background)
- [Customize background padding](#customize-background-padding)
- [Watermark](#watermark)
- [Commands](#commands)
- [Configuration](#configuration)
- [Contribution](#contribution)
- [Contributors](#contributors)
- [License](#license)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## 🚣Migration
If you have installed v0.x before, this chapter will show you what break changes version v1.x introduced.
- The `CodeSnapPreviewOn` command is not supported, if you prefer live-preview, you can pin `CodeSnap.nvim` version to `v0.0.11` to continue using this command.
- The `opacity` and `preview_title` config has been removed from v1.0.0
- The `editor_font_family` was renamed to `code_font_family`
v1.x has a different architecture and better performance than v0.x, and v1.x can generate screenshots directly without an open browser. We recommend you upgrade to v1.x for a better experience.
## ✨Features ## ✨Features
- 🔥 Real-time preview
- 🤩 Beautiful code snap template - 🤩 Beautiful code snap template
- 😎 Custom watermark and window style - 😎 Custom watermark and window style
- 💻 Mac style title bar - 💻 Beautiful Mac-style title bar
- 👏 [WIP] Custom template background - 🤖 Generate snapshots using only a single command
- 🤖 [WIP] Generate snapshot just one command - 🍞 Breadcrumbs for display file path
- 🌊 More beautiful background theme
- 🔢 Support for display line number make sharing code snapshot easier
- 🔆 Highlight specific lines of code
- 🖨️ Generate ASCII art code snapshots
## Prerequirements ## Prerequirements
- Rust environment required for compiling codesnap.nvim plugin server source code, visit [Install Rust](https://www.rust-lang.org/tools/install) for more detail. - Neovim 0.9.0+
- NPM required for build preview source code, visit [Install Nodejs](https://nodejs.org/en) for more detail.
## Install ## Install
We recommend using [Lazy.nvim](https://github.com/folke/lazy.nvim) to install CodeSnap.nvim, but you can still use another plugin manager you prefer.
**Lazy.nvim**
```lua ```lua
{ "mistricky/codesnap.nvim", build = "make" }, { "mistricky/codesnap.nvim", build = "make" },
``` ```
**Packer**
```lua
use {'mistricky/codesnap.nvim', run = 'make'}
```
**Vim-Plug**
```lua
Plug 'mistricky/codesnap.nvim', { 'do': 'make' }
```
It's worth mentioning that the screenshot feature is implemented by a module called `generator` written in Rust, when `make` the project, the CodeSnap.nvim will mount a precompiled cross-compile `generator` shared file into the plugin that depends on what OS you are using.
We precompiled the following targets:
- x86_64-unknown-linux-gnu
- x86_64-apple-darwin
- aarch64-apple-darwin
If your platform is in the above list, you can just run `make` after the plugin is installed like the above examples do, CodeSnap.nvim will automatically mount the shared file into the plugin. This means you don't need any Rust utils to compile manually from source.
### Compile from source
You need to install Rust development environment before compiling from source, you can refer [Install Rust](https://www.rust-lang.org/tools/install) for more detail.
Please keep in mind, cross-compile to these platforms only helps a portion of users to have out-of-box experience, if your platform is not in the above targets list, you still need to compile from source using `make build_generator`, for instance using Lazy:
```lua
{ "mistricky/codesnap.nvim", build = "make build_generator" },
```
We always recommend you to compile CodeSnap.nvim from `source` instead of using the precompiled shared file, because the correctness and consistency of compiling from source are always higher than cross-compiling.
### Compile on ARM
If you try to compile CodeSnap.nvim on ARM architecture, you may need to install additional dependencies to compile it, thanks @matteocavestri mentioned in https://github.com/mistricky/codesnap.nvim/issues/53#issuecomment-2032088162
```shell
export CC=gcc
sudo dnf install libuv libuv-devel # On RHEL based systems
sudo apt-get install libtool libuv1-dev # On Debian based systems
```
### Keymappings
If you use `Lazy.nvim` as your package manager, here are some examples show you how to configure keymappings for CodeSnap:
```lua
{
"mistricky/codesnap.nvim",
build = "make build_generator",
keys = {
{ "<leader>cc", "<cmd>CodeSnap<cr>", mode = "x", desc = "Save selected code snapshot into clipboard" },
{ "<leader>cs", "<cmd>CodeSnapSave<cr>", mode = "x", desc = "Save selected code snapshot in ~/Pictures" },
},
opts = {
save_path = "~/Pictures",
has_breadcrumbs = true,
bg_theme = "bamboo",
},
}
```
### Windows Support
Unfortunately, CodeSnap does not support Windows yet, but version `v0.0.x` is working fine on Windows. If you want to use CodeSnap on Windows, we recommend you pin the version to `0.0.11` to use CodeSnap, follow to [0.0.11 Document](https://github.com/mistricky/codesnap.nvim/tree/v0.0.11) for more detail.
## Usage ## Usage
For take a screenshot, the `codesnap.nvim` provides a command named `CodeSnapPreviewOn` to open the preview page, and then you can switch to visual mode and select code you want, and finally just click the copy button on the preview page, that's all :) `CodeSnap.nvim` provides the following two ways to take snapshots of currently selected code
https://github.com/mistricky/codesnap.nvim/assets/22574136/5e1a023e-142f-49e8-b24f-707da3728fd5 ### Copy into the clipboard
To take a beautiful snapshot use CodeSnap.nvim, you can just use `CodeSnap` command to generate a snapshot of the current selected code, then the `CodeSnap.nvim` will write the snapshot into the clipboard, and you can paste it anywhere you want.
https://github.com/mistricky/codesnap.nvim/assets/22574136/99be72db-57d7-4839-91d0-2a9dfb1901ac
#### Copy into clipboard on Linux Wayland
Copy screenshots directly into the clipboard is cool, however, it doesn't work well on wl-clipboard, because the wl-clipboard can't paste the content which come from exited processes. As Hyprland document say:
> When we copy something on Wayland (using wl-clipboard) and close the application we copied from, the copied data disappears from the clipboard and we cannot paste it anymore. So to fix this problem we can use a program called as wl-clip-persist which will preserve the data in the clipboard after the application is closed.
If you using CodeSnap.nvim on wl-clipboard, you can refer [wl-clip-persist](https://github.com/Linus789/wl-clip-persist), it reads all the clipboard data into memory and then overwrites the clipboard with the data from our memory to persist copied data.
### Save the snapshot
Of course, you can use `CodeSnapSave` command to save the snapshot to path where you defined it in `config.save_path`
```lua
require("codesnap").setup({
-- The save_path must be ends with .png, unless when you specified a directory path,
-- CodeSnap will append an auto-generated filename to the specified directory path
-- For example:
-- save_path = "~/Pictures"
-- parsed: "~/Pictures/CodeSnap_y-m-d_at_h:m:s.png"
-- save_path = "~/Pictures/foo.png"
-- parsed: "~/Pictures/foo.png"
save_path = ...
})
```
https://github.com/mistricky/codesnap.nvim/assets/22574136/69b27e77-3dce-4bc3-8516-89ce636fe02d
### Highlight code block
CodeSnap allows you to take code snapshots with highlights code blocks, we provide two commands for this scenario:
```shell
CodeSnapHighlight # Take code snapshot with highlights code blocks and copy it into the clipboard
CodeSnapSaveHighlight # Take code snapshot with highlights code blocks and save it somewhere
```
#### How to use
For take a code snapshot with highlights code blocks and save it somewhere. First you need to select code which you want to snapshot, then enter the command `CodeSnapSaveHighlight` to open a window show you the selected code which from previous step, now you can select code which you want to highlight, finally press the Enter key, CodeSnap will generate a snapshot with highlight blocks and save it in save_path.
Here is an example video:
https://github.com/mistricky/codesnap.nvim/assets/22574136/bea0bf6c-8fc9-4d09-9cab-4e1e6f47899c
### Take ASCII snapshot
Run `CodeSnapASCII`, CodeSnap will generate a "code snapshot" in ASCII format and then copy it into clipboard automatically, it's really cool and lightweight, if you want to share your code in somewhere like Markdown document, even you can enjoy the code highlighting which provided by Markdown parser. Here is an usage video:
https://github.com/mistricky/codesnap.nvim/assets/22574136/91bc3d96-7dbd-4e1c-9224-95428c7cca48
### Specify language extension
In some scenarios, CodeSnap.nvim cannot auto-detect what language syntax should used to highlight code, for example, shell script can have no extension, they specify interpreters using shebang.
CodeSnap.nvim won't read the whole content of the file, thus cannot detect what language syntax is this, in this case, you can specify extension explicitly, for instance:
```
CodeSnapSave sh
CodeSnap sh
```
## Breadcrumbs
Breadcrumbs are something to display the current snapshot file path, you can open it through config `has_breadcrumbs`:
```lua
require("codesnap").setup({
-- ...
has_breadcrumbs = true
})
```
The breadcrumbs look like:
![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/23274faa-36a9-4d41-88a5-e48c44b4d5bf)
### Show workspace in breadcrumbs
Breadcrumbs hide the workspace name by default, if you want to display workspace in breadcrumbs, you can just set `show_workspace` as true.
```lua
require("codesnap").setup({
-- ...
has_breadcrumbs = true
show_workspace = true
})
```
### Custom path separator
The CodeSnap.nvim uses `/` as the separator of the file path by default, of course, you can specify any symbol you prefer as the custom separator:
```lua
require("codesnap").setup({
-- ...
has_breadcrumbs = true
breadcrumbs_separator = "👉"
})
```
![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/84b80d0f-1467-4bdf-9cbd-aede868f93aa)
## Line number
We also support displaying line number, you can set `has_line_number` to true to display line number.
```lua
require("codesnap").setup({
// ...
has_line_number = true,
})
```
![image](https://github.com/mistricky/codesnap.nvim/assets/22574136/3a5999b1-bb2a-4646-8d69-609be1d28140)
## Custom background
The `CodeSnap.nvim` comes with many beautiful backgrounds preset, you can set any background you like by setting `bg_theme` to its name, just like:
```lua
require("codesnap").setup({
-- The "default" background is one you see at the beginning of the README
bg_theme = "default"
})
```
<table>
<tr>
<th>bamboo</th>
<th>sea</th>
</tr>
<tr>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/ce3a387b-61a5-42ba-8f71-1b4949f5e148" width="650" />
</td>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/122790b6-6365-402c-806a-dfc78dabbc06" width="650" />
</td>
</tr>
<tr>
<th>peach</th>
<th>grape</th>
</tr>
<tr>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/c0ec9dc1-cd8b-463e-9f2d-ab2e1e3a9831" width="650" />
</td>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/b573786b-70ed-4006-89c7-20bed115c9cc" width="650" />
</td>
</tr>
<tr>
<th>dusk</th>
<th>summer</th>
</tr>
<tr>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/e3bb5222-542d-4c32-b78b-8cf4695feec9" width="650" />
</td>
<td>
<img src="https://github.com/mistricky/codesnap.nvim/assets/22574136/98ced31a-091b-4ed8-9bd6-bb5b502a7db2" width="650" />
</td>
</tr>
</table>
### Solid color background
If you prefer solid color background, you can set `bg_color` to your preferred color. For example:
```lua
require("codesnap").setup({
-- ...
bg_color = "#535c68"
})
```
![CodeSnap](https://github.com/mistricky/codesnap.nvim/assets/22574136/a600c2e4-4c60-4ec0-b2fc-3b41481048dc)
### Customize background padding
CodeSnap allows you to customize the padding of background using `bg_x_padding`, `bg_y_padding` and `bg_padding`, the default value is:
```lua
require("codesnap").setup({
bg_x_padding = 122,
bg_y_padding = 82,
bg_padding = nil
})
```
If you want to hide background, you can set `bg_padding` to `0` in your config:
```lua
require("codesnap").setup({
-- ...
bg_padding = 0
})
```
## Watermark
Watermark is something that makes screenshots more personalized, but if you don't like watermark just set it as an empty string to hide it.
```lua
require("codesnap").setup({
-- ...
watermark = ""
})
```
## Commands ## Commands
```shell ```shell
CodeSnapPreviewOn # Open preview page CodeSnap # Take a snapshot of the currently selected code and copy the snapshot into the clipboard
-- The following commands are planned but not implemented yet. (welcome PR :)) CodeSnapSave # Save the snapshot of the currently selected code and save it on the disk
CodeSnap # Take a code snap and copy it into the clipboard
CodeSnapASCII # Take a code snapshot in ASCII format
```
**Lua**
```lua
local codesnap <const> = require("codesnap")
-- Take a snapshot of the currently selected code and copy the snapshot into the clipboard
codesnap.copy_into_clipboard()
-- Save the snapshot of the currently selected code and save it on the disk
codesnap.save_snapshot()
``` ```
## Configuration ## Configuration
@ -57,15 +395,32 @@ require("codesnap").setup({...})
There is a default config: There is a default config:
```lua ```lua
{ {
mac_window_bar = true,-- (Optional) MacOS style title bar switch mac_window_bar = true,
opacity = true, -- (Optional) The code snap has some opacity by default, set it to false for 100% opacity title = "CodeSnap.nvim",
watermark = "CodeSnap.nvim", -- (Optional) you can custom your own watermark, but if you don't like it, just set it to "" code_font_family = "CaskaydiaCove Nerd Font",
preview_title = "CodeSnap.nvim", -- (Optional) preview page title watermark_font_family = "Pacifico",
editor_font_family = "CaskaydiaCove Nerd Font", -- (Optional) preview code font family watermark = "CodeSnap.nvim",
watermark_font_family = "Pacifico", -- (Optional) watermark font family bg_theme = "default",
highlight_theme = "atom-one-dark", -- (Optional) theme for code highlights breadcrumbs_separator = "/",
has_breadcrumbs = false,
has_line_number = false,
show_workspace = false,
min_width = 0,
bg_x_padding = 122,
bg_y_padding = 82,
save_path = os.getenv("XDG_PICTURES_DIR") or (os.getenv("HOME").. "/Pictures")
} }
``` ```
## Contribution
CodeSnap.nvim is a project that will be maintained for the long term, and we always accepts new contributors, please feel free to submit PR & issues.
The commit message convention of this project is following [commitlint-wizardoc](https://github.com/wizardoc/commitlint-wizardoc).
### Contributors
Thanks to all contributors for their contributions and works they have done.
<img src="CONTRIBUTORS.svg" />
## License ## License
MIT. MIT.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,560 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>author</key>
<string>Template: Chris Kempson, Scheme: Lalit Magant (http://github.com/tilal6991)</string>
<key>name</key>
<string>Base16 OneDark</string>
<key>semanticClass</key>
<string>theme.base16.onedark</string>
<key>colorSpaceName</key>
<string>sRGB</string>
<key>gutterSettings</key>
<dict>
<key>background</key>
<string>#353b45</string>
<key>divider</key>
<string>#353b45</string>
<key>foreground</key>
<string>#545862</string>
<key>selectionBackground</key>
<string>#3e4451</string>
<key>selectionForeground</key>
<string>#565c64</string>
</dict>
<key>settings</key>
<array>
<dict>
<key>settings</key>
<dict>
<key>background</key>
<string>#282c34</string>
<key>caret</key>
<string>#abb2bf</string>
<key>foreground</key>
<string>#abb2bf</string>
<key>invisibles</key>
<string>#545862</string>
<key>lineHighlight</key>
<string>#54586255</string>
<key>selection</key>
<string>#3e4451</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Text</string>
<key>scope</key>
<string>variable.parameter.function</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#abb2bf</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Comments</string>
<key>scope</key>
<string>comment, punctuation.definition.comment</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#545862</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Punctuation</string>
<key>scope</key>
<string>punctuation.definition.string, punctuation.definition.variable, punctuation.definition.string, punctuation.definition.parameters, punctuation.definition.string, punctuation.definition.array</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#abb2bf</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Delimiters</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#abb2bf</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Operators</string>
<key>scope</key>
<string>keyword.operator</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#abb2bf</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Keywords</string>
<key>scope</key>
<string>keyword</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Variables</string>
<key>scope</key>
<string>variable</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e06c75</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Functions</string>
<key>scope</key>
<string>entity.name.function, meta.require, support.function.any-method, variable.function, variable.annotation, support.macro</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#61afef</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Labels</string>
<key>scope</key>
<string>entity.name.label</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#be5046</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Classes</string>
<key>scope</key>
<string>support.class, entity.name.class, entity.name.type.class</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e5c07b</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Classes</string>
<key>scope</key>
<string>meta.class</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c8ccd4</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Methods</string>
<key>scope</key>
<string>keyword.other.special-method</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#61afef</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Storage</string>
<key>scope</key>
<string>storage</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Support</string>
<key>scope</key>
<string>support.function</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#56b6c2</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Strings, Inherited Class</string>
<key>scope</key>
<string>string, constant.other.symbol, entity.other.inherited-class</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#98c379</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Integers</string>
<key>scope</key>
<string>constant.numeric</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Floats</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Boolean</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Constants</string>
<key>scope</key>
<string>constant</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Tags</string>
<key>scope</key>
<string>entity.name.tag</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e06c75</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Attributes</string>
<key>scope</key>
<string>entity.other.attribute-name</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Attribute IDs</string>
<key>scope</key>
<string>entity.other.attribute-name.id, punctuation.definition.entity</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#61afef</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Selector</string>
<key>scope</key>
<string>meta.selector</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Values</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Headings</string>
<key>scope</key>
<string>markup.heading punctuation.definition.heading, entity.name.section</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string></string>
<key>foreground</key>
<string>#61afef</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Units</string>
<key>scope</key>
<string>keyword.other.unit</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Bold</string>
<key>scope</key>
<string>markup.bold, punctuation.definition.bold</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#e5c07b</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Italic</string>
<key>scope</key>
<string>markup.italic, punctuation.definition.italic</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>italic</string>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Code</string>
<key>scope</key>
<string>markup.raw.inline</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#98c379</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Link Text</string>
<key>scope</key>
<string>string.other.link, punctuation.definition.string.end.markdown, punctuation.definition.string.begin.markdown</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e06c75</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Link Url</string>
<key>scope</key>
<string>meta.link</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Lists</string>
<key>scope</key>
<string>markup.list</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e06c75</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Quotes</string>
<key>scope</key>
<string>markup.quote</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#d19a66</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Separator</string>
<key>scope</key>
<string>meta.separator</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#3e4451</string>
<key>foreground</key>
<string>#abb2bf</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Inserted</string>
<key>scope</key>
<string>markup.inserted</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#98c379</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Deleted</string>
<key>scope</key>
<string>markup.deleted</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e06c75</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Changed</string>
<key>scope</key>
<string>markup.changed</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Colors</string>
<key>scope</key>
<string>constant.other.color</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#56b6c2</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Regular Expressions</string>
<key>scope</key>
<string>string.regexp</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#56b6c2</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Escape Characters</string>
<key>scope</key>
<string>constant.character.escape</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#56b6c2</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Embedded</string>
<key>scope</key>
<string>punctuation.section.embedded, variable.interpolation</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c678dd</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Illegal</string>
<key>scope</key>
<string>invalid.illegal</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#e06c75</string>
<key>foreground</key>
<string>#c8ccd4</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Broken</string>
<key>scope</key>
<string>invalid.broken</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#d19a66</string>
<key>foreground</key>
<string>#282c34</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Deprecated</string>
<key>scope</key>
<string>invalid.deprecated</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#be5046</string>
<key>foreground</key>
<string>#c8ccd4</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Unimplemented</string>
<key>scope</key>
<string>invalid.unimplemented</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#545862</string>
<key>foreground</key>
<string>#c8ccd4</string>
</dict>
</dict>
</array>
<key>uuid</key>
<string>uuid</string>
</dict>
</plist>

View File

@ -0,0 +1,560 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>author</key>
<string>Template: Chris Kempson, Scheme: Emilia Dunfelt &lt;edun@dunfelt.se&gt;</string>
<key>name</key>
<string>Base16 Rosé Pine</string>
<key>semanticClass</key>
<string>theme.base16.rosé-pine</string>
<key>colorSpaceName</key>
<string>sRGB</string>
<key>gutterSettings</key>
<dict>
<key>background</key>
<string>#1f1d2e</string>
<key>divider</key>
<string>#1f1d2e</string>
<key>foreground</key>
<string>#6e6a86</string>
<key>selectionBackground</key>
<string>#26233a</string>
<key>selectionForeground</key>
<string>#908caa</string>
</dict>
<key>settings</key>
<array>
<dict>
<key>settings</key>
<dict>
<key>background</key>
<string>#191724</string>
<key>caret</key>
<string>#e0def4</string>
<key>foreground</key>
<string>#e0def4</string>
<key>invisibles</key>
<string>#6e6a86</string>
<key>lineHighlight</key>
<string>#6e6a8655</string>
<key>selection</key>
<string>#26233a</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Text</string>
<key>scope</key>
<string>variable.parameter.function</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e0def4</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Comments</string>
<key>scope</key>
<string>comment, punctuation.definition.comment</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#6e6a86</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Punctuation</string>
<key>scope</key>
<string>punctuation.definition.string, punctuation.definition.variable, punctuation.definition.string, punctuation.definition.parameters, punctuation.definition.string, punctuation.definition.array</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e0def4</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Delimiters</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e0def4</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Operators</string>
<key>scope</key>
<string>keyword.operator</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#e0def4</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Keywords</string>
<key>scope</key>
<string>keyword</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Variables</string>
<key>scope</key>
<string>variable</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#eb6f92</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Functions</string>
<key>scope</key>
<string>entity.name.function, meta.require, support.function.any-method, variable.function, variable.annotation, support.macro</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c4a7e7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Labels</string>
<key>scope</key>
<string>entity.name.label</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#524f67</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Classes</string>
<key>scope</key>
<string>support.class, entity.name.class, entity.name.type.class</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#ebbcba</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Classes</string>
<key>scope</key>
<string>meta.class</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#524f67</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Methods</string>
<key>scope</key>
<string>keyword.other.special-method</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c4a7e7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Storage</string>
<key>scope</key>
<string>storage</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Support</string>
<key>scope</key>
<string>support.function</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9ccfd8</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Strings, Inherited Class</string>
<key>scope</key>
<string>string, constant.other.symbol, entity.other.inherited-class</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#31748f</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Integers</string>
<key>scope</key>
<string>constant.numeric</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Floats</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Boolean</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Constants</string>
<key>scope</key>
<string>constant</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Tags</string>
<key>scope</key>
<string>entity.name.tag</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#eb6f92</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Attributes</string>
<key>scope</key>
<string>entity.other.attribute-name</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Attribute IDs</string>
<key>scope</key>
<string>entity.other.attribute-name.id, punctuation.definition.entity</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#c4a7e7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Selector</string>
<key>scope</key>
<string>meta.selector</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Values</string>
<key>scope</key>
<string>none</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Headings</string>
<key>scope</key>
<string>markup.heading punctuation.definition.heading, entity.name.section</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string></string>
<key>foreground</key>
<string>#c4a7e7</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Units</string>
<key>scope</key>
<string>keyword.other.unit</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Bold</string>
<key>scope</key>
<string>markup.bold, punctuation.definition.bold</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>bold</string>
<key>foreground</key>
<string>#ebbcba</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Italic</string>
<key>scope</key>
<string>markup.italic, punctuation.definition.italic</string>
<key>settings</key>
<dict>
<key>fontStyle</key>
<string>italic</string>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Code</string>
<key>scope</key>
<string>markup.raw.inline</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#31748f</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Link Text</string>
<key>scope</key>
<string>string.other.link, punctuation.definition.string.end.markdown, punctuation.definition.string.begin.markdown</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#eb6f92</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Link Url</string>
<key>scope</key>
<string>meta.link</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Lists</string>
<key>scope</key>
<string>markup.list</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#eb6f92</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Quotes</string>
<key>scope</key>
<string>markup.quote</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Separator</string>
<key>scope</key>
<string>meta.separator</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#26233a</string>
<key>foreground</key>
<string>#e0def4</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Inserted</string>
<key>scope</key>
<string>markup.inserted</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#31748f</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Deleted</string>
<key>scope</key>
<string>markup.deleted</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#eb6f92</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Changed</string>
<key>scope</key>
<string>markup.changed</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Colors</string>
<key>scope</key>
<string>constant.other.color</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9ccfd8</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Regular Expressions</string>
<key>scope</key>
<string>string.regexp</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9ccfd8</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Escape Characters</string>
<key>scope</key>
<string>constant.character.escape</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#9ccfd8</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Embedded</string>
<key>scope</key>
<string>punctuation.section.embedded, variable.interpolation</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#f6c177</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Illegal</string>
<key>scope</key>
<string>invalid.illegal</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#eb6f92</string>
<key>foreground</key>
<string>#524f67</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Broken</string>
<key>scope</key>
<string>invalid.broken</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#f6c177</string>
<key>foreground</key>
<string>#191724</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Deprecated</string>
<key>scope</key>
<string>invalid.deprecated</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#524f67</string>
<key>foreground</key>
<string>#524f67</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>Unimplemented</string>
<key>scope</key>
<string>invalid.unimplemented</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#6e6a86</string>
<key>foreground</key>
<string>#524f67</string>
</dict>
</dict>
</array>
<key>uuid</key>
<string>uuid</string>
</dict>
</plist>

View File

@ -1,4 +1,4 @@
**codesnap.nvim** 📸 Snapshot plugin that can make pretty code snapshots with real-time previews for Neovim **codesnap.nvim** 📸 Snapshot plugin that can make pretty code snapshots with real-time previews for Neovim
Author: Mist <mist.zzh@gmail.com> Author: Mist <mist.zzh@gmail.com>
version: 0.0.9 version: 1.6.0

1975
generator/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

19
generator/Cargo.toml Normal file
View File

@ -0,0 +1,19 @@
[package]
name = "generator"
version = "0.1.0"
edition = "2021"
[dependencies]
nvim-oxi = { features = ["neovim-0-9", "libuv", "oxi-libuv"], version = "0.3" }
tiny-skia = "0.11.4"
syntect = "5.2.0"
cosmic-text = "0.12.0"
serde = "1.0.204"
arboard = { features = ["wayland-data-control"], version = "3.4.0" }
thiserror = "1.0.63"
regex = "1.10.5"
two-face = "0.4.0"
cached = "0.53.1"
[lib]
crate-type = ["cdylib"]

84
generator/src/code.rs Normal file
View File

@ -0,0 +1,84 @@
use cached::proc_macro::cached;
use regex::Regex;
const MIN_WIDTH: f32 = 100.;
pub const CHAR_WIDTH: f32 = 9.05;
fn min_width(width: f32) -> f32 {
if width < MIN_WIDTH {
MIN_WIDTH
} else {
width
}
}
pub fn calc_max_line_number_length(code_length: usize, start_line_number: usize) -> usize {
let max_line_number = code_length + start_line_number;
// If code length is 1, the max_line_number will equal to start_line_number
(max_line_number - 1).to_string().len()
}
pub fn calc_wh(text: &str, char_wdith: f32, line_height: f32) -> (f32, f32) {
let trimmed_text = prepare_code(text);
let lines = trimmed_text.lines();
let max_length_line = lines.clone().into_iter().fold("", |max_length_line, cur| {
if cur.len() > max_length_line.len() {
cur
} else {
max_length_line
}
});
let width = max_length_line.len() as f32 * char_wdith;
let height = lines.collect::<Vec<&str>>().len() as f32 * line_height;
(width, height)
}
// Because the code block is input by users, we need to calculate the width and height
// to make sure render the width and height of the "editor" shape correctly
#[cached(key = "String", convert = r#"{ format!("{}", text) }"#)]
pub fn calc_wh_with_min_width(text: &str, char_wdith: f32, line_height: f32) -> (f32, f32) {
let (width, height) = calc_wh(text, char_wdith, line_height);
(min_width(width), height)
}
// The tab character is incorrectly render using cosmic, need to replace all tab with space
// before render the code
fn replace_tab_to_space(text: &str) -> String {
let spaces = " ".repeat(2);
str::replace(text, "\t", &spaces)
}
// Find min indention of code lines, and remove the same indention from subsequent lines
fn trim_space(text: &str) -> String {
let lines = text.split("\n").collect::<Vec<&str>>();
let regex = Regex::new(r"(?:^|\n)(\s*)").unwrap();
let captures_iter = regex.captures_iter(text);
let space_lengths = captures_iter
.map(|capture| capture.get(1).unwrap().as_str().len())
.collect::<Vec<usize>>();
if space_lengths.len() < lines.len() {
return text.to_string();
}
let need_to_remove_spaces = " ".repeat(space_lengths.into_iter().min().unwrap());
lines
.into_iter()
.map(|line| {
Regex::new(format!("^{}", need_to_remove_spaces).as_ref())
.unwrap()
.replace(line, "")
.to_string()
})
.collect::<Vec<String>>()
.join("\n")
}
pub fn prepare_code(code: &str) -> String {
trim_space(&replace_tab_to_space(&code))
}

44
generator/src/color.rs Normal file
View File

@ -0,0 +1,44 @@
use std::i64;
use tiny_skia::Color;
const HEX_COLOR_LENGTH: usize = 7;
const HEX_COLOR_WITH_ALPHA_LENGTH: usize = 9;
pub struct RgbaColor {
pub color: Color,
}
pub fn is_valid_hex_color(color: &str) -> bool {
(color.len() == HEX_COLOR_LENGTH || color.len() == HEX_COLOR_WITH_ALPHA_LENGTH)
&& color.starts_with("#")
}
fn parse_color_to_rgba_hex(hex: &str) -> String {
if !is_valid_hex_color(&hex) || hex.len() == HEX_COLOR_WITH_ALPHA_LENGTH {
hex.to_string()
} else {
format!("{}ff", hex)
}
}
impl Into<RgbaColor> for String {
fn into(self) -> RgbaColor {
let rgba_hex_color = parse_color_to_rgba_hex(&self);
// Remove the '#' symbol
let hex_color = &rgba_hex_color.to_lowercase()[1..rgba_hex_color.len()];
let chars = hex_color.chars().collect::<Vec<char>>();
let splits = &chars
.chunks(2)
.map(|chunk| i64::from_str_radix(&chunk.iter().collect::<String>(), 16).unwrap())
.collect::<Vec<_>>();
RgbaColor {
color: Color::from_rgba8(
splits[0] as u8,
splits[1] as u8,
splits[2] as u8,
splits[3] as u8,
),
}
}
}

View File

@ -0,0 +1,10 @@
pub mod background;
pub mod breadcrumbs;
pub mod code_block;
pub mod container;
pub mod editor;
pub mod highlight_code_block;
pub mod interface;
pub mod line_number;
pub mod rect;
pub mod watermark;

View File

@ -0,0 +1,147 @@
use tiny_skia::{
Color, GradientStop, LinearGradient, Paint, Pixmap, Point, Rect, SpreadMode, Transform,
};
use crate::{
color::{is_valid_hex_color, RgbaColor},
edges::{edge::Edge, padding::Padding},
};
use super::interface::{
component::{Component, ComponentContext, RenderParams},
render_error::{self, RenderError},
style::{ComponentAlign, ComponentStyle, RawComponentStyle},
};
pub struct Background {
children: Vec<Box<dyn Component>>,
padding: Padding,
}
impl Background {
pub fn new(padding: Padding, children: Vec<Box<dyn Component>>) -> Background {
Background { children, padding }
}
pub fn parse_background_padding(
horizontal_background_padding: f32,
vertical_background_padding: f32,
background_padding: Option<f32>,
) -> Padding {
match background_padding {
Some(padding) => Padding::from_value(padding),
None => Padding {
top: vertical_background_padding,
bottom: vertical_background_padding,
left: horizontal_background_padding,
right: horizontal_background_padding,
},
}
}
pub fn has_background(padding: &Padding) -> bool {
return padding.horizontal() != 0. || padding.vertical() != 0.;
}
}
impl Component for Background {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
RawComponentStyle::default()
.align(ComponentAlign::Column)
.padding(self.padding.clone())
}
fn self_render_condition(&self) -> bool {
Self::has_background(&self.padding)
}
fn draw_self(
&self,
pixmap: &mut Pixmap,
context: &ComponentContext,
_render_params: &RenderParams,
_style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
let mut paint = Paint::default();
let w = pixmap.width() as f32;
let h = pixmap.height() as f32;
let params = &context.take_snapshot_params;
paint.anti_alias = false;
match params.bg_color.as_ref() {
Some(color) => {
if !is_valid_hex_color(color) {
return Err(RenderError::InvalidHexColor(color.to_string()));
}
let rgba_color: RgbaColor = color.to_string().into();
paint.set_color(rgba_color.color);
}
None => {
paint.shader = LinearGradient::new(
Point::from_xy(0., 0.),
Point::from_xy(w, 0.),
Background::get_theme(&context.take_snapshot_params.bg_theme)?,
SpreadMode::Pad,
Transform::identity(),
)
.unwrap();
}
};
pixmap.fill_rect(
Rect::from_xywh(0., 0., w, h).unwrap(),
&paint,
Transform::identity(),
None,
);
Ok(())
}
}
impl Background {
fn get_theme(theme: &str) -> render_error::Result<Vec<GradientStop>> {
let theme = match theme {
"default" => vec![
GradientStop::new(0.0, Color::from_rgba8(58, 28, 113, 255)),
GradientStop::new(0.5, Color::from_rgba8(215, 109, 119, 255)),
GradientStop::new(0.95, Color::from_rgba8(255, 175, 123, 255)),
],
"sea" => vec![
GradientStop::new(0.0, Color::from_rgba8(31, 162, 255, 255)),
GradientStop::new(0.4, Color::from_rgba8(18, 216, 250, 255)),
GradientStop::new(0.95, Color::from_rgba8(166, 255, 203, 255)),
],
"grape" => vec![
GradientStop::new(0.28, Color::from_rgba8(103, 90, 247, 255)),
GradientStop::new(0.95, Color::from_rgba8(189, 101, 250, 255)),
],
"peach" => vec![
GradientStop::new(0.22, Color::from_rgba8(221, 94, 137, 255)),
GradientStop::new(0.95, Color::from_rgba8(247, 187, 151, 255)),
],
"summer" => vec![
GradientStop::new(0.28, Color::from_rgba8(248, 165, 194, 255)),
GradientStop::new(0.95, Color::from_rgba8(116, 185, 255, 255)),
],
"bamboo" => vec![
GradientStop::new(0.22, Color::from_rgba8(107, 203, 165, 255)),
GradientStop::new(0.95, Color::from_rgba8(202, 244, 194, 255)),
],
"dusk" => vec![
GradientStop::new(0.22, Color::from_rgba8(255, 98, 110, 255)),
GradientStop::new(0.95, Color::from_rgba8(255, 190, 113, 255)),
],
_ => return Err(RenderError::UnknownBackgroundTheme(theme.to_string())),
};
Ok(theme)
}
}

View File

@ -0,0 +1,90 @@
use cosmic_text::{Attrs, Color, Family};
use regex::Regex;
use crate::{code::calc_wh_with_min_width, edges::margin::Margin, text::FontRenderer};
use super::interface::{
component::Component,
style::{ComponentStyle, RawComponentStyle, Size},
};
pub struct Breadcrumbs {
children: Vec<Box<dyn Component>>,
path: String,
line_height: f32,
has_breadcrumbs: bool,
}
impl Component for Breadcrumbs {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
let style = RawComponentStyle::default();
if self.has_breadcrumbs {
let (w, h) = calc_wh_with_min_width(&self.path, 8., self.line_height);
style.size(Size::Num(w), Size::Num(h)).margin(Margin {
top: 5.,
..Margin::default()
})
} else {
style
}
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &super::interface::component::ComponentContext,
render_params: &super::interface::component::RenderParams,
style: &super::interface::style::ComponentStyle,
_parent_style: &ComponentStyle,
) -> super::interface::render_error::Result<()> {
if self.has_breadcrumbs {
let attrs = Attrs::new()
.color(Color::rgb(128, 132, 139))
.family(Family::Name(&context.take_snapshot_params.code_font_family));
FontRenderer::new(
12.,
self.line_height,
context.scale_factor,
&context.take_snapshot_params.fonts_folder,
)
.draw_text(
render_params.x,
render_params.y,
style.width,
self.line_height,
vec![(&self.path, attrs)],
pixmap,
);
}
Ok(())
}
}
impl Breadcrumbs {
pub fn from_path(
path: String,
line_height: f32,
separator: String,
has_breadcrumbs: bool,
) -> Breadcrumbs {
let path = Regex::new("/")
.unwrap()
.replace_all(&path, separator)
.to_string();
Breadcrumbs {
children: vec![],
path,
line_height,
has_breadcrumbs,
}
}
}

View File

@ -0,0 +1,17 @@
use super::interface::component::Component;
pub struct CodeBlock {
children: Vec<Box<dyn Component>>,
}
impl Component for CodeBlock {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
}
impl CodeBlock {
pub fn from_children(children: Vec<Box<dyn Component>>) -> CodeBlock {
CodeBlock { children }
}
}

View File

@ -0,0 +1,42 @@
use tiny_skia::Pixmap;
use super::interface::{
component::{Component, ComponentContext, ComponentRenderParams},
render_error::Result,
style::Style,
};
pub struct Container {
children: Vec<Box<dyn Component>>,
}
impl Component for Container {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
}
impl Container {
pub fn from_children(children: Vec<Box<dyn Component>>) -> Container {
Container { children }
}
pub fn draw_root(&self, context: &ComponentContext) -> Result<Pixmap> {
let style = self.parsed_style();
let mut pixmap = Pixmap::new(
(style.width * context.scale_factor) as u32,
(style.height * context.scale_factor) as u32,
)
.unwrap();
self.draw(
&mut pixmap,
context,
ComponentRenderParams::default(),
Style::default(),
Style::default(),
)?;
Ok(pixmap)
}
}

View File

@ -0,0 +1,2 @@
pub mod code;
pub mod mac_title_bar;

View File

@ -0,0 +1,75 @@
use crate::{
code::{calc_wh_with_min_width, prepare_code, CHAR_WIDTH},
components::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentStyle, RawComponentStyle, Size, Style},
},
highlight::Highlight,
text::FontRenderer,
};
pub struct Code {
children: Vec<Box<dyn Component>>,
line_height: f32,
font_size: f32,
value: String,
}
impl Component for Code {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
let (w, h) = calc_wh_with_min_width(&self.value, CHAR_WIDTH, self.line_height);
Style::default().size(Size::Num(w), Size::Num(h))
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
let params = &context.take_snapshot_params;
let highlight = Highlight::new(
self.value.clone(),
params.code_font_family.clone(),
params.code_file_path.clone(),
params.extension.clone(),
);
let highlight_result = highlight.parse(&params.themes_folder, &params.theme)?;
FontRenderer::new(
self.font_size,
self.line_height,
context.scale_factor,
&context.take_snapshot_params.fonts_folder,
)
.draw_text(
render_params.x,
render_params.y,
style.width,
style.height,
highlight_result.clone(),
pixmap,
);
Ok(())
}
}
impl Code {
pub fn new(value: String, line_height: f32, font_size: f32) -> Code {
Code {
value: prepare_code(&value),
line_height,
font_size,
children: vec![],
}
}
}

View File

@ -0,0 +1,109 @@
use tiny_skia::{Color, FillRule, Paint, PathBuilder, Transform};
use crate::{
components::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentStyle, RawComponentStyle, Size, Style},
},
edges::margin::Margin,
};
pub struct MacTitleBar {
radius: f32,
children: Vec<Box<dyn Component>>,
render_condition: bool,
}
impl Component for MacTitleBar {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
let demeter = self.radius * 2.;
Style::default()
.size(Size::Num(demeter + 2. * 25.), Size::Num(demeter))
.margin(Margin {
bottom: 10.,
..Margin::default()
})
}
fn render_condition(&self) -> bool {
return self.render_condition;
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
_style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
self.draw_control_buttons(
// Control bar construct by draw circles, after drawn, the path will be at the center,
// so the x, y need to offset by radius of the circle, and the next shape will still
// be drwan on the original point
render_params.x + self.radius,
render_params.y + self.radius,
pixmap,
vec![
Color::from_rgba8(255, 94, 87, 255),
Color::from_rgba8(255, 186, 46, 255),
Color::from_rgba8(43, 200, 65, 255),
],
25.,
Transform::from_scale(context.scale_factor, context.scale_factor),
);
Ok(())
}
}
impl MacTitleBar {
pub fn from_radius(radius: f32, render_condition: bool) -> MacTitleBar {
MacTitleBar {
radius,
children: vec![],
render_condition,
}
}
fn draw_control_buttons(
&self,
x: f32,
y: f32,
pixmap: &mut tiny_skia::Pixmap,
colors: Vec<Color>,
gap: f32,
transform: Transform,
) {
for (index, color) in colors.into_iter().enumerate() {
self.draw_control_button(x, y, pixmap, color, index as f32 * gap, transform);
}
}
fn draw_control_button(
&self,
x: f32,
y: f32,
pixmap: &mut tiny_skia::Pixmap,
color: Color,
x_offset: f32,
transform: Transform,
) {
let mut path_builder = PathBuilder::new();
path_builder.push_circle(x + x_offset, y, self.radius);
path_builder.close();
let path = path_builder.finish().unwrap();
let mut paint = Paint::default();
paint.set_color(color);
pixmap.fill_path(&path, &paint, FillRule::Winding, transform, None);
}
}

View File

@ -0,0 +1,76 @@
use super::{
interface::{component::Component, style::ComponentStyle},
rect::EDITOR_PADDING,
};
use tiny_skia::{Color, Paint, Rect, Transform};
#[derive(Default)]
pub struct HighlightCodeBlock {
children: Vec<Box<dyn Component>>,
line_height: f32,
start_line_number: usize,
end_line_number: usize,
render_condition: bool,
}
impl Component for HighlightCodeBlock {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn render_condition(&self) -> bool {
self.render_condition
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &super::interface::component::ComponentContext,
render_params: &super::interface::component::RenderParams,
_style: &super::interface::style::ComponentStyle,
parent_style: &ComponentStyle,
) -> super::interface::render_error::Result<()> {
let mut paint = Paint::default();
let start_y_offset = (self.start_line_number - 1) as f32 * self.line_height;
paint.anti_alias = false;
paint.set_color(Color::from_rgba8(255, 255, 255, 10));
pixmap.fill_rect(
Rect::from_xywh(
render_params.x - EDITOR_PADDING,
render_params.y + start_y_offset,
parent_style.width + EDITOR_PADDING * 2.,
(self.end_line_number - self.start_line_number + 1) as f32 * self.line_height,
)
.unwrap(),
&paint,
Transform::from_scale(context.scale_factor, context.scale_factor),
None,
);
Ok(())
}
}
impl HighlightCodeBlock {
pub fn from_line_number(
start_line_number: Option<usize>,
end_line_number: Option<usize>,
line_height: f32,
) -> HighlightCodeBlock {
if end_line_number < start_line_number {
panic!("end_line_number should be greater than start_line_number")
}
match start_line_number {
Some(start_line_number) => HighlightCodeBlock {
render_condition: true,
children: vec![],
line_height,
start_line_number,
end_line_number: end_line_number.unwrap(),
},
None => HighlightCodeBlock::default(),
}
}
}

View File

@ -0,0 +1,3 @@
pub mod component;
pub mod render_error;
pub mod style;

View File

@ -0,0 +1,204 @@
use super::{
render_error,
style::{ComponentAlign, ComponentStyle, RawComponentStyle, Size, Style},
};
use crate::{config::TakeSnapshotParams, edges::edge::Edge};
use std::sync::Arc;
use tiny_skia::Pixmap;
pub struct ComponentContext {
pub scale_factor: f32,
pub take_snapshot_params: Arc<TakeSnapshotParams>,
}
#[derive(Default, Clone)]
pub struct RenderParams {
pub x: f32,
pub y: f32,
}
#[derive(Default)]
pub struct ComponentRenderParams {
pub parent_render_params: RenderParams,
pub sibling_render_params: RenderParams,
}
impl ComponentRenderParams {
fn parse_into_render_params_with_style(
&self,
parent_style: ComponentStyle,
sibling_style: ComponentStyle,
style: ComponentStyle,
) -> RenderParams {
match parent_style.align {
ComponentAlign::Row => RenderParams {
x: self.sibling_render_params.x
+ sibling_style.width
+ style.margin.left
+ sibling_style.padding.horizontal(),
y: self.sibling_render_params.y + style.margin.top,
},
ComponentAlign::Column => RenderParams {
x: self.sibling_render_params.x + style.margin.left,
y: self.sibling_render_params.y
+ style.margin.top
+ sibling_style.height
+ sibling_style.padding.vertical(),
},
}
}
}
pub trait Component {
fn children(&self) -> &Vec<Box<dyn Component>>;
fn align(&self) -> ComponentAlign {
ComponentAlign::Row
}
fn initialize(&self, render_params: &RenderParams) -> RenderParams {
render_params.clone()
}
// The render_condition determines whether the component should be rendered or not
fn render_condition(&self) -> bool {
true
}
// The difference with render_condition is that self_render_condition still renders childrens
fn self_render_condition(&self) -> bool {
true
}
fn draw_self(
&self,
_pixmap: &mut Pixmap,
_context: &ComponentContext,
_render_params: &RenderParams,
_style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
Ok(())
}
fn style(&self) -> RawComponentStyle {
RawComponentStyle::default()
}
fn parse_size(&self, size: Size, dynamic_value: f32) -> f32 {
match size {
Size::Num(num) => num,
Size::Dynamic => dynamic_value,
}
}
fn parsed_style(&self) -> Style<f32> {
// If render_condition return false, the whole component shouldn't rendered,
// includes its children
if !self.render_condition() {
return ComponentStyle::default();
}
// If self_render_condition return false, the component shouldn't rendered,
// so the corresponding style should be cleared
let style = if self.self_render_condition() {
self.style()
} else {
RawComponentStyle::default()
};
let (width, height) = self.get_dynamic_wh();
let width = self.parse_size(style.width, width)
+ style.padding.horizontal()
+ style.margin.horizontal();
Style {
min_width: style.min_width,
width: if width > style.min_width {
width
} else {
style.min_width
},
height: self.parse_size(style.height, height)
+ style.padding.vertical()
+ style.margin.vertical(),
align: style.align,
padding: style.padding,
margin: style.margin,
}
}
fn draw(
&self,
pixmap: &mut Pixmap,
context: &ComponentContext,
component_render_params: ComponentRenderParams,
parent_style: ComponentStyle,
sibling_style: ComponentStyle,
) -> render_error::Result<RenderParams> {
let style = self.parsed_style();
let render_params = self.initialize(
&component_render_params.parse_into_render_params_with_style(
parent_style.clone(),
sibling_style.clone(),
style.clone(),
),
);
// Render nothing on paint if render_condition return false
if !self.render_condition() {
return Ok(render_params.clone());
}
if self.self_render_condition() {
self.draw_self(pixmap, context, &render_params, &style, &parent_style)?;
}
let children = self.children();
let mut sibling_render_params = RenderParams {
x: render_params.x + style.padding.left,
y: render_params.y + style.padding.top,
};
let mut sibling_style = ComponentStyle::default();
for child in children {
sibling_render_params = child.draw(
pixmap,
context,
ComponentRenderParams {
parent_render_params: render_params.clone(),
sibling_render_params,
},
style.clone(),
sibling_style,
)?;
sibling_style = child.parsed_style();
}
Ok(render_params.clone())
}
// Dynamic calculate width and height of children, if the children is empty, get_dynamic_wh
// will return (0., 0.)
fn get_dynamic_wh(&self) -> (f32, f32) {
let children = self.children();
let calc_children_wh = |cb: fn((f32, f32), &Box<dyn Component>) -> (f32, f32)| {
children.iter().fold((0., 0.), cb)
};
let style = self.style();
match style.align {
// If align is row, width is sum of children width, height is max of children height
ComponentAlign::Row => calc_children_wh(|(w, h), child| {
let style = child.parsed_style();
(w + style.width, h.max(style.height))
}),
// If align is column, width is max of children width, height is sum of children height
ComponentAlign::Column => calc_children_wh(|(w, h), child| {
let style = child.parsed_style();
(w.max(style.width), h + style.height)
}),
}
}
}

View File

@ -0,0 +1,28 @@
use nvim_oxi::lua;
use thiserror::Error;
pub type Result<T> = std::result::Result<T, RenderError>;
#[derive(Debug, Error)]
pub enum RenderError {
#[error("Highlight code failed!")]
HighlightThemeLoadFailed,
#[error("No such highlight syntax for {0}")]
HighlightCodeFailed(String),
#[error("Unable to parse unknown background theme {0}")]
UnknownBackgroundTheme(String),
#[error("Invalid hex color {0}")]
InvalidHexColor(String),
#[error("No such file {0}")]
NoSuchFile(String),
}
impl From<RenderError> for nvim_oxi::Error {
fn from(err: RenderError) -> Self {
nvim_oxi::Error::Lua(lua::Error::RuntimeError(err.to_string()))
}
}

View File

@ -0,0 +1,80 @@
use crate::edges::{margin::Margin, padding::Padding};
#[derive(Clone, Debug)]
pub enum ComponentAlign {
Row,
Column,
}
pub enum Size {
Dynamic,
Num(f32),
}
#[derive(Clone, Debug)]
pub struct Style<T> {
pub width: T,
pub height: T,
pub min_width: f32,
pub align: ComponentAlign,
pub padding: Padding,
pub margin: Margin,
}
pub type RawComponentStyle = Style<Size>;
pub type ComponentStyle = Style<f32>;
impl Default for RawComponentStyle {
fn default() -> Self {
Style {
min_width: 0.,
width: Size::Dynamic,
height: Size::Dynamic,
align: ComponentAlign::Row,
padding: Padding::default(),
margin: Margin::default(),
}
}
}
impl Default for ComponentStyle {
fn default() -> Self {
Style {
min_width: 0.,
width: 0.,
height: 0.,
align: ComponentAlign::Row,
padding: Padding::default(),
margin: Margin::default(),
}
}
}
impl RawComponentStyle {
pub fn size(mut self, width: Size, height: Size) -> Self {
self.width = width;
self.height = height;
self
}
// Only works if the width is calculate dynamically
pub fn min_width(mut self, min_width: f32) -> Self {
self.min_width = min_width;
self
}
pub fn align(mut self, align: ComponentAlign) -> Self {
self.align = align;
self
}
pub fn padding(mut self, padding: Padding) -> Self {
self.padding = padding;
self
}
pub fn margin(mut self, margin: Margin) -> Self {
self.margin = margin;
self
}
}

View File

@ -0,0 +1,100 @@
use super::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentStyle, RawComponentStyle, Size, Style},
};
use crate::{code::CHAR_WIDTH, edges::margin::Margin, text::FontRenderer};
use cosmic_text::{Attrs, Color, Family};
const FONT_SIZE: f32 = 14.;
#[derive(Default)]
pub struct LineNumber {
children: Vec<Box<dyn Component>>,
line_height: f32,
render_condition: bool,
line_number_content: Vec<String>,
number_of_digit: usize,
}
impl Component for LineNumber {
fn render_condition(&self) -> bool {
return self.render_condition;
}
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
Style::default()
.size(
Size::Num(CHAR_WIDTH * self.number_of_digit as f32),
Size::Num(self.line_number_content.len() as f32 * self.line_height),
)
.margin(Margin {
right: 10.,
..Margin::default()
})
}
fn draw_self(
&self,
pixmap: &mut tiny_skia::Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
FontRenderer::new(
FONT_SIZE,
self.line_height,
context.scale_factor,
&context.take_snapshot_params.fonts_folder,
)
.draw_text(
render_params.x,
render_params.y,
style.width,
style.height,
vec![(
&self.line_number_content.join("\n"),
Attrs::new()
.color(Color::rgb(73, 81, 98))
.family(Family::Name(&context.take_snapshot_params.code_font_family)),
)],
pixmap,
);
Ok(())
}
}
impl LineNumber {
pub fn new(content: &str, start_line_number: Option<usize>, line_height: f32) -> LineNumber {
match start_line_number {
None => LineNumber::default(),
Some(start_line_number) => {
let lines = content.split("\n").collect::<Vec<&str>>();
let max_line_number = lines.len() + start_line_number;
let number_of_digit = (max_line_number - 1).to_string().len();
LineNumber {
line_number_content: (start_line_number..max_line_number)
.map(|line_number| {
format!(
"{:>width$}",
line_number.to_string(),
width = number_of_digit
)
})
.collect::<Vec<String>>(),
number_of_digit,
children: vec![],
render_condition: true,
line_height,
}
}
}
}
}

View File

@ -0,0 +1,106 @@
use super::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentAlign, ComponentStyle, RawComponentStyle, Style},
};
use crate::edges::padding::Padding;
use tiny_skia::{FillRule, Paint, PathBuilder, Pixmap, Transform};
pub const EDITOR_PADDING: f32 = 20.;
pub struct Rect {
radius: f32,
min_width: f32,
children: Vec<Box<dyn Component>>,
}
impl Component for Rect {
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn style(&self) -> RawComponentStyle {
Style::default()
.min_width(self.min_width)
.align(ComponentAlign::Column)
.padding(Padding::from_value(EDITOR_PADDING))
}
fn draw_self(
&self,
pixmap: &mut Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
let mut path_builder = PathBuilder::new();
let x = render_params.x;
let y = render_params.y;
let w = style.width;
let h = style.height;
let rect_width = w - 2. * self.radius;
let rect_height = h - 2. * self.radius;
path_builder.move_to(x + self.radius, y);
path_builder.line_to(x + self.radius + rect_width, y);
path_builder.line_to(x + self.radius + rect_width, y + self.radius);
path_builder.line_to(x + rect_width + self.radius * 2., y + self.radius);
path_builder.line_to(
x + rect_width + self.radius * 2.,
y + rect_height + self.radius,
);
path_builder.line_to(x + rect_width + self.radius, y + rect_height + self.radius);
path_builder.line_to(
x + rect_width + self.radius,
y + rect_height + self.radius * 2.,
);
path_builder.line_to(x + self.radius, y + rect_height + self.radius * 2.);
path_builder.line_to(x + self.radius, y + rect_height + self.radius);
path_builder.line_to(x, y + rect_height + self.radius);
path_builder.line_to(x, y + self.radius);
path_builder.line_to(x + self.radius, y + self.radius);
path_builder.line_to(x + self.radius, y);
path_builder.line_to(x + self.radius + rect_width, y);
path_builder.push_circle(
x + rect_width + self.radius,
y + rect_height + self.radius,
self.radius,
);
path_builder.push_circle(x + self.radius + rect_width, y + self.radius, self.radius);
path_builder.push_circle(x + self.radius, y + self.radius, self.radius);
path_builder.push_circle(x + self.radius, y + rect_height + self.radius, self.radius);
path_builder.close();
let path = path_builder.finish().unwrap();
let mut paint = Paint::default();
paint.set_color_rgba8(40, 44, 52, 237);
pixmap.fill_path(
&path,
&paint,
FillRule::Winding,
Transform::from_scale(context.scale_factor, context.scale_factor),
// Transform::identity(),
None,
);
Ok(())
}
}
impl Rect {
pub fn new(radius: f32, min_width: Option<f32>, children: Vec<Box<dyn Component>>) -> Rect {
Rect {
radius,
children,
min_width: min_width.unwrap_or(0.),
}
}
}

View File

@ -0,0 +1,82 @@
use cosmic_text::{Align, Attrs, Family};
use tiny_skia::Pixmap;
use crate::{edges::margin::Margin, text::FontRenderer};
use super::interface::{
component::{Component, ComponentContext, RenderParams},
render_error,
style::{ComponentStyle, RawComponentStyle},
};
pub struct Watermark {
children: Vec<Box<dyn Component>>,
value: String,
}
impl Component for Watermark {
fn draw_self(
&self,
pixmap: &mut Pixmap,
context: &ComponentContext,
render_params: &RenderParams,
_style: &ComponentStyle,
_parent_style: &ComponentStyle,
) -> render_error::Result<()> {
let params = &context.take_snapshot_params;
let attrs = Attrs::new().family(Family::Name(
&context.take_snapshot_params.watermark_font_family,
));
FontRenderer::new(
20.,
20.,
context.scale_factor,
&context.take_snapshot_params.fonts_folder,
)
.draw_line(
0.,
render_params.y,
pixmap.width() as f32,
pixmap.height() as f32,
&params.watermark,
attrs,
Some(Align::Center),
pixmap,
);
Ok(())
}
fn children(&self) -> &Vec<Box<dyn Component>> {
&self.children
}
fn render_condition(&self) -> bool {
self.value != ""
}
fn style(&self) -> RawComponentStyle {
let default_style = RawComponentStyle::default();
if self.value != "" {
default_style.margin(Margin {
bottom: 22.,
top: 15.,
..Margin::default()
})
} else {
default_style
}
}
}
impl Watermark {
pub fn new(value: String) -> Watermark {
Watermark {
children: vec![],
value,
}
}
}

63
generator/src/config.rs Normal file
View File

@ -0,0 +1,63 @@
use nvim_oxi::conversion::{Error as ConversionError, FromObject, ToObject};
use nvim_oxi::serde::{Deserializer, Serializer};
use nvim_oxi::{lua, Object};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)]
pub struct TakeSnapshotParams {
// Whether to display the MacOS style title bar
pub mac_window_bar: bool,
// Wartermark of the code snapshot
pub watermark: String,
// Editor title
pub title: Option<String>,
pub code_font_family: String,
pub watermark_font_family: String,
pub code: String,
pub code_file_path: String,
pub extension: Option<String>,
pub save_path: Option<String>,
pub themes_folder: String,
pub fonts_folder: String,
pub theme: String,
pub bg_theme: String,
pub bg_color: Option<String>,
// Breadcrumbs path
pub file_path: String,
pub breadcrumbs_separator: String,
pub has_breadcrumbs: bool,
pub start_line_number: Option<usize>,
pub highlight_start_line_number: Option<usize>,
pub highlight_end_line_number: Option<usize>,
pub min_width: Option<f32>,
pub bg_x_padding: f32,
pub bg_y_padding: f32,
pub bg_padding: Option<f32>,
}
impl FromObject for TakeSnapshotParams {
fn from_object(obj: Object) -> Result<Self, ConversionError> {
Self::deserialize(Deserializer::new(obj)).map_err(Into::into)
}
}
impl ToObject for TakeSnapshotParams {
fn to_object(self) -> Result<Object, ConversionError> {
self.serialize(Serializer::new()).map_err(Into::into)
}
}
impl lua::Poppable for TakeSnapshotParams {
unsafe fn pop(lstate: *mut lua::ffi::lua_State) -> Result<Self, lua::Error> {
let obj = Object::pop(lstate)?;
Self::from_object(obj).map_err(lua::Error::pop_error_from_err::<Self, _>)
}
}
impl lua::Pushable for TakeSnapshotParams {
unsafe fn push(self, lstate: *mut lua::ffi::lua_State) -> Result<std::ffi::c_int, lua::Error> {
self.to_object()
.map_err(lua::Error::push_error_from_err::<Self, _>)?
.push(lstate)
}
}

46
generator/src/copy.rs Normal file
View File

@ -0,0 +1,46 @@
use crate::{config::TakeSnapshotParams, snapshot::take_snapshot};
#[cfg(target_os = "linux")]
use arboard::SetExtLinux;
use arboard::{Clipboard, ImageData};
use nvim_oxi::Result;
// The function will be called as FFI on Lua side
#[allow(dead_code)]
pub fn copy_into_clipboard(config: TakeSnapshotParams) -> Result<()> {
let pixmap = take_snapshot(config.clone())?;
let premultplied_colors = pixmap.pixels();
let colors = premultplied_colors
.iter()
.map(|premultplied_color| {
vec![
premultplied_color.red(),
premultplied_color.green(),
premultplied_color.blue(),
premultplied_color.alpha(),
]
})
.flatten()
.collect::<Vec<u8>>();
let img_data = ImageData {
width: pixmap.width() as usize,
height: pixmap.height() as usize,
bytes: colors.into(),
};
#[cfg(target_os = "linux")]
std::thread::spawn(move || {
Clipboard::new()
.unwrap()
.set()
.wait()
.image(img_data)
.unwrap();
});
#[cfg(not(target_os = "linux"))]
Clipboard::new().unwrap().set_image(img_data).unwrap();
Ok(())
}

View File

@ -0,0 +1,77 @@
use crate::{
code::{calc_max_line_number_length, calc_wh, prepare_code},
config::TakeSnapshotParams,
};
use arboard::Clipboard;
#[cfg(target_os = "linux")]
use arboard::SetExtLinux;
use nvim_oxi::Result;
use std::cmp::max;
const SPACE_BOTH_SIDE: usize = 2;
fn optional(component: String, is_view: bool) -> String {
if is_view {
component
} else {
"".to_string()
}
}
#[allow(dead_code)]
pub fn copy_ascii(params: TakeSnapshotParams) -> Result<()> {
let code = prepare_code(&params.code);
let (width, height) = calc_wh(&code, 1., 1.);
let calc_line_number_width =
|start_line_number: usize| calc_max_line_number_length(height as usize, start_line_number);
let frame_width = max(width as usize, params.file_path.len()) + SPACE_BOTH_SIDE;
let frame_width = match params.start_line_number {
Some(start_line_number) => {
frame_width + SPACE_BOTH_SIDE + calc_line_number_width(start_line_number)
}
None => frame_width,
};
let line = format!("{}\n", "".repeat(frame_width));
let frame_width_with_content = frame_width - 1;
let top_frame = format!("{}\n", "".repeat(frame_width));
let bottom_frame = format!("{}", "".repeat(frame_width));
let code = code
.lines()
.enumerate()
.map(|(i, line)| {
format!(
"│ {:1$} │\n",
match params.start_line_number {
Some(start_line_number) => format!(
"{:1$} {line}",
start_line_number + i,
calc_line_number_width(start_line_number),
),
None => line.to_string(),
},
frame_width_with_content - 1
)
})
.collect::<String>();
let text_line = |text: &str| format!("{:1$}\n", text, frame_width_with_content);
let breadcrumbs = optional(
format!("{}{line}", text_line(&params.file_path)),
params.has_breadcrumbs,
);
let ascii_snapshot = format!("{top_frame}{breadcrumbs}{code}{bottom_frame}");
#[cfg(target_os = "linux")]
std::thread::spawn(move || {
Clipboard::new()
.unwrap()
.set()
.wait()
.text(ascii_snapshot)
.unwrap();
});
#[cfg(not(target_os = "linux"))]
Clipboard::new().unwrap().set_text(ascii_snapshot).unwrap();
Ok(())
}

3
generator/src/edges.rs Normal file
View File

@ -0,0 +1,3 @@
pub mod edge;
pub mod margin;
pub mod padding;

View File

@ -0,0 +1,5 @@
pub trait Edge {
fn horizontal(&self) -> f32;
fn vertical(&self) -> f32;
}

View File

@ -0,0 +1,31 @@
use super::edge::Edge;
#[derive(Clone, Default, Debug)]
pub struct Margin {
pub left: f32,
pub right: f32,
pub top: f32,
pub bottom: f32,
}
impl Edge for Margin {
fn horizontal(&self) -> f32 {
self.left + self.right
}
fn vertical(&self) -> f32 {
self.bottom + self.top
}
}
impl Margin {
#[allow(dead_code)]
pub fn from_value(value: f32) -> Margin {
Margin {
left: value,
right: value,
top: value,
bottom: value,
}
}
}

View File

@ -0,0 +1,30 @@
use super::edge::Edge;
#[derive(Clone, Default, Debug)]
pub struct Padding {
pub left: f32,
pub right: f32,
pub top: f32,
pub bottom: f32,
}
impl Edge for Padding {
fn horizontal(&self) -> f32 {
self.left + self.right
}
fn vertical(&self) -> f32 {
self.bottom + self.top
}
}
impl Padding {
pub fn from_value(value: f32) -> Padding {
Padding {
left: value,
right: value,
top: value,
bottom: value,
}
}
}

107
generator/src/highlight.rs Normal file
View File

@ -0,0 +1,107 @@
use std::collections::HashMap;
use cosmic_text::{Attrs, Family, Style, Weight};
use syntect::{
easy::HighlightLines,
highlighting::{FontStyle, ThemeSet},
parsing::{SyntaxReference, SyntaxSet},
util::LinesWithEndings,
};
use crate::components::interface::render_error::RenderError;
type SourceMap = HashMap<&'static str, &'static str>;
pub struct Highlight {
content: String,
code_file_path: String,
extension: Option<String>,
font_family: String,
highlighting_language_source_map: SourceMap,
}
pub type HighlightResult<'a> = Vec<(&'a str, Attrs<'a>)>;
impl Highlight {
pub fn new(
content: String,
font_family: String,
code_file_path: String,
extension: Option<String>,
) -> Highlight {
Highlight {
content,
code_file_path,
extension,
font_family,
highlighting_language_source_map: HashMap::from([("PHP", "<?php")]),
}
}
fn guess_syntax(&self, syntax_set: &SyntaxSet) -> Result<SyntaxReference, RenderError> {
// The extension exist only when users specified explicitly
// By default, using filepath to detect what syntax should use
let syntax = match &self.extension {
Some(extension) => syntax_set
.find_syntax_by_extension(&extension)
.ok_or(RenderError::HighlightCodeFailed(extension.to_string()))?,
None => syntax_set
.find_syntax_for_file(&self.code_file_path)
.map_err(|_| RenderError::NoSuchFile(self.code_file_path.to_string()))?
.ok_or(RenderError::HighlightCodeFailed(
self.code_file_path.to_string(),
))?,
};
// The Syntect clearly distinguish between PHP and PHP Source
// Should use PHP as highlight language if the source content contains "<php" tag
// Should use PHP Source as highlight language if the source content not contains "<php" tag
if let Some(identifier) = self.highlighting_language_source_map.get(&syntax.name[..]) {
if !self.content.contains(identifier) {
return Ok(syntax_set
.find_syntax_by_name(&format!("{} Source", &syntax.name))
.unwrap_or(syntax)
.to_owned());
}
}
Ok(syntax.to_owned())
}
pub fn parse(
&self,
theme_folder: &str,
theme: &str,
) -> Result<Vec<(&str, Attrs)>, RenderError> {
let syntax_set = two_face::syntax::extra_newlines();
let theme_set = ThemeSet::load_from_folder(theme_folder)
.map_err(|_| RenderError::HighlightThemeLoadFailed)?;
let syntax = &self.guess_syntax(&syntax_set)?;
let mut highlight = HighlightLines::new(syntax, &theme_set.themes[theme]);
let attrs = Attrs::new().family(Family::Name(self.font_family.as_ref()));
// Highlight the content line by line using highlight_line function
Ok(LinesWithEndings::from(&self.content)
.map(|line| {
highlight
.highlight_line(line, &syntax_set)
.unwrap()
.into_iter()
.map(|(style, str)| {
let syntect::highlighting::Color { r, g, b, a: _ } = style.foreground;
let attrs = match style.font_style {
FontStyle::BOLD => attrs.weight(Weight::BOLD),
FontStyle::ITALIC => attrs.style(Style::Italic),
FontStyle::UNDERLINE => attrs.style(Style::Normal),
_ => attrs,
};
(str, attrs.color(cosmic_text::Color::rgb(r, g, b)))
})
.collect::<HighlightResult>()
})
.fold(vec![], |acc, cur| [acc, cur].concat())
.into_iter()
.collect::<HighlightResult>())
}
}

29
generator/src/lib.rs Normal file
View File

@ -0,0 +1,29 @@
mod code;
mod color;
mod components;
mod config;
mod copy;
mod copy_ascii;
mod edges;
mod highlight;
mod path;
mod save;
mod snapshot;
mod text;
use copy::copy_into_clipboard;
use copy_ascii::copy_ascii;
use nvim_oxi::{Dictionary, Function, Result};
use save::save_snapshot;
#[nvim_oxi::module]
fn generator() -> Result<Dictionary> {
Ok(Dictionary::from_iter([
(
"copy_into_clipboard",
Function::from_fn(copy_into_clipboard),
),
("save_snapshot", Function::from_fn(save_snapshot)),
("copy_ascii", Function::from_fn(copy_ascii)),
]))
}

10
generator/src/path.rs Normal file
View File

@ -0,0 +1,10 @@
use regex::Regex;
use std::env::{var, VarError};
pub fn parse_save_path(path: String) -> Result<String, VarError> {
let home_path = var("HOME")?;
let regex = Regex::new(r"(~|$HOME)").unwrap();
let path = regex.replace_all(&path, home_path);
Ok(path.to_string())
}

27
generator/src/save.rs Normal file
View File

@ -0,0 +1,27 @@
use crate::{config::TakeSnapshotParams, path::parse_save_path, snapshot::take_snapshot};
use nvim_oxi::{lua::Error::RuntimeError, Error, Result};
// The function will be called as FFI on Lua side
#[allow(dead_code)]
pub fn save_snapshot(config: TakeSnapshotParams) -> Result<()> {
match &config.save_path {
Some(path) => {
if !path.ends_with(".png") {
return Err(Error::Lua(RuntimeError(
"The save_path must ends with .png".to_string(),
)));
}
let pixmap = take_snapshot(config.clone())?;
let path = parse_save_path(path.to_string())
.map_err(|err| Error::Lua(RuntimeError(err.to_string())))?;
pixmap
.save_png(path)
.map_err(|err| Error::Lua(RuntimeError(err.to_string())))
}
None => Err(Error::Lua(RuntimeError(
"Cannot find 'save_path' in config".to_string(),
))),
}
}

78
generator/src/snapshot.rs Normal file
View File

@ -0,0 +1,78 @@
use std::sync::Arc;
use tiny_skia::Pixmap;
use crate::components::background::Background;
use crate::components::breadcrumbs::Breadcrumbs;
use crate::components::code_block::CodeBlock;
use crate::components::container::Container;
use crate::components::editor::code::Code;
use crate::components::editor::mac_title_bar::MacTitleBar;
use crate::components::highlight_code_block::HighlightCodeBlock;
use crate::components::interface::component::ComponentContext;
use crate::components::interface::render_error;
use crate::components::line_number::LineNumber;
use crate::components::rect::Rect;
use crate::components::watermark::Watermark;
use crate::config::TakeSnapshotParams;
// Scale the screenshot to 3 times its size
const SCALE_FACTOR: f32 = 3.;
const LINE_HEIGHT: f32 = 20.;
const VIEW_WATERMARK_PADDING: f32 = 82.;
// The params is come from neovim instance
pub fn take_snapshot(params: TakeSnapshotParams) -> render_error::Result<Pixmap> {
let context = ComponentContext {
scale_factor: SCALE_FACTOR,
take_snapshot_params: Arc::new(params.clone()),
};
let background_padding = Background::parse_background_padding(
params.bg_x_padding,
params.bg_y_padding,
params.bg_padding,
);
// If vertical background padding is less than 82., should hidden watermark component
// If watermark text is equal to "", the watermark component is hidden
let watermark = if background_padding.bottom >= VIEW_WATERMARK_PADDING {
params.watermark
} else {
"".to_string()
};
let pixmap = Container::from_children(vec![Box::new(Background::new(
background_padding,
vec![
Box::new(Rect::new(
16.,
params.min_width,
vec![
Box::new(MacTitleBar::from_radius(8., params.mac_window_bar)),
Box::new(Breadcrumbs::from_path(
params.file_path,
15.,
params.breadcrumbs_separator,
params.has_breadcrumbs,
)),
Box::new(CodeBlock::from_children(vec![
Box::new(HighlightCodeBlock::from_line_number(
params.highlight_start_line_number,
params.highlight_end_line_number,
LINE_HEIGHT,
)),
Box::new(LineNumber::new(
&params.code,
params.start_line_number,
LINE_HEIGHT,
)),
Box::new(Code::new(params.code, LINE_HEIGHT, 15.)),
])),
],
)),
Box::new(Watermark::new(watermark)),
],
))])
.draw_root(&context)?;
Ok(pixmap)
}

121
generator/src/text.rs Normal file
View File

@ -0,0 +1,121 @@
use cosmic_text::{
Align, Attrs, AttrsList, Buffer, BufferLine, Color, FontSystem, LineEnding, Metrics, Shaping,
SwashCache,
};
use tiny_skia::{Paint, Pixmap, Rect, Transform};
pub struct FontRenderer {
font_system: FontSystem,
scale_factor: f32,
metrics: Metrics,
}
impl FontRenderer {
pub fn new(
font_size: f32,
line_height: f32,
scale_factor: f32,
fonts_folder: &str,
) -> FontRenderer {
let mut font_system = FontSystem::new();
font_system.db_mut().load_fonts_dir(fonts_folder);
let metrics = Metrics::new(font_size, line_height).scale(scale_factor.clone());
FontRenderer {
metrics,
font_system,
scale_factor,
}
}
pub fn draw_text(
&mut self,
x: f32,
y: f32,
w: f32,
h: f32,
spans: Vec<(&str, Attrs)>,
pixmap: &mut Pixmap,
) {
let mut buffer = Buffer::new(&mut self.font_system, self.metrics);
buffer.set_size(
&mut self.font_system,
Some(w * self.scale_factor),
Some(h * self.scale_factor),
);
buffer.set_rich_text(
&mut self.font_system,
spans,
Attrs::new(),
Shaping::Advanced,
);
self.draw(x, y, &mut buffer, pixmap);
}
pub fn draw_line(
&mut self,
x: f32,
y: f32,
w: f32,
h: f32,
line: &str,
attrs: Attrs,
align: Option<Align>,
pixmap: &mut Pixmap,
) {
let mut buffer = Buffer::new(&mut self.font_system, self.metrics);
let mut line = if cfg!(unix) {
BufferLine::new(
line,
LineEnding::Lf,
AttrsList::new(attrs),
Shaping::Advanced,
)
} else if cfg!(windows) {
BufferLine::new(
line,
LineEnding::CrLf,
AttrsList::new(attrs),
Shaping::Advanced,
)
} else {
panic!("Unsupported OS")
};
line.set_align(align);
buffer.lines = vec![line];
buffer.set_size(&mut self.font_system, Some(w), Some(h));
self.draw(x, y, &mut buffer, pixmap);
}
fn draw<'a>(&mut self, x: f32, y: f32, buffer: &mut Buffer, pixmap: &mut Pixmap) {
let mut swash_cache = SwashCache::new();
let default_font_color = Color::rgb(255, 255, 255);
buffer.draw(
&mut self.font_system,
&mut swash_cache,
default_font_color,
|font_x, font_y, w, h, color| {
let mut paint = Paint {
anti_alias: true,
..Default::default()
};
paint.set_color_rgba8(color.r(), color.g(), color.b(), color.a());
let rect = Rect::from_xywh(
font_x as f32 + x * self.scale_factor,
font_y as f32 + y * self.scale_factor,
w as f32,
h as f32,
)
.expect("Cannot draw text on pixmap");
pixmap.fill_rect(rect, &paint, Transform::identity(), None);
},
);
}
}

View File

@ -1,61 +0,0 @@
local logger = require("codesnap.utils.logger")
local static = require("codesnap.static")
local client = {
job_id = 0,
}
local cwd = static.cwd .. "/snap-server"
function client:connect()
return vim.fn.jobstart({
cwd .. "/target/release/snap-server",
}, {
cwd = cwd,
stderr_buffered = true,
rpc = true,
on_stderr = function(_, err)
vim.fn.jobstop(self.job_id)
logger.error(err)
end,
on_exit = function()
vim.fn.chanclose(self.job_id)
self.job_id = 0
end,
})
end
function client:init()
return self.job_id == 0 and client:connect() or self.job_id
end
function client:start()
self.job_id = client:init()
if self.job_id == 0 then
logger.error("cannot start rpc process")
return
end
if self.job_id == -1 then
logger.error("rpc process is not executable")
vim.fn.jobstop(self.job_id)
return
end
return self
end
function client:send(event, message)
vim.fn.rpcnotify(self.job_id, event, message)
end
function client:stop()
if self.job_id == 0 or self.job_id == -1 then
return
end
vim.fn.jobstop(self.job_id)
end
return client

59
lua/codesnap/config.lua Normal file
View File

@ -0,0 +1,59 @@
local visual_utils = require("codesnap.utils.visual")
local path_utils = require("codesnap.utils.path")
local string_utils = require("codesnap.utils.string")
local static = require("codesnap.static")
local table_utils = require("codesnap.utils.table")
local config_module = {}
local assets_folder = static.cwd .. "/assets"
-- Auto generated codesnap filename based on the following rule:
-- CodeSnap_y-m-d_at_h:m:s
local function auto_generate_snap_filename()
return os.date("CodeSnap_%Y-%m-%d_at_%H:%M:%S.png")
end
-- If the save_path is already configured, but no explicit filename is specified,
-- it will be replaced with auto-generated filename
local function parse_save_path(save_path)
if save_path == nil or string_utils.ends_with(save_path, "png") then
return save_path
end
local parsed_save_path = string_utils.ends_with(save_path, "/") and save_path or save_path .. "/"
return parsed_save_path .. auto_generate_snap_filename()
end
local function get_file_path(show_workspace)
local relative_path = path_utils.get_relative_path()
return show_workspace and path_utils.get_workspace() .. "/" .. relative_path or relative_path
end
function config_module.get_config(extension)
local code = visual_utils.get_selected_text()
local start_line_number = visual_utils.get_start_line_number()
if string_utils.is_str_empty(code) then
error("No code is selected", 0)
return
end
local config = table_utils.merge({
code = code,
extension = extension,
code_file_path = vim.fn.expand("%:p"),
fonts_folder = assets_folder .. "/fonts",
themes_folder = assets_folder .. "/themes",
theme = "base16-rose-pine",
file_path = static.config.has_breadcrumbs and get_file_path(static.config.show_workspace) or "",
start_line_number = static.config.has_line_number and start_line_number or nil,
}, static.config)
config.save_path = parse_save_path(config.save_path)
return config
end
return config_module

View File

@ -0,0 +1,55 @@
local string_utils = require("codesnap.utils.string")
local table_utils = require("codesnap.utils.table")
local highlight_module = {}
function highlight_module.call_cb_with_parsed_config(cb_name, highlight_start_line_number, highlight_end_line_number)
vim.api.nvim_buf_delete(0, {})
vim.schedule(function()
local main = require("codesnap")
local config = table_utils.merge(main.highlight_mode_config, {
highlight_start_line_number = highlight_start_line_number,
highlight_end_line_number = highlight_end_line_number,
})
main[cb_name](config)
end)
end
function highlight_module.create_highlight_selector_window(cb_name, code)
local width = 100
local height = #code + 2
local row = vim.fn.winheight(0) / 2 - height / 2
local col = vim.fn.winwidth(0) / 2 - width / 2
local bufnr = vim.api.nvim_create_buf(false, true)
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, code)
local window_id = vim.api.nvim_open_win(bufnr, false, {
relative = "editor",
width = width,
height = height,
col = col,
row = row,
style = "minimal",
border = "rounded",
title = "Select highlight lines",
title_pos = "center",
})
vim.api.nvim_buf_set_option(bufnr, "modifiable", false)
vim.api.nvim_buf_set_option(bufnr, "filetype", vim.bo.filetype)
vim.api.nvim_buf_set_keymap(bufnr, "n", "q", ":q<CR>", {})
vim.api.nvim_buf_set_keymap(bufnr, "", "<ESC>", ":q<CR>", {})
vim.api.nvim_buf_set_keymap(
bufnr,
"v",
"<CR>",
":lua require('codesnap.highlight').call_cb_with_parsed_config('"
.. cb_name
.. "', require('codesnap.utils.visual').get_start_line_number(), require('codesnap.utils.visual').get_end_line_number())<CR>",
{ silent = true }
)
vim.api.nvim_set_current_win(window_id)
end
return highlight_module

View File

@ -1,33 +1,76 @@
local table_utils = require("codesnap.utils.table")
local static = require("codesnap.static") local static = require("codesnap.static")
local client = require("codesnap.client")
local visual_utils = require("codesnap.utils.visual") local visual_utils = require("codesnap.utils.visual")
local table_utils = require("codesnap.utils.table")
local string_utils = require("codesnap.utils.string")
local config_module = require("codesnap.config")
local highlight_module = require("codesnap.highlight")
local main = { local main = {
cwd = static.cwd, cwd = static.cwd,
preview_switch = static.preview_switch, preview_switch = static.preview_switch,
highlight_mode_config = nil,
} }
function main.setup(config) function main.setup(config)
static.config = table_utils.merge(static.config, config == nil and {} or config) static.config = table_utils.merge(static.config, config == nil and {} or config)
if static.config.auto_load then
client:start()
end end
client:send("config_setup", static.config) function main.copy_into_clipboard_with_config(config)
require("generator").copy_into_clipboard(config)
vim.cmd("delmarks <>")
vim.notify("Save snapshot into clipboard successfully")
end end
function main.preview_code() -- Take ASCII code snapshot into clipboard
client:send("preview_code", { content = visual_utils.get_selected_text(), language = vim.bo.filetype }) function main.copy_ascii_snapshot(extension)
require("generator").copy_ascii(config_module.get_config(extension))
vim.cmd("delmarks <>")
vim.notify("Save snapshot into clipboard successfully")
end end
function main.open_preview() function main.save_snapshot_with_config(config)
client:send("open_preview") if string_utils.is_str_empty(static.config.save_path) then
error(
"If you want to save snapshot in somewhere, you should config the save_path before, refer: https://github.com/mistricky/codesnap.nvim?tab=readme-ov-file#save-the-snapshot",
0
)
end end
function main.stop_client() local matched_extension = string.match(static.config.save_path, "%.(.+)$")
client:stop()
if matched_extension ~= "png" and matched_extension ~= nil then
error("The extension of save_path should be .png", 0)
end
require("generator").save_snapshot(config)
vim.cmd("delmarks <>")
---@diagnostic disable-next-line: need-check-nil
vim.notify("Save snapshot in " .. config.save_path .. " successfully")
end
-- Take a snapshot and copy it into clipboard
function main.copy_into_clipboard(extension)
main.copy_into_clipboard_with_config(config_module.get_config(extension))
end
-- Take a snapshot and save it into the specified path
function main.save_snapshot(extension)
main.save_snapshot_with_config(config_module.get_config(extension))
end
function main.highlight_mode_copy_into_clipboard(extension)
main.highlight_mode_config = config_module.get_config(extension)
highlight_module.create_highlight_selector_window(
"copy_into_clipboard_with_config",
visual_utils.get_selected_lines()
)
end
function main.highlight_mode_save_snapshot(extension)
main.highlight_mode_config = config_module.get_config(extension)
highlight_module.create_highlight_selector_window("save_snapshot_with_config", visual_utils.get_selected_lines())
end end
return main return main

View File

@ -3,13 +3,19 @@ local path_utils = require("codesnap.utils.path")
return { return {
config = { config = {
mac_window_bar = true, mac_window_bar = true,
opacity = true, title = "CodeSnap.nvim",
watermark = "CodeSnap.nvim", code_font_family = "CaskaydiaCove Nerd Font",
preview_title = "CodeSnap.nvim",
editor_font_family = "CaskaydiaCove Nerd Font",
watermark_font_family = "Pacifico", watermark_font_family = "Pacifico",
highlight_theme = "atom-one-dark", watermark = "CodeSnap.nvim",
auto_load = true, bg_theme = "default",
breadcrumbs_separator = "/",
has_breadcrumbs = false,
has_line_number = false,
show_workspace = false,
min_width = 0,
bg_x_padding = 122,
bg_y_padding = 82,
save_path = path_utils.get_default_save_path(),
}, },
cwd = path_utils.back(path_utils.back(debug.getinfo(1, "S").source:sub(2):match("(.*[/\\])"))), cwd = path_utils.back(path_utils.back(debug.getinfo(1, "S").source:sub(2):match("(.*[/\\])"))),
preview_switch = true, preview_switch = true,

View File

@ -1,11 +0,0 @@
local logger = {}
function logger.log(level, message)
vim.api.nvim_notify("[" .. level .. "] CodeSnap: " .. tostring(vim.inspect(message)), vim.log.levels[level], {})
end
function logger.error(message)
logger.log("ERROR", message)
end
return logger

View File

@ -1,9 +1,47 @@
local string_utils = require("codesnap.utils.string")
local platform_utils = require("codesnap.utils.platform")
local path_utils = {} local path_utils = {}
function path_utils.get_escaped_cwd()
local cwd = vim.fn.getcwd()
return string_utils.escape(cwd)
end
function path_utils.back(path) function path_utils.back(path)
local parsed_path, _ = path:gsub("/[^\\/]+/?$", "") local parsed_path, _ = path:gsub("/[^\\/]+/?$", "")
return parsed_path return parsed_path
end end
function path_utils.get_workspace()
local cwd = vim.fn.getcwd()
local _, _, workspace = string.find(cwd, "/([^/]+)$")
return workspace == nil and "" or workspace
end
function path_utils.get_relative_path()
local full_file_path = vim.fn.expand("%:p")
return full_file_path:gsub(path_utils.get_escaped_cwd(), ""):sub(2)
end
-- Get default save path by OS
-- If Linux, use XDG_PICTURE_DIR
-- if mac use ~/Pictures
-- if windows use FOLDERID_Pictures (If support is added back)
function path_utils.get_default_save_path()
local home_picture_folder = os.getenv("HOME") .. "/Pictures"
return platform_utils.match_os({
Darwin = function()
return home_picture_folder
end,
Linux = function()
return os.getenv("XDG_PICTURES_DIR") or home_picture_folder
end,
})
end
return path_utils return path_utils

View File

@ -0,0 +1,15 @@
local platform_utils = {}
local current_os_name = vim.loop.os_uname().sysname
function platform_utils.match_os(matches_table)
local fn = matches_table[current_os_name]
if fn == nil then
error("codesnap.nvim not supported on " .. current_os_name)
end
return fn()
end
return platform_utils

View File

@ -12,4 +12,26 @@ function string_util.ends_with(str, suffix)
return str:sub(-#suffix) == suffix return str:sub(-#suffix) == suffix
end end
function string_util.is_str_empty(target)
return target == nil or target == ""
end
function string_util.convert_empty_to_nil(target)
if target == "" then
return nil
else
return target
end
end
function string_util.split(str, delimiter)
local result = {}
for token in string.gmatch(str, "[^" .. delimiter .. "]+") do
table.insert(result, token)
end
return result
end
return string_util return string_util

View File

@ -33,7 +33,7 @@ end
function table_utils.serialize_array(t) function table_utils.serialize_array(t)
local result = list_utils.map(t, function(ele) local result = list_utils.map(t, function(ele)
table_utils.serialize_json(ele) table_utils.to_string(ele)
end) end)
return "[" .. result.concat(t, ",") .. "]" return "[" .. result.concat(t, ",") .. "]"
@ -43,17 +43,17 @@ function table_utils.serialize_table(t)
local result = {} local result = {}
for key, value in pairs(t) do for key, value in pairs(t) do
table.insert(result, string.format('"%s":%s', key, table_utils.serialize_json(value))) table.insert(result, string.format("%s = %s", key, table_utils.to_string(value)))
end end
return "{" .. table.concat(result, ",") .. "}" return "{" .. table.concat(result, ",") .. "}"
end end
function table_utils.serialize_string(value) function table_utils.serialize_string(value)
return '"' .. value .. '"' return "[[" .. value .. "]]"
end end
function table_utils.serialize_json(t) function table_utils.to_string(t)
local complex_type_parser = { local complex_type_parser = {
array = table_utils.serialize_array, array = table_utils.serialize_array,
table = table_utils.serialize_table, table = table_utils.serialize_table,
@ -67,4 +67,14 @@ function table_utils.serialize_json(t)
return parse(t) return parse(t)
end end
-- function table_utils.to_string(t)
-- local result = ""
--
-- for key, value in pairs(t) do
-- result = result .. key .. ":" .. tostring(value) .. ","
-- end
--
-- return "{" .. result .. "}"
-- end
return table_utils return table_utils

View File

@ -1,6 +1,36 @@
local visual_utils = {} local visual_utils = {}
-- Get all the lines from "from" to "to" and return them as a single string
-- If "from" and "to" are the same, return the line at "from"
local function get_whole_lines(from, to)
local lines = {}
if from == to then
table.insert(lines, vim.api.nvim_buf_get_lines(0, from - 1, from, false)[1])
else
for i = from, to do
table.insert(lines, vim.api.nvim_buf_get_lines(0, i - 1, i, false)[1])
end
end
return table.concat(lines, "\n")
end
function visual_utils.get_start_line_number()
return vim.fn.line("'<")
end
function visual_utils.get_end_line_number()
return vim.fn.line("'>")
end
function visual_utils.get_selected_lines()
return vim.fn.getline("'<", "'>")
end
function visual_utils.get_selected_text() function visual_utils.get_selected_text()
return table.concat(visual_utils.get_selected_lines(), "\n")
end
function visual_utils.get_selected_text_realtime()
local start_pos = vim.fn.getpos("v") local start_pos = vim.fn.getpos("v")
local end_pos = vim.fn.getpos(".") local end_pos = vim.fn.getpos(".")
@ -10,9 +40,14 @@ function visual_utils.get_selected_text()
start_pos, end_pos = end_pos, start_pos start_pos, end_pos = end_pos, start_pos
end end
if vim.api.nvim_get_mode().mode == "V" then
return get_whole_lines(start_pos[2], end_pos[2])
end
if start_pos[2] == end_pos[2] then if start_pos[2] == end_pos[2] then
return vim.api.nvim_buf_get_lines(0, start_pos[2] - 1, start_pos[2], false)[1]:sub(start_pos[3], end_pos[3] - 1) return vim.api.nvim_buf_get_lines(0, start_pos[2] - 1, start_pos[2], false)[1]:sub(start_pos[3], end_pos[3] - 1)
else end
local selected_text = {} local selected_text = {}
for i = start_pos[2], end_pos[2] do for i = start_pos[2], end_pos[2] do
local line_text = vim.api.nvim_buf_get_lines(0, i - 1, i, false)[1] local line_text = vim.api.nvim_buf_get_lines(0, i - 1, i, false)[1]
@ -25,8 +60,8 @@ function visual_utils.get_selected_text()
end end
table.insert(selected_text, line_text) table.insert(selected_text, line_text)
end end
return table.concat(selected_text, "\n") return table.concat(selected_text, "\n")
end end
end
return visual_utils return visual_utils

BIN
lua/linux-x86_64generator.so Executable file

Binary file not shown.

BIN
lua/mac-aarch64generator.so Executable file

Binary file not shown.

BIN
lua/mac-x86_64generator.so Executable file

Binary file not shown.

View File

@ -1,14 +1,8 @@
build: build:
make build_preview_client ./scripts/apply_generator.sh
make build_server
make make_static_files
build_preview_client: build_generator_debug:
cd snap-client && npm install && npm run build ./scripts/build_generator.sh
build_server: build_generator:
cd snap-server && cargo build --release ./scripts/build_generator.sh --release
make_static_files:
cp -r snap-client/build snap-server/public
cp -r snap-client/node_modules/highlight.js/styles/ snap-server/public/

View File

@ -1,34 +1,42 @@
local codesnap = require("codesnap") local codesnap = require("codesnap")
-- local client = require("codesnap.client")
-- vim.api.nvim_create_user_command("CodeSnap", function() -- The func param is a function that come from rust side, the function
-- client:send("copy") -- may raise exception to user side, the run_generator_function is used to
-- end, {}) -- handle these function and print it friendly
local function run_generator_function(func)
vim.api.nvim_create_user_command("CodeSnapPreviewOn", function() xpcall(func, function(err)
codesnap.open_preview() print(err)
end, {}) end)
local validModes = {
["v"] = true,
["V"] = true,
["^V"] = true,
}
vim.api.nvim_create_autocmd({ "CursorMoved" }, {
callback = function()
local mode = vim.api.nvim_get_mode().mode
if not validModes[mode] or not codesnap.preview_switch then
return
end end
codesnap.preview_code() local function take_snapshot(take_snapshot_function)
end, return function(detail)
}) local args = detail.fargs
vim.api.nvim_create_autocmd({ "VimLeavePre" }, { run_generator_function(function()
pattern = "*", take_snapshot_function(args[1])
callback = function() end)
codesnap.stop_client() end
end, end
})
vim.api.nvim_create_user_command("CodeSnap", take_snapshot(codesnap.copy_into_clipboard), { nargs = "*", range = "%" })
vim.api.nvim_create_user_command("CodeSnapSave", take_snapshot(codesnap.save_snapshot), { nargs = "*", range = "%" })
vim.api.nvim_create_user_command(
"CodeSnapASCII",
take_snapshot(codesnap.copy_ascii_snapshot),
{ nargs = "*", range = "%" }
)
vim.api.nvim_create_user_command(
"CodeSnapHighlight",
take_snapshot(codesnap.highlight_mode_copy_into_clipboard),
{ nargs = "*", range = "%" }
)
vim.api.nvim_create_user_command(
"CodeSnapSaveHighlight",
take_snapshot(codesnap.highlight_mode_save_snapshot),
{ nargs = "*", range = "%" }
)

View File

@ -1,6 +1,6 @@
[project] [project]
name = "codesnap.nvim" name = "codesnap.nvim"
version = "0.0.9" version = "1.6.0"
description = "📸 Snapshot plugin that can make pretty code snapshots with real-time previews for Neovim" description = "📸 Snapshot plugin that can make pretty code snapshots with real-time previews for Neovim"
author = "Mist" author = "Mist"
email = "mist.zzh@gmail.com" email = "mist.zzh@gmail.com"

9
scripts/apply_generator.sh Executable file
View File

@ -0,0 +1,9 @@
#!/usr/bin/env bash
source ./scripts/check_os.sh
function apply_generator {
cp -rf lua/"${os}generator.so" lua/generator.so
}
apply_generator $os

18
scripts/build_generator.sh Executable file
View File

@ -0,0 +1,18 @@
#!/usr/bin/env bash
source ./scripts/check_os.sh
(cd ./generator; cargo build $1)
lib_suffix="so"
target="debug"
if [[ $os =~ "mac" ]]; then
lib_suffix="dylib"
fi
if [[ $1 =~ "release" ]]; then
target="release"
fi
cp -rf ./generator/target/$target/libgenerator.$lib_suffix lua/generator.so

18
scripts/check_os.sh Normal file
View File

@ -0,0 +1,18 @@
os="Unknown"
uname_output=`uname`
if [[ $uname_output == "Darwin" ]]; then
uname_m_output=`uname -m`
if [[ $uname_m_output == "arm64" ]]; then
os="mac-aarch64"
elif [[ $uname_m_output == "x86_64" ]]; then
os="mac-x86_64"
else
echo "Unknown sillicon"
fi
elif [[ $uname_output == "Linux" ]]; then
os="linux-x86_64"
else
echo "Unknown platform"
fi

View File

@ -1,23 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -1,46 +0,0 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

File diff suppressed because it is too large Load Diff

View File

@ -1,55 +0,0 @@
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@tailwindcss/typography": "^0.5.10",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.81",
"@types/react": "^18.2.55",
"@types/react-dom": "^18.2.19",
"downloadjs": "^1.4.7",
"highlight.js": "^11.9.0",
"html-to-image": "^1.11.11",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"react-use-websocket": "^3.0.0",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "npm run tailwindcss:compile && react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"tailwindcss:watch": "npm run tailwindcss:compile -- -w",
"tailwindcss:compile": "tailwindcss -i ./src/input.css -o ./src/output.css"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@types/downloadjs": "^1.4.6",
"daisyui": "^3.9.4",
"tailwindcss": "^3.4.1"
}
}

View File

@ -1,47 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css2?family=Pacifico&display=swap" rel="stylesheet" crossorigin="anonymous">
<link rel="stylesheet" href="https://mshaugh.github.io/nerdfont-webfonts/build/caskaydiacove-nerd-font.css" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@ -1,15 +0,0 @@
{
"short_name": "CdeoSnap.nvim",
"name": "CodeSnap.nvim",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -1,3 +0,0 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -1,128 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "react";
import useWebSocket, { ReadyState } from "react-use-websocket";
import { ControlBar, Editor, Frame, Panel } from "./components";
import { useConfig, useEvent } from "./hooks";
import { toPng, toBlob } from "html-to-image";
import download from "downloadjs";
import { getWebsocketHost } from "./utils";
const CODE_EMPTY_PLACEHOLDER = `print "Hello, CodeSnap.nvim!"`;
const WATER_MARK_PLACEHOLDER = "CodeSnap.nvim";
const PREVIEW_TITLE_PLACEHOLDER = "CodeSnap.nvim";
const DEFAULT_THEME = "atom-one-dark";
function App() {
const [socketUrl] = useState(`ws://${getWebsocketHost()}/ws`);
const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);
const event = useEvent(lastMessage);
const config = useConfig(event?.config_setup);
const frameRef = useRef<HTMLDivElement | null>(null);
const [isCopyButtonDisabled, setIsCopyButtonDisabled] = useState(false);
const handleCopyButtonClick = useCallback(async () => {
if (!frameRef.current) {
return;
}
setIsCopyButtonDisabled(true);
try {
const blob = await toBlob(frameRef.current);
const clipboardItem = new ClipboardItem({ "image/png": blob! });
navigator.clipboard.write([clipboardItem]);
} catch (e) {
console.error(e);
} finally {
setIsCopyButtonDisabled(false);
}
}, []);
const handleExportClick = useCallback(async () => {
if (!frameRef.current) {
return;
}
const dataURL = await toPng(frameRef.current);
download(dataURL, "codesnap.png");
}, []);
const notifyCopyCommand = useCallback(async () => {
if (!frameRef.current) {
return;
}
const dataURL = await toPng(frameRef.current);
sendMessage(dataURL);
}, [sendMessage]);
useEffect(() => {
if (readyState !== ReadyState.OPEN || !event?.copy) {
return;
}
notifyCopyCommand();
}, [event, readyState, notifyCopyCommand]);
useEffect(() => {
document.title = config?.preview_title ?? PREVIEW_TITLE_PLACEHOLDER;
}, []);
useEffect(() => {
const theme = config?.highlight_theme ?? DEFAULT_THEME;
const cssLink = document.createElement("link");
cssLink.rel = "stylesheet";
cssLink.href = `./styles/${theme}.css`;
document.head.appendChild(cssLink);
return () => {
document.head.removeChild(cssLink);
};
}
, [config?.highlight_theme]);
return (
<div className="w-full h-full flex flex-col items-center bg-deep-gray">
<p className="rainbow-text text-4xl font-extrabold mt-20">
CodeSnap.nvim
</p>
<Panel>
<ControlBar
isCopyButtonDisabled={isCopyButtonDisabled}
onExportClick={handleExportClick}
onCopyClick={handleCopyButtonClick}
readyState={readyState}
/>
<div id="frame" className="rounded-xl overflow-hidden">
<Frame
ref={frameRef}
watermarkFontFamily={config?.watermark_font_family}
watermark={config?.watermark ?? WATER_MARK_PLACEHOLDER}
>
<Editor
codeFontFamily={config?.editor_font_family}
language={event?.code?.language}
macStyleTitleBar={config?.mac_window_bar}
>
{event?.code?.content ?? CODE_EMPTY_PLACEHOLDER}
</Editor>
</Frame>
</div>
</Panel>
<a href="https://github.com/mistricky/codesnap.nvim">
<svg
role="img"
viewBox="0 0 24 24"
className="w-10 h-10 mt-10 fill-white opacity-50"
xmlns="http://www.w3.org/2000/svg"
>
<title>GitHub</title>
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
</svg>
</a>
</div>
);
}
export default App;

View File

@ -1,53 +0,0 @@
import { useMemo } from "react";
import { ReadyState } from "react-use-websocket";
interface ConnectionStatusProps {
readyState: ReadyState;
}
const CONNECTION_STATUS_MAP = {
[ReadyState.CONNECTING]: {
text: "Connecting",
color: "#fdcb6e",
},
[ReadyState.OPEN]: {
text: "Connected",
color: "#00b894",
},
[ReadyState.CLOSING]: {
text: "Closing",
color: "#fab1a0",
},
[ReadyState.CLOSED]: {
text: "Closed",
color: "#636e72",
},
[ReadyState.UNINSTANTIATED]: {
text: "Uninstantiated",
color: "#2d3436",
},
} as const;
const UNKNOWN_STATE = { text: "Unknown", color: "#a29bfe" };
export const ConnectionStatus = ({ readyState }: ConnectionStatusProps) => {
const parsedState = useMemo(
() => CONNECTION_STATUS_MAP[readyState] ?? UNKNOWN_STATE,
[readyState],
);
return (
<div className="flex flex-grow flex-row items-center mr-1 ml-2">
<div
className="flex w-5 h-5 mr-2 justify-center items-center rounded-full"
style={{ backgroundColor: `${parsedState.color}50` }}
>
<div
className="w-3 h-3 rounded-full"
style={{ backgroundColor: parsedState.color }}
></div>
</div>
{parsedState.text}
</div>
);
};

View File

@ -1,65 +0,0 @@
import { ConnectionStatus } from "./connection-status";
import { ReadyState } from "react-use-websocket";
interface ControlBarProps {
isCopyButtonDisabled: boolean;
onCopyClick(): void;
onExportClick(): void;
readyState: ReadyState;
}
export const ControlBar = ({
onCopyClick,
onExportClick,
isCopyButtonDisabled,
readyState,
}: ControlBarProps) => {
return (
<div className="bg-neutral rounded-xl mb-2 p-1 flex flex-row items-center">
<ConnectionStatus readyState={readyState} />
<div className="flex flex-row items-center">
{/*
* <button className="btn mr-1">
<svg
role="img"
className="h-4 w-4 fill-neutral-500"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<title>X</title>
<path d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z" />
</svg>
</button>
*/}
<button className="btn mr-1" onClick={onExportClick}>
Export
<svg
className="fill-neutral-content"
xmlns="http://www.w3.org/2000/svg"
height="24"
viewBox="0 -960 960 960"
width="24"
>
<path d="M480-320 280-520l56-58 104 104v-326h80v326l104-104 56 58-200 200ZM240-160q-33 0-56.5-23.5T160-240v-120h80v120h480v-120h80v120q0 33-23.5 56.5T720-160H240Z" />
</svg>
</button>
<button
onClick={onCopyClick}
id="copy"
className={`btn ${isCopyButtonDisabled && "btn-disabled"}`}
>
Copy
<svg
className="fill-neutral-content"
xmlns="http://www.w3.org/2000/svg"
height="20"
viewBox="0 -960 960 960"
width="20"
>
<path d="M360-240q-33 0-56.5-23.5T280-320v-480q0-33 23.5-56.5T360-880h360q33 0 56.5 23.5T800-800v480q0 33-23.5 56.5T720-240H360Zm0-80h360v-480H360v480ZM200-80q-33 0-56.5-23.5T120-160v-560h80v560h440v80H200Zm160-240v-480 480Z" />
</svg>{" "}
</button>
</div>
</div>
);
};

View File

@ -1 +0,0 @@
export * from "./control-bar";

View File

@ -1,53 +0,0 @@
import { MacStyleTitleBar } from "./mac-style-titlebar";
import hljs from "highlight.js";
export interface EditorProps {
macStyleTitleBar?: boolean;
language?: string;
opacity?: boolean;
codeFontFamily?: string;
children: string;
}
const DEFAULT_CODE_FONT_FAMILY = "CaskaydiaCove Nerd Font";
const LSP_LANGUAGE_NAME_MAP: Record<string, string> = {
typescriptreact: "tsx",
javascriptreact: "jsx",
};
const highlightLanguage = (code: string, language?: string) => {
if (!language) {
return hljs.highlightAuto(code).value;
}
try {
return hljs.highlight(code, {
language: LSP_LANGUAGE_NAME_MAP[language] ?? language,
}).value;
} catch {
return hljs.highlightAuto(code).value;
}
};
export const Editor = ({
children,
language,
codeFontFamily,
opacity = true,
macStyleTitleBar = true,
}: EditorProps) => (
<div
className={`editor-shadow ${opacity ? "bg-one-dark-base/[.93]" : "bg-one-dark-base"} rounded-2xl p-5 pb-7 border-border-color border-[1px]`}
>
{macStyleTitleBar && <MacStyleTitleBar />}
<pre className="mt-4">
<code
className="code"
style={{ fontFamily: codeFontFamily ?? DEFAULT_CODE_FONT_FAMILY }}
dangerouslySetInnerHTML={{
__html: highlightLanguage(children, language),
}}
/>
</pre>
</div>
);

View File

@ -1,26 +0,0 @@
import { forwardRef, PropsWithChildren } from "react";
const DEFAULT_WATERMARK_FONT_FAMILY = "Pacifico";
export interface FrameProps {
watermark?: string;
watermarkFontFamily?: string;
}
export const Frame = forwardRef<HTMLDivElement, PropsWithChildren<FrameProps>>(
({ children, watermark, watermarkFontFamily }, ref) => (
<div ref={ref} className="bg-relay min-w-[800px] p-20">
{children}
{watermark && (
<p
style={{
fontFamily: watermarkFontFamily ?? DEFAULT_WATERMARK_FONT_FAMILY,
}}
className="text-xl opacity-50 font-bold text-white text-center w-full mt-14"
>
{watermark}
</p>
)}
</div>
),
);

View File

@ -1,2 +0,0 @@
export * from "./frame";
export * from "./editor";

View File

@ -1,18 +0,0 @@
interface ButtonProps {
color: string;
}
const Button = ({ color }: ButtonProps) => (
<div
className="w-4 h-4 mr-2 rounded-full"
style={{ backgroundColor: color }}
></div>
);
export const MacStyleTitleBar = () => (
<div className="flex flex-row">
<Button color="#FF5E57" />
<Button color="#FFBC2E" />
<Button color="#2BC841" />
</div>
);

View File

@ -1,3 +0,0 @@
export * from "./control-bar";
export * from "./panel";
export * from "./editor";

View File

@ -1,7 +0,0 @@
import { PropsWithChildren } from "react";
export interface PanelProps {}
export const Panel = ({ children }: PropsWithChildren<PanelProps>) => (
<div className="p-10 br-10">{children}</div>
);

View File

@ -1,3 +0,0 @@
export * from "./use-event";
export * from "./use-storage";
export * from "./use-config";

View File

@ -1,20 +0,0 @@
import { useLocalStorage } from "./use-storage";
export interface Config {
mac_window_bar: boolean;
opacity: boolean;
watermark: string;
auto_load: boolean;
preview_title: string;
watermark_font_family: string;
editor_font_family: string;
highlight_theme: string;
}
const CONFIG_STORAGE_KEY = "CONFIG_STORAGE_KEY";
export const useConfig = (defaultConfig?: Config) => {
const [config] = useLocalStorage(CONFIG_STORAGE_KEY, defaultConfig);
return config;
};

View File

@ -1,34 +0,0 @@
import { useMemo } from "react";
import { Config } from "./use-config";
export enum EventType {
CONFIG_SETUP = "config_setup",
CODE = "code",
COPY = "copy",
}
type CodeMessage = {
content: string;
language: string;
};
type ParsedConfig = {
[EventType.CODE]: CodeMessage;
[EventType.CONFIG_SETUP]: Config;
[EventType.COPY]: undefined;
};
export const useEvent = (
event: MessageEvent<string> | null,
): Partial<ParsedConfig> | undefined =>
useMemo(() => {
if (!event) {
return undefined;
}
const parsedEvent = JSON.parse(event.data);
return {
[parsedEvent.name]: parsedEvent.data,
};
}, [event]);

View File

@ -1,33 +0,0 @@
import { useCallback, useMemo } from "react";
const createStorageHook =
(storage: Storage) =>
<T>(
key: string,
defaultData?: T,
): [NonNullable<T> | null, (value: T) => void] => {
const setValue = useCallback(
(value: T) => {
storage.setItem(key, JSON.stringify(value));
},
[key],
);
const value = useMemo(() => {
const value = storage.getItem(key);
if (defaultData) {
setValue(defaultData);
return defaultData;
}
return value ? JSON.parse(value) : value;
}, [key, defaultData, setValue]);
return [value, setValue];
};
export const useLocalStorage = createStorageHook(localStorage);
export const useSessionStorage = createStorageHook(sessionStorage);

View File

@ -1,19 +0,0 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "./output.css";
import App from "./app";
import reportWebVitals from "./reportWebVitals";
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement,
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

View File

@ -1,106 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
html, body, #root {
height: 100%;
background-image:
linear-gradient(to right, rgba(36, 46, 54, 0.2) 2px, transparent 1px),
linear-gradient(to bottom, rgba(36, 46, 54, 0.2) 2px, transparent 1px);
background-size: 2.5rem 2.5rem;
background-position: center center;
}
@layer components {
.rainbow-text {
background-image: linear-gradient(90deg,hsl(var(--s)) 4%,color-mix(in oklch, hsl(var(--sf)), hsl(163.22deg 80% 43%)));
-webkit-text-fill-color: transparent;
background-clip: text;
}
.editor-shadow {
box-shadow: 0 20px 68px rgba(0, 0, 0, 0.55);
}
.pacifico-regular {
font-family: "Pacifico", cursive;
font-weight: 400;
font-style: normal;
}
.bg-stripe {
background: linear-gradient(to right, #1fa2ff, #12d8fa, #a6ffcb);
}
.bg-flare {
background: linear-gradient(to right, #f12711, #f5af19);
}
.bg-vanusa {
background: linear-gradient(to right, #da4453, #89216b);
}
.bg-sublime-light {
background: linear-gradient(to right, #fc5c7d, #6a82fb);
}
.bg-bighead {
background: linear-gradient(to right, #c94b4b, #4b134f);
}
.bg-velvet-sun {
background: linear-gradient(to right, #e1eec3, #f05053);
}
.bg-argon {
background: linear-gradient(to right, #03001e, #7303c0, #ec38bc, #fdeff9);
}
.bg-celestial {
background: linear-gradient(to right, #c33764, #1d2671);
}
.bg-relay {
background: linear-gradient(to right, #3a1c71, #d76d77, #ffaf7b);
}
.bg-crystal-clear {
background: linear-gradient(to right, #159957, #155799);
}
.bg-ibiza-sunset {
background: linear-gradient(to right, #ee0979, #ff6a00);
}
.bg-fresh-turboscent {
background: linear-gradient(to right, #f1f2b5, #135058);
}
.bg-cheer-up-emo-kid {
background: linear-gradient(to right, #556270, #ff6b6b);
}
.bg-starfall {
background: linear-gradient(to right, #f0c27b, #4b1248);
}
.bg-nelson {
background: linear-gradient(to right, #f2709c, #ff9472);
}
.bg-forever-lost {
background: linear-gradient(to right, #5d4157, #a8caba);
}
.bg-blurry-beach {
background: linear-gradient(to right, #d53369, #cbad6d);
}
.bg-influenza {
background: linear-gradient(to right, #c04848, #480048);
}
.bg-jshine {
background: linear-gradient(to right, #12c2e9, #c471ed, #f64f59);
}
.bg-calm-darya {
background: linear-gradient(to right, #5f2c82, #49a09d);
}
.bg-titanium {
background: linear-gradient(to right, #283048, #859398);
}
.bg-pinky {
background: linear-gradient(to right, #dd5e89, #f7bb97);
}
.bg-purple-paradise {
background: linear-gradient(to right, #1d2b64, #f8cdda);
}
.bg-horizon {
background: linear-gradient(to right, #003973, #e5e5be);
}
.bg-noon-to-dusk {
background: linear-gradient(to right, #ff6e7f, #bfe9ff);
}
}

View File

@ -1 +0,0 @@
/// <reference types="react-scripts" />

View File

@ -1,15 +0,0 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -1,5 +0,0 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

View File

@ -1,4 +0,0 @@
export const getWebsocketHost = () =>
process.env.NODE_ENV === "development"
? "localhost:8080"
: window.location.host;

View File

@ -1 +0,0 @@
export * from "./addr";

View File

@ -1,20 +0,0 @@
import type { Config } from "tailwindcss";
export default {
content: ["./src/**/*.{js,jsx,ts,tsx}"],
plugins: [require("daisyui"), require("@tailwindcss/typography")],
daisyui: {
themes: ["dark"],
},
theme: {
fontFamily: {
caskaydiacove: "CaskaydiaCove Nerd Font",
},
extend: {
colors: {
"one-dark-base": "#282C34",
"border-color": "#545F64",
},
},
},
} satisfies Config;

View File

@ -1,26 +0,0 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}

2550
snap-server/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,18 +0,0 @@
[package]
name = "snap-server"
version = "0.1.0"
edition = "2021"
[dependencies]
actix = "0.13.3"
actix-files = "0.6.5"
actix-web = "4.5.1"
actix-web-actors = "4.3.0"
arboard = "3.3.1"
image = "0.24.8"
image-base64 = "0.1.0"
neovim-lib = "0.6.1"
rand = "0.8.5"
serde = {version = "1.0.196", features = ["derive", "serde_derive", "std"]}
serde_json = "1.0.113"
webbrowser = "0.8.12"

View File

@ -1,31 +0,0 @@
use serde::Serialize;
#[derive(Serialize)]
pub struct Event<T>
where
T: Serialize,
{
name: String,
data: T,
}
impl<T> Event<T>
where
T: Serialize,
{
pub fn new(name: &str, data: T) -> Event<T> {
Event {
name: name.to_string(),
data,
}
}
}
impl<T> Into<String> for Event<T>
where
T: Serialize,
{
fn into(self) -> String {
serde_json::to_string(&self).unwrap()
}
}

View File

@ -1,71 +0,0 @@
pub mod arguments;
pub mod config;
pub mod messages;
pub mod neovim;
use actix::{Actor, Addr, Context};
use arguments::parse_string_first;
pub use config::Config;
pub use messages::Message;
use neovim::Neovim;
use serde_json::Value;
use std::sync::{Arc, Mutex};
use crate::{
event::Event,
server::{ClientMessage, ConfigSetupMessage, Server},
};
pub struct EventHandler {
neovim: Arc<Mutex<Neovim>>,
server: Arc<Addr<Server>>,
port: u16,
}
impl Actor for EventHandler {
type Context = Context<Self>;
fn started(&mut self, _: &mut Self::Context) {
self.start_listen();
}
}
impl EventHandler {
pub fn new(neovim: Arc<Mutex<Neovim>>, server: Arc<Addr<Server>>, port: u16) -> EventHandler {
EventHandler {
neovim,
server,
port,
}
}
pub fn start_listen(&mut self) {
let receiver = self.neovim.lock().unwrap().create_receiver();
for (event_name, values) in receiver {
match Message::from(event_name.clone()) {
Message::OpenPreview => {
let _ = webbrowser::open(format!("http://localhost:{}", self.port).as_str());
}
// The Copy message is not implement yet, but will support in the future
Message::Copy => {}
Message::PreviewCode => self.server.do_send(ClientMessage {
msg: Event::new(
"code",
serde_json::from_str::<Value>(parse_string_first(&values).as_str())
.unwrap(),
)
.into(),
}),
Message::ConfigSetup => self.server.do_send(ConfigSetupMessage {
msg: parse_string_first(&values),
}),
Message::Unknown => self
.neovim
.lock()
.unwrap()
.print(&format!("Unhandled event which name is {}", &event_name)),
};
}
}
}

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