Browse Source

fix `ansi_fg` and `ansi_bg`

blueloveTH 11 months ago
parent
commit
0c45634eda
3 changed files with 19 additions and 9 deletions
  1. 1 1
      .github/workflows/website.yml
  2. 14 8
      src/modules/vmath.c
  3. 4 0
      tests/80_color32.py

+ 1 - 1
.github/workflows/website.yml

@@ -11,7 +11,7 @@ permissions:
 
 jobs:
   deploy:
-    runs-on: ubuntu-latest
+    runs-on: ubuntu-22.04
     steps:
     - uses: actions/checkout@v4
     ###################################################

+ 14 - 8
src/modules/vmath.c

@@ -1015,22 +1015,28 @@ static bool color32__repr__(int argc, py_Ref argv) {
 }
 
 static bool color32_ansi_fg(int argc, py_Ref argv) {
-    PY_CHECK_ARGC(1);
+    PY_CHECK_ARGC(2);
     c11_color32 color = py_tocolor32(argv);
     c11_color32_premult(&color);
-    char buf[32];
-    int size = snprintf(buf, sizeof(buf), "\033[38;2;%d;%d;%dm", color.r, color.g, color.b);
-    py_newstrv(py_retval(), (c11_sv){buf, size});
+    PY_CHECK_ARG_TYPE(1, tp_str);
+    c11_sv text = py_tosv(&argv[1]);
+    c11_sbuf buf;
+    c11_sbuf__ctor(&buf);
+    pk_sprintf(&buf, "\x1b[38;2;%d;%d;%dm%v\x1b[0m", color.r, color.g, color.b, text);
+    c11_sbuf__py_submit(&buf, py_retval());
     return true;
 }
 
 static bool color32_ansi_bg(int argc, py_Ref argv) {
-    PY_CHECK_ARGC(1);
+    PY_CHECK_ARGC(2);
     c11_color32 color = py_tocolor32(argv);
     c11_color32_premult(&color);
-    char buf[32];
-    int size = snprintf(buf, sizeof(buf), "\033[48;2;%d;%d;%dm", color.r, color.g, color.b);
-    py_newstrv(py_retval(), (c11_sv){buf, size});
+    PY_CHECK_ARG_TYPE(1, tp_str);
+    c11_sv text = py_tosv(&argv[1]);
+    c11_sbuf buf;
+    c11_sbuf__ctor(&buf);
+    pk_sprintf(&buf, "\x1b[48;2;%d;%d;%dm%v\x1b[0m", color.r, color.g, color.b, text);
+    c11_sbuf__py_submit(&buf, py_retval());
     return true;
 }
 

+ 4 - 0
tests/80_color32.py

@@ -23,3 +23,7 @@ assert a != b
 assert repr(b) == 'color32(75, 150, 200, 200)'
 
 # assert color32.alpha_blend(a, b) == color32(86, 173, 225, 162)
+
+c = rgb(100, 200, 255)
+assert c.ansi_fg('xxx') == '\x1b[38;2;100;200;255mxxx\x1b[0m'
+assert c.ansi_bg('xxx') == '\x1b[48;2;100;200;255mxxx\x1b[0m'