-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.py
More file actions
2964 lines (2564 loc) · 113 KB
/
Copy pathmodule.py
File metadata and controls
2964 lines (2564 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
import random
import time
import re
import threading
from inputs import get_gamepad, UnpluggedError
import subprocess
import hid
import pyperclip
import serial.tools.list_ports
import shutil
import ctypes
import colorsys
from DataFetcher import *
from themeParser import *
import collections
import math
import pygame
import yt_dlp
import soundcard as sc
import numpy as np
import warnings
from PIL import Image, ImageSequence
import cv2
from functools import wraps
import base64
from io import BytesIO
import mss
import pygetwindow as gw
import win32gui
import win32ui
import win32api
import win32con
from spotlight import *
import ctypes
from ctypes import wintypes, windll
from displays import *
import colorsys
from math import cos, sin
if os.name == 'nt':
import msvcrt
else:
import select
class RawTerminal():
"""
a class that sets the state of the terminal to allow for cursor inputs.
you must call it before all cursor inputs,
and is recommended for most input loops.
Args:
None
Returns:
a set of functions that are used by the with statement.
Example:
>>> with RawTerminal():
>>> i = finput(max_length=1, inputs=["mouse"])
to get a mouse input of i. (read finput for details)
Notes:
__init__ is when called
__enter__ is when the while happens (sets terminal to raw mode)
__exit__ is when the while finishes (resets terminal to normal mode)
"""
def __init__(self) -> None:
self.original_stdin_state = None
self.original_stdout_state = None
self.fd_in = sys.stdin.fileno() if sys.stdin.isatty() else None
def __enter__(self) -> self:
if self.fd_in is None:
print("\033[31m[ERROR]\033[0m this terminal has mouse events disabled.\nplease use a diffrent terminal, to be able to use mouse.")
return self
if os.name == 'nt':
import ctypes
from ctypes import wintypes
self.h_stdin = ctypes.windll.kernel32.GetStdHandle(-10)
self.h_stdout = ctypes.windll.kernel32.GetStdHandle(-11)
self.original_stdin_state = wintypes.DWORD()
self.original_stdout_state = wintypes.DWORD()
ctypes.windll.kernel32.GetConsoleMode(self.h_stdin, ctypes.byref(self.original_stdin_state))
ctypes.windll.kernel32.GetConsoleMode(self.h_stdout, ctypes.byref(self.original_stdout_state))
# input config
in_mode = wintypes.DWORD(self.original_stdin_state.value)
in_mode.value &= ~(0x0002 | 0x0004 | 0x0010 | 0x0040)
in_mode.value |= (0x0080 | 0x0200)
ctypes.windll.kernel32.SetConsoleMode(self.h_stdin, in_mode)
# output config
out_mode = wintypes.DWORD(self.original_stdout_state.value)
out_mode.value |= (0x0001 | 0x0004)
ctypes.windll.kernel32.SetConsoleMode(self.h_stdout, out_mode)
else:
import tty, termios
self.old_settings = termios.tcgetattr(self.fd_in)
tty.setraw(self.fd_in)
return self
def __exit__(self, type, value, traceback) -> None:
if os.name == 'nt':
import ctypes
if self.original_stdin_state is not None:
ctypes.windll.kernel32.SetConsoleMode(self.h_stdin, self.original_stdin_state)
if self.original_stdout_state is not None:
ctypes.windll.kernel32.SetConsoleMode(self.h_stdout, self.original_stdout_state)
else:
if self.fd_in is not None:
import termios
termios.tcsetattr(self.fd_in, termios.TCSADRAIN, self.old_settings)
# basic commands
ENABLE_MOUSE = "\x1b[?1000h\x1b[?1006h"
DISABLE_MOUSE = "\x1b[?1000l\x1b[?1006l"
ENABLE_MOUSE_D = "\x1b[?1002h\x1b[?1006h"
DISABLE_MOUSE_D = "\x1b[?1002l\x1b[?1006l"
CLEAR_SCREEN = "\033[H\033[J"
DoubleX = True
Debug = False
BLOCKS = [" ", "▂", "▃", "▄", "▅", "▆", "▇", "█"]
I_BLOCKS = [" ", "▔", "🮂", "🮃", "▀", "🮄", "🮅", "🮆", "█"]
W, H = shutil.get_terminal_size()
theme = ThemeEngine()
bg_color = ""
def ansi_doc_string():
"""\033[44mhello\033[0m world"""
def exampleDoc() -> None:
"""
prints an example docstring template.
Args:
None
Returns:
None
Example:
>>> exampleDoc()
Notes:
it's just in here so i can easily copy paste it, not really intended for actual use.
"""
print(
"""
small description
optional larger description
Args:
parameter:
Description.
parameter:
Description.
Returns:
Description of the return value.
Example:
>>> example()
Notes:
Extra information
"""
)
def clear(n:str="", bg_c:str=bg_color) -> str:
"""
applies bg color and clears screen.
This sets the main bg to that color.
Args:
n:
value after clearing screen,
good for inline expressions.
bg_c:
ANSI color for the terminal background color
Returns:
the value of `n`
Example:
>>> clear(input(), color("green"))
>>> # sets bg to green after input and returns input
Notes:
`bg_c` must be an ANSI background escape sequence. Use
`color()` or another formatting helper to generate one.
"""
print(end=bg_c)
os.system("cls" if os.name == "nt" else "clear")
return n
def leadZero (i:int, d:int) -> str:
"""
takes a num (i) and pads it to a length (d)
with 0's
Args:
i:
the number you want to pad.
d:
the length you want str(i) to be
Returns:
a str of i with the length of d.
Example:
>>> print(leadZero(65, 6))
>>> # output: 000065
Notes:
if d is <= len(str(i)) then it will just return str(i)
"""
return "0" * (d - len(str(i))) + str(i)
def rgb(*args, m:str="f", Max:float=255) -> str:
"""
returns the ANSI escape sequence for a rgb color.
can be for foreground (text color) or background (bg color)
Args:
r:
the amount of red (0 - 255)
g:
the amount of green (0 - 255)
b:
the amount of blue (0 -255)
m:
determines weather the color will be applied to the text or bg.
("f" for text/"b" for back ground)
Max:
determines the range of r,g,b, and can allow for normalized inputs
keep in mind once r,g,b have been formatted to the range (0-255)
they will be rounded to the nearest int.
Returns:
a ANSI escape sequence of the rgb color.
Example:
>>> print(f'{rgb(100, 0, 200, "b")} hello')
>>> # prints hello highlighted with a puprle color
Notes:
values outside the valid range are clamped.
"""
if not args:
return ""
if isinstance(args[0], tuple):
tup = args[0]
r, g, b = tup[0], tup[1], tup[2]
if len(tup) > 3: m = tup[3]
if len(tup) > 4: Max = tup[4]
if len(args) > 1: m = args[1]
if len(args) > 2: Max = args[2]
elif isinstance(args[0], (int, float)):
r, g, b = args[0], args[1], args[2]
if len(args) > 3: m = args[3]
if len(args) > 4: Max = args[4]
else:
return ""
r_calc = int(round(255 * r / Max))
g_calc = int(round(255 * g / Max))
b_calc = int(round(255 * b / Max))
r = max(0, min(255, r_calc))
g = max(0, min(255, g_calc))
b = max(0, min(255, b_calc))
return f"\033[38;2;{r};{g};{b}m" if m.lower()[0] == "f" else f"\033[48;2;{r};{g};{b}m" if m.lower()[0] == "b" else ""
class cursor:
"""
applies affects to the terminal cursor.
Returns:
A printable escape code (for all functions)
Example:
>>> print(cursor().left(1))
>>> #moves the cursor to the left
Notes:
vis and invis may not be supported on some terminals
"""
def invis(self) -> str:
"""
makes the cursor invisible
Example:
>>> cursor().invis()
"""
return ("\033[?25l")
def vis(self) -> str:
"""
makes the cursor visible
Example:
>>> cursor().vis()
"""
return ("\033[?25h")
def up(self, n:int=1) -> str:
"""
moves the cursor up `n` characters
Example:
>>> cursor().up()
"""
return (f"\033[{n}A")
def down(self, n:int=1) -> str:
"""
moves the cursor down `n` characters
Example:
>>> cursor().down()
"""
return (f"\033[{n}B")
def left(self, n:int=1) -> str:
"""
moves the cursor left `n` characters
Example:
>>> cursor().left()
"""
return (f"\033[{n}D")
def right(self, n:int=1) -> str:
"""
moves the cursor right `n` characters
Example:
>>> cursor().right()
"""
return (f"\033[{n}C")
def nextLine(self, n:int=1) -> str:
"""
moves the cursor down `n` characters and to start of Column
Example:
>>> cursor().nextLine()
"""
return (f"\033[{n}E")
def prevLine(self, n:int=1) -> str:
"""
moves the cursor up `n` characters and to start of Column
Example:
>>> cursor().prevLine()
"""
return (f"\033[{n}F")
def column(self, n:int) -> str:
"""
moves the cursor to the `n`th column
Example:
>>> cursor().column()
"""
return (f"\033[{n}G")
def getPos(self) -> str:
"""
gets the cursor pos in the form of \033[r;cR where r is row and c is column
Example:
>>> cursor().getPos()
"""
return ("\033[6n")
def up1(self) -> str:
"""
moves cursor up 1, just use up()
Example:
>>> cursor().up1()
"""
return ("\033 M")
def setPos(self, x:int|str=0,y:int|str=0) -> str:
"""
sets the cursor pos to (x,y)
Example:
>>> cursor().setPos(3,7)
"""
return (f"\033[{y};{x}H")
def savePos(self) -> str:
"""
saves the cursor pos
Example:
>>> cursor().savePos()
"""
return ("\033[s")
def loadPos(self) -> str:
"""
sets the cursor pos to the last saved cursor pos
Example:
>>> cursor().loadPos()
"""
return ("\033[u")
def saveAll(self) -> str:
"""
saves all cursor attributes
Example:
>>> cursor().saveAll()
"""
return ("\0337")
def loadAll(self) -> str:
"""
sets all cursor attributes to the saved attributes
Example:
>>> cursor().loadAll()
"""
return ("\0338")
c = cursor()
chars = {
#custom chars
"BEL" : "\a", # terminal bell
"BS" : "\b", # backspace
"HT" : "\t", # horizontal tab
"LF" : "\n", # linefeed (newline)
"VT" : "\v", # vertical tab
"FF" : "\f", # formfeed (also: new page NP)
"CR" : "\r", # carriage return
"ESC" : "\x1B", # escape charater
"DEL" : "\x7F" # delete charater
}
class screen:
"""
funcs to manipulate lines
Example:
>>> screen().save
Notes:
it's not that useful, but it exists.
"""
class erase:
"""
C is cursor
"""
def CtoEnd(self):
return "\033[0J"
def CtoStart(self):
return "\033[1J"
def all(self):
return "\033[2J"
def saved(self):
return "\033[3J"
def save(self):
return "\033[?47h"
def load(self):
return "\033[?47l"
class line:
class erase:
def CtoEnd(self):
return "\033[0K"
def CtoStart(self):
return "\033[1K"
def all(self):
return "\033[2K"
class graphics:
"""text decorators, add/remove"""
add = {
"none" : "\033[0m",
"bold" : "\033[1m",
"dim" : "\033[2m",
"italic" : "\033[3m",
"underline" : "\033[4m",
"Blink" : "\033[5m",
"Reverse" : "\033[7m",
"hidden" : "\033[8m",
"strikethrough" : "\033[9m"}
remove = {
"bold" : "\033[22m",
"dim" : "\033[22m",
"italic" : "\033[23m",
"underline" : "\033[24m",
"Blink" : "\033[25m",
"Reverse" : "\033[27m",
"hidden" : "\033[28m",
"strikethrough" : "\033[29m"}
def color(name:str="default", m:str="f", bright:bool=False) -> str:
"""
give the name of one of the 9 base colors, and get the ANSI escape code for it.
Args:
name:
the name of the color (must be in list)
["black","red","green","yellow","blue","magenta","cyan","white",None,"default"]
m:
determines weather the color will be applied to the text or bg.
("f" for text/"b" for back ground)
bright:
makes the color brighter if True, is not same as bold.
Returns:
The ANSI escape code for your color.
Example:
>>> print(color("red")+"hello"+color())
>>> prints a red hello
Notes:
default is same as reset for `m` (so will reset foreground color if m == "f" else reset bg color)
"""
names = ["black","red","green","yellow","blue","magenta","cyan","white",None,"default"]
return f"\033[{names.index(name.lower()) + 30 + (10 if m.lower()[0] == 'b' else 0) + (60 if bright else 0)}m" if name else ""
# >>><<<
def color256(id:int, m:str="f") -> str:
"""
returns the ANSI for the `id`th color, out of 256.
Args:
id:
its position / index in the colors
m:
determines weather the color will be applied to the text or bg.
("f" for text/"b" for back ground)
Returns:
A printable ANSI escape sequence
Example:
>>> print(color256(17,"f") + "hi" + color("default"))
Notes:
0-7: standard colors (as in ESC [ 30-37 m)
8-15: high intensity colors (as in ESC [ 90-97 m)
16-231: 6 * 6 * 6 cube (216 colors): 16 + 36 * r + 6 * g + b (0 ≤ r, g, b ≤ 5)
232-255: grayscale from dark to light in 24 steps.
"""
return f"\033[{38 if m.lower()[0] == 'f' else 48};5;{id}m"
def setMode(id:int, m:str="add") -> str:
"""
returns the ANSI for the `id`th mode.
Args:
id:
its position / index in the mode
m:
determines weather the mode will be added or removed.
Returns:
A printable ANSI escape sequence
Example:
>>> # idk how or why ou would use this
Notes:
0 <= id <= 7 or 13 <= id <= 19 , add/remove (a/r)
Changes the screen width or type to the mode specified by id.
0 - 40 x 25 monochrome (text)
1 - 40 x 25 color (text)
2 - 80 x 25 monochrome (text)
3 - 80 x 25 color (text)
4 - 320 x 200 4-color (graphics)
5 - 320 x 200 monochrome (graphics)
6 - 640 x 200 monochrome (graphics)
7 - Enables line wrapping
13 - 320 x 200 color (graphics)
14 - 640 x 200 color (16-color graphics)
15 - 640 x 350 monochrome (2-color graphics)
16 - 640 x 350 color (16-color graphics)
17 - 640 x 480 monochrome (2-color graphics)
18 - 640 x 480 color (16-color graphics)
19 - 320 x 200 color (256-color graphics)
1049 - alternative buffer
"""
return f"\033[{'=' if id != 1049 else '?'}{id}{'h' if m.lower()[0] == 'a' else 'l'}"
def divider(char:str="-") -> None:
"""
prints a line of chars, across the screen.
Args:
char:
char used to print the divider.
Returns:
None
Example:
>>> divider("_")
Notes:
what questions could you possibly have for this function.
"""
terminal_width = shutil.get_terminal_size(fallback=(80, 24)).columns
print(char * terminal_width)
def log(msg:str) -> None:
"""
log's a msg in a log file
Args:
msg:
the msg you want to log
Returns:
None
Example:
>>> log("[error] insert error msg here")
Notes:
use `tail debug.log` to see the logs in you'r terminal
"""
with open("debug.log", "a") as f:
f.write(f"{msg}\n")
f.flush()
lsbd = ["TL","TR","BL","BR","H","V","LT","RT","TT","BT","C"]
symbolList = ["\u250c","\u2510","\u2514","\u2518","\u2500","\u2502","\u251c","\u2524","\u252c","\u2534","\u253c"]
# box drawings
def bd(id:list=lsbd,length:list|int=1,CC:str=color("default")) -> str:
"""
allows for the creation of dynamic boxes
Args:
id:
the corners in order.
length:
the length between the corners in order.
CC:
the ansi color of the lines
Returns:
A printable ANSI escape sequence to print the box
Example:
>>> bd(["TL","TR"],3) # prints `┌───┐`
Notes:
kinda complicated to use, but also super intuitive.
Mess around with it and you'll figure it out.
Also one of the better functions
"""
if len(id[0]) > 1:
if len(id) == 2:
id = [id[0],("H" if id[0][0] == id[1][0] else "V"),id[1]]
elif len(id) > 2 and len(id[1]) > 1:
lengths = length if isinstance(length, list) else [length] * (len(id) - 1)
if len(lengths) < len(id) - 1:
return ""
result = CC + symbolList[lsbd.index(id[0])]
for i in range(len(id) - 1):
if id[i][0] != id[i+1][0]:
result += ((c.down(1) if id[i][0] == "T" else c.up(1)) + c.left(1) + symbolList[lsbd.index("V")]) * lengths[i]
result += (c.down(1) if id[i][0] == "T" else c.up(1)) + c.left(1) + symbolList[lsbd.index(id[i+1])]
else:
result += ((c.left(2) if id[i][1] == "R" else "") + symbolList[lsbd.index("H")]) * lengths[i]
result += (c.left(2) if id[i][1] == "R" else "") + symbolList[lsbd.index(id[i+1])]
return result + "\033[0m"
if id == lsbd:
return ""
elif len(id) == 3:
return CC + symbolList[lsbd.index(id[0])] + symbolList[lsbd.index(id[1])] * length + symbolList[lsbd.index(id[2])] + "\033[0m"
elif id == "V":
return CC + (symbolList[lsbd.index(id)] + c.down(1) + c.left(1)) * length + "\033[0m"
else:
return CC + symbolList[lsbd.index(id)] * length + "\033[0m"
shaded = {"none":" ","light":"\u2591","medium":"\u2592","dark":"\u2593"}
def ps(p:int=0,c:str="") -> str:
"""
returns a shaded box char equal to p (0 = none, 3 = full).
Args:
p:
its shade
c:
ANSI string for its color
Returns:
A printable char
Example:
>>> print(ps(0) + ps(1) + ps(2) + ps(3))
Notes:
use this for simple gradients.
"""
return c + list(shaded.values())[p] + "\033[0m"
def HSVtoRGB(*args) -> tuple[int,int,int]:
"""
converts to hsv to rgb.
Args:
H:
Hue of the color.
S:
Saturation of the color.
V:
Value of the color
Returns:
A rgb tuple
Example:
>>> HSVtoRGB(100, 1,1)
Notes:
only really useful for rainbow stuff.
"""
if len(args) == 3:
H, S, V = args[0], args[1], args[2]
else:
H, S, V = args[0]
r, g, b = colorsys.hsv_to_rgb(H / 360, S, V)
return (int(255 * r), int(255 * g), int(255 * b))
def HEXtoRGB(hex:str) -> tuple[int,int,int]:
"""
converts to hex to rgb.
Args:
hex:
Hex code for the color.
Returns:
A rgb tuple
Example:
>>> HEXtoRGB("#ffffff")
Notes:
nothing to note
"""
return tuple(int(hex.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))
def CMYKtoRGB(*args) -> tuple[int,int,int]:
"""
converts to cmyk to rgb.
Args:
args:
cmyk as a tuple or as separate, args.
Returns:
A rgb tuple
Example:
>>> CMYKtoRGB(1,0,0,0) # -> (0,255,255)
Notes:
is on range 0 to 1
"""
if len(args) == 1:
args = args[0]
C, M, Y, K = args
return (255 * (1-C) * (1-K),255 * (1-M) * (1-K),255 * (1-Y) * (1-K))
def toggle_item(L:list, item) -> list:
"""
converts to hsv to rgb.
Args:
L:
list that has the item
item:
item you want to toggle
Returns:
the new list
Example:
>>> List = [1,2,3,2,3]
>>> toggle_item(List,2) #removes first 2
>>> toggle_item(List,2) #removes first 2
>>> toggle_item(List,2) #appends a 2
Notes:
its a utility function
"""
if item in L:
L.remove(item)
else:
L.append(item)
return L
#useful fancy stuff
def renameTerminal(name:str) -> str:
"""
renames the title of your terminal
Args:
name:
the new name you want your terminal to have
Returns:
An ansi string that you need to print to activate.
Example:
>>> print(renameTerminal("wow so cool"))
Notes:
vscode shows python followed by name
"""
return f"\033]0;{name}\007\033]9;9;\"{name}\"\007"
def clear_graph_area(x:int, y:int, width:int, height:int):
out = []
for row in range(height):
out.append(f"\x1b[{y + row};{x}H" + (" " * width))
return "".join(out)
def cpu_graph(x:int, y:int, width:int, height:int, history:list, color, char:str="█", smooth:bool=True, max:float=100.0):
if len(color[0]) == 1:
color = [color] * (height)
elif len(color) < height:
c = color
color = []
for i in range(height):
i = int(i // (height / len(c)))
color.append(c[i])
if width <= 0 or height <= 0: return ""
samples = list(history)[-width:]
out = []
for col, value in enumerate(samples):
bar_height = int((value / max) * height)
extra = (value / max) * height - bar_height
for row in range(bar_height + 1):
current_row = (y + height - 1) - row
if row < bar_height:
out.append(f"\x1b[{current_row};{x + col}H{color[min(row, len(color) - 1)]}{char}\033[0m")
elif int(7 * extra) != 0:
out.append(f"\x1b[{current_row};{x + col}H{color[min(row, len(color) - 1)]}{BLOCKS[int(7 * extra)]}\033[0m")
return "".join(out)
def dual_graph(x, y, width, height, c_up, c_down, color, char:str="█"):
if len(color[0]) == 1:
color = [color] * (height)
elif len(color) < height:
c = color
color = []
for i in range(height):
i = int(i // (height / len(c)))
color.append(c[i])
if width <= 0 or height <= 0: return ""
out = "color[min(row, len(color) - 1)]"
mid_y = (y + height) / 2
for i in range(max(len(c_up),len(c_down))):
if (y % 2) == 1:
out += f"\x1b[{math.ceil(mid_y)};{x + i}H{char}"
py, my, pe, me = 0, 0, 0, 0
if i < len(c_up) - 1:
py = int(c_up[i])
pe = c_up[i] - py
if i < len(c_down):
my = int(c_down[i])
me = c_down[i] - my
if int(7 * me) != 0:
out += f"\x1b[{math.ceil(mid_y) - j};{x + i}H{I_BLOCKS[int(me * 7)]}"
if my > 0:
for j in range(my):
j += 1
out += f"\x1b[{math.ceil(mid_y) - j};{x + i}H{char}"
if py > 0:
for j in range(py):
j += 1
out += f"\x1b[{math.floor(mid_y) + j};{x + i}H{char}"
if int(7 * pe) != 0:
out += f"\x1b[{math.ceil(mid_y) - j};{x + i}H{BLOCKS[int(pe * 7)]}"
out += "\033[0m"
return out
def iprint(msgs:list, end:str="\n", lend:str=""):
for i in msgs:
print(i,end=(end if i == msgs[-1] else lend))
pygame.init()
pygame.mixer.init()
def playFile(path:str):
if not pygame.mixer.get_init():
pygame.mixer.init()
pygame.mixer.music.load(path)
pygame.mixer.music.play(-1)
while pygame.mixer.music.get_busy():
if control.paused:
if pygame.mixer.music.get_busy():
pygame.mixer.music.pause()
while control.paused:
time.sleep(0.1)
pygame.mixer.music.unpause()
time.sleep(0.1)
#non standard inputs
# fancy stuff
# python leper.
def lerp(a:float|tuple|list, b:float|tuple|list, t:float) -> float|list|tuple:
"""
takes 2 numbers, and returns a number between them at place t
Args:
a:
The starting number.
b:
The end number.
t:
percent as a decimal, of the new numbers place between a and b.
Returns:
Returns a number that is t% between a and b.
Example:
>>> lerp(0,[10,12,16],0.5) # -> [5,6,8]
Notes:
mainly used by gradients, also make sure that if both a and b are lists / tuples,
that they have the same length.
also if either a or b is a list the return value is a list,
if neither is a list and one is a tuple the return value is a tuple.
"""
is_list = isinstance(a,list) or isinstance(b,list)
if isinstance(a,float|int) and isinstance(b,float|int):
return a + (b - a) * t
else:
if isinstance(a, int|float):
return list(a + (b[i] - a) * t for i in range(len(b))) if is_list else tuple(a + (b[i] - a) * t for i in range(len(b)))
elif isinstance(b, int|float):
return list(a[i] + (b - a[i]) * t for i in range(len(a))) if is_list else tuple(a[i] + (b - a[i]) * t for i in range(len(b)))
else:
return list(a[i] + (b[i] - a[i]) * t for i in range(len(min(a,b,key=len)))) if is_list else tuple(a[i] + (b[i] - a[i]) * t for i in range(len(b)))
def gradient2(A:tuple|float|int=(0,0,0), B:tuple|float|int=(255,255,255), L:int = 10) -> list:
"""
makes a 2d gradient between 2 rgb colors.
Args:
A:
start color
B:
end color
L:
length of the returned list
Returns:
returns a list of rgb tuples that are i% between colors
A and B, where i = [0...L] * 100/L
Example:
>>> for i in gradient2(A=(255,0,0), B=(0,0,255), L = 20):
>>> print(rgb(i,"b") + " ", end=color(m="b"))
>>> # prints a cool gradient from red to blue
Notes:
use rgb to convert it into ansi strings.
Also you can make the tuples longer or shorter or make them an int|float, for other cases,
but its kinda complex, if you do try it, make sure A and B have the same length.
"""
if isinstance(A, float|int): A = (A)
if isinstance(B, float|int): B = (B)
grid = [()] * L
grid[0] = A
grid[-1] = B
for i in range(L - 2):
i += 1
grid[i] = lerp(A,B,i/(L-1))
return grid
def gradient4(TL=(255,0,0),TR=(0,0,255),BL=(0,255,0),BR:tuple[int,int,int]=(255,255,0),w:int=10,h:int=10,matrix=False) -> list:
"""
a 4 color gradient maker
Args:
TL:
The top left color as a rgb tuple
TR:
The top right color as a rgb tuple
BL:
The bottom left color as a rgb tuple
BR:
The bottom right color as a rgb tuple
w:
width of the gradient
h:
the height of the gradient
matrix:
returns the list as a 2d array, instead of a 1d list.
As of currently, it is slower than normal.
Returns:
a 1d list of the gradient
if matrix == True:
it returns a 2d list instead.
[[TL...TR]...[BL...BR]]
Example:
>>> g = gradient4()
>>> for i in range(10): # (height of the gradient)
>>> for j in range(10): # (width of the gradient)
>>> print(rgb(g[j + 10 * i],"b") + " ", end=color(m="b")) # (10 is width)
>>> print()
Example2:
>>> # yeah im spoiling you with a second example. (but this is one of my favorite functions)
>>> chars = ".,-~:;=!*#$@"