-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsupernano.py
1455 lines (1013 loc) · 48.9 KB
/
supernano.py
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 os, sys, shutil, logging, time, threading, argparse
if getattr(sys, 'frozen', False):
__file__ = sys.executable
from datetime import datetime
import urwid
import pyperclip
try:
from libs.helperegex import findpositions, rreplace
from libs.titlecommand import get_console_title, set_console_title
from libs.cmd_filter import shorten_path, validate_folder
from libs.errrorHandler import complex_handle_errors
from libs.system_manajemen import set_low_priority, SafeProcessExecutor
from libs.timeout import timeout_v2, timeout_v1
from libs.filemanager import (
StreamFile,
ModuleInspector,
read_file_in_chunks,
validate_file,
isvalidate_folder,
isvalidate_filename,
create_file_or_folder,
resolve_relative_path_v2,
resolve_relative_path,
all_system_paths,
)
except:
try:
from .helperegex import findpositions, rreplace
from .titlecommand import get_console_title, set_console_title
from .cmd_filter import shorten_path, validate_folder
from .errrorHandler import complex_handle_errors
from .system_manajemen import set_low_priority, SafeProcessExecutor
from .timeout import timeout_v2, timeout_v1
from .filemanager import (
StreamFile,
ModuleInspector,
read_file_in_chunks,
validate_file,
isvalidate_folder,
isvalidate_filename,
create_file_or_folder,
resolve_relative_path_v2,
resolve_relative_path,
all_system_paths,
)
except:
from helperegex import findpositions, rreplace
from titlecommand import get_console_title, set_console_title
from cmd_filter import shorten_path, validate_folder
from errrorHandler import complex_handle_errors
from system_manajemen import set_low_priority, SafeProcessExecutor
from timeout import timeout_v2, timeout_v1
from filemanager import (
StreamFile,
ModuleInspector,
read_file_in_chunks,
validate_file,
isvalidate_folder,
isvalidate_filename,
create_file_or_folder,
resolve_relative_path_v2,
resolve_relative_path,
all_system_paths,
)
set_low_priority(os.getpid())
#########mendapatkan process terbaik tanpa membebani ram dan cpu
thisfolder, _x = all_system_paths
__version__ = "2.2.1"
fileloogiing = os.path.join(thisfolder, "cache", "file_browser.log").replace("\\", "/")
if not os.path.isdir(os.path.join(thisfolder, "cache")):
os.mkdir(os.path.join(thisfolder, "cache"))
if not os.path.isfile(fileloogiing):
open(fileloogiing, "a+")
elif os.path.getsize(fileloogiing) > 0:
with open(fileloogiing, "wb+") as f:
f.truncate(0)
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(
filename=fileloogiing,
filemode="w",
encoding=sys.getfilesystemencoding(),
format="%(asctime)s, %(msecs)d %(name)s %(levelname)s [ %(filename)s-%(module)s-%(lineno)d ] : %(message)s",
datefmt="%H:%M:%S",
level=logging.ERROR,
)
logging.getLogger("urwid").disabled = True
logger = logging.getLogger("urwid")
for handler in logger.handlers[:]:
logger.removeHandler(handler)
def setTitle(title: str):
"""
Fungsi setTitle bertugas untuk mengatur judul konsol (console title) berdasarkan parameter title yang diberikan.\n
Jika inputan title memiliki panjang lebih dari 30 karakter maka potong karakternya
"""
process = title
Getitles = get_console_title()
if os.path.isdir(process) or os.path.isfile(process):
length = int(process.__len__() / 2)
if length < 28:
x = process.__len__()
nexts = int(50 - x) - (x / 2)
if nexts < 28:
length = int((28 - nexts) + nexts)
else:
length = nexts
elif length > 50:
length = 28
process = shorten_path(process, length)
if Getitles.startswith("Win-SuperNano"):
output = str("Win-SuperNano {titles}".format(titles=process))
else:
output = title
set_console_title(output)
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def parse_args():
"""
Fungsi parse_args bertugas untuk mendapatkan\menangkap argument konsol (console title) yang diberikan oleh user.\n
"""
parser = argparse.ArgumentParser(
description="An extension on nano for editing directories in CLI."
)
parser.add_argument(
"path",
default=os.path.split(thisfolder)[0],
nargs="?",
type=str,
help="Target file or directory to edit.",
)
args = parser.parse_args()
path = resolve_relative_path(args.path, "") or "."
if os.path.exists(path):
if validate_folder(path=path):
pass
else:
logging.error("ERROR - {path} path cannot access".format(path=path))
exit()
else:
logging.error("ERROR - {path} path does not exist".format(path=path))
exit()
return resolve_relative_path_v2(path).replace("\\", "/")
class PlainButton(urwid.Button):
"""
Class PlainButton bertugas untuk mengkoustomisasi button dan menghilangkan karakter < dan >.\n
"""
button_left = urwid.Text("")
button_right = urwid.Text("")
class FileButton(PlainButton):
def __init__(self, label, functions, file_path):
super().__init__(label)
self.file_path = file_path
self.functions = functions
urwid.connect_signal(
self, "click", self.on_single_click, user_args=[self.file_path]
)
def on_single_click(self, button, user_data=None):
time.sleep(0.02)
if (
not self.get_label()
.lower()
.endswith(
(
".bin",
".exe",
".dat",
".dll",
".flt",
".xbin",
".x",
".bmp",
".rpm",
".xz",
".iso",
".zst",
".appimage",
".apk",
".msi",
".apx",
".app",
".apps",
".cmd",
".run",
".deb",
".dmg",
".ipa",
)
)
):
self.functions(button, user_data) # Buka file jika single-click
else:
self.functions(button, None)
class NumberedEdit(urwid.WidgetWrap):
def __init__(self, edit_text="", multiline=True):
self.edit = urwid.Edit(edit_text, multiline=multiline)
self.line_numbers = urwid.Text("")
self.update_line_numbers()
columns = urwid.Columns([("fixed", 4, self.line_numbers), self.edit])
super().__init__(urwid.AttrMap(columns, None, focus_map="reversed"))
# Connect the 'change' signal from the internal Edit widget
urwid.connect_signal(self.edit, "change", self._on_change)
def update_line_numbers(self):
text = self.edit.get_edit_text()
lines = text.splitlines()
line_numbers = "\n".join(["{:>3}".format(i + 1) for i in range(len(lines))])
self.line_numbers.set_text(line_numbers)
def keypress(self, size, key):
key = super().keypress(size, key)
self.update_line_numbers()
return key
def mouse_event(self, size, event, button, col, row, focus):
handled = super().mouse_event(size, event, button, col, row, focus)
if handled:
self.update_line_numbers()
return handled
def _on_change(self, edit, new_text):
self.update_line_numbers()
urwid.emit_signal(self, "change", self, new_text)
def set_edit_text(self, text):
"""Set the text of the edit widget and update line numbers."""
self.edit.set_edit_text(text)
self.update_line_numbers()
def get_edit_text(self):
"""Get the text from the edit widget."""
return self.edit.get_edit_text()
class SaveableEdit(urwid.Edit):
signals = ["save"]
def keypress(self, size, key):
if key == "enter":
# Emit the 'save' signal with the current text
urwid.emit_signal(self, "save", self.get_edit_text())
return True
return super().keypress(size, key)
urwid.register_signal(NumberedEdit, ["change"])
class SuperNano:
"""
Kelas SuperNano yang sedang Anda kembangkan adalah text editor berbasis console yang menggunakan Python 3.6 ke atas dengan dukungan urwid[curses].
Pembuat: Ramsyan Tungga Kiansantang (ID) | Github: LcfherShell
Tanggal dibuat: 21 Agustus 2024
Jika ada bug silahkan kunjungi git yang telah tertera diatas
"""
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def __init__(self, start_path="."):
"Mengatur path awal, judul aplikasi, widget, dan layout utama. Juga mengatur alarm untuk memuat menu utama dan memulai loop aplikasi."
self.current_path = start_path
self.current_pathx = self.current_path
self.current_file_name = None # Track current file name
self.undo_stack, self.redo_stack = [[], []] # Stack for undo # Stack for redo
self.overlay_POPUP = None # Overlay untuk popup
self.module_package_Python = ModuleInspector() # memuat module python
self.module_package_PythonC = self.module_package_Python.curents
# Set title
setTitle("Win-SuperNano v{version}".format(version=__version__))
# Create widgets
"""
1.loading menu
2. main menu: search, list file or folder, and inspect module python
"""
######Create widgets modulepython menu
def create_button(module_name):
button = PlainButton(module_name)
urwid.connect_signal(button, "click", self.inspect_module, module_name)
return urwid.AttrMap(button, None, focus_map="reversed")
self.listmodules_from_package_Python = urwid.SimpleFocusListWalker(
[
create_button(module)
for module in self.module_package_Python.get_python_module(sys.path)
]
)
# Footer text and ListBox for scrolling
self.Text_Deinspect_modules_from_package_Python = urwid.Text(
"Select a module to inspect."
)
MenuText_Inspect_modules_from_package_Python = urwid.ListBox(
urwid.SimpleFocusListWalker(
[self.Text_Deinspect_modules_from_package_Python]
)
)
Box_Deinspect_modules_from_package_Python = urwid.BoxAdapter(
MenuText_Inspect_modules_from_package_Python, 14
) # Set max height for the footer
# Use a Frame to wrap the main content and footer
self.Inspect_modules_from_package_Python = urwid.Frame(
body=urwid.LineBox(
urwid.ListBox(self.listmodules_from_package_Python),
title="Python Modules",
),
footer=Box_Deinspect_modules_from_package_Python,
)
###Create widgets loading menu
self.title_loading_widget = urwid.Text(
"Win-SuperNano v{version} CopyRight: LcfherShell@{year}\n".format(
version=__version__, year=datetime.now().year
),
align="center",
)
self.loading_widget = urwid.Text("Loading, please wait...", align="center")
self.main_layout = urwid.Filler(
urwid.Pile([self.title_loading_widget, self.loading_widget]),
valign="middle",
)
# Create main menu
self.main_menu_columns = urwid.Columns([])
self.main_menu_pile = urwid.Pile([self.main_menu_columns])
self.status_msg_footer_text = urwid.Text(
"Press ctrl + q to exit, Arrow keys to navigate"
)
self.main_footer_text = urwid.Text(
"Ctrl+S : Save file Ctrl+D : Delete File Ctrl+Z : Undo Edit Ctrl+Y : Redo Edit Ctrl+E : Redirect input Ctrl+N : Rename/Create Ctrl+R : Refresh UI ESC: Quit "
)
# Event loop
self.loop = urwid.MainLoop(self.main_layout, unhandled_input=self.handle_input)
self.loading_alarm = self.loop.set_alarm_in(
round(timeout_v1() * timeout_v2(), 1) + 1,
lambda loop, user_data: self.load_main_menu(),
)
self.system_alarm = None
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def load_main_menu(self):
"Menyiapkan dan menampilkan menu utama setelah periode loading, dan menghapus alarm loading."
# self.loading_widget.set_text("Press key R")
set_low_priority(os.getpid())
self.loop.remove_alarm(self.loading_alarm) # Hentikan alarm
self.loading_alarm = None
self.switch_to_secondary_layout()
def switch_to_secondary_layout(self):
"Mengubah layout aplikasi ke menu utama yang telah disiapkan."
self.setup_main_menu()
if self.loading_alarm != None:
self.loop.remove_alarm(
self.loading_alarm
) # Hentikan alarm loading jika masih ada
self.loading_alarm = None
self.loop.widget = self.main_layout
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def setup_main_menu(self):
"Menyiapkan dan mengatur widget untuk menu utama, termasuk daftar file, editor teks, dan tombol-tombol fungsional. Mengatur layout untuk tampilan aplikasi."
# Define widgets
self.file_list = urwid.SimpleFocusListWalker(self.get_file_list())
self.file_list_box = urwid.ListBox(self.file_list)
self.text_editor = NumberedEdit(multiline=True)
self.current_focus = 0 # 0 for textbox1, 1 for textbox2
# Wrap text_editor with BoxAdapter for scrollable content
self.text_editor_scrollable = urwid.LineBox(
urwid.Filler(self.text_editor, valign="top"), title="TextBox"
)
# Define menu widgets
self.quit_button = PlainButton("Quit", align="center")
urwid.connect_signal(self.quit_button, "click", self.quit_app)
self.search_edit = urwid.Edit(
"Search, Rename or Create: ", multiline=False, align="left"
)
search_limited = urwid.BoxAdapter(
urwid.Filler(self.search_edit, valign="top"), height=1
)
self.search_button = PlainButton("Execute", align="center")
urwid.connect_signal(self.search_button, "click", self.in_search_)
padded_button = urwid.Padding(
self.search_button, align="center", width=("relative", 50)
) # Tombol berada di tengah dengan lebar 50% dari total layar
padded_button = urwid.AttrMap(
padded_button, None, focus_map="reversed"
) # Mengatur warna saat tombol difokuskan
urwid.connect_signal(
self.text_editor.base_widget, "change", self.set_focus_on_click, 0
)
urwid.connect_signal(
self.search_edit.base_widget, "change", self.set_focus_on_click, 1
)
# Menu layout
self.main_menu_columns = urwid.Columns(
[
(
"weight",
3,
urwid.AttrMap(search_limited, None, focus_map="reversed"),
),
(
"weight",
1,
urwid.AttrMap(padded_button, None, focus_map="reversed"),
),
(
"weight",
2,
urwid.AttrMap(self.quit_button, None, focus_map="reversed"),
),
# (
# "weight",
# 4,
# urwid.AttrMap(urwid.Pile(menu_items), None, focus_map="reversed"),
# ),
]
)
self.main_menu_pile = urwid.Pile([self.main_menu_columns])
# Layout
self.main_layout = urwid.Frame(
header=self.main_menu_pile,
body=urwid.Columns(
[
(
"weight",
1,
urwid.LineBox(self.file_list_box, title="Directory Files"),
),
(
"weight",
1,
urwid.AttrMap(
self.Inspect_modules_from_package_Python,
None,
focus_map="reversed",
),
),
(
"weight",
3,
self.text_editor_scrollable,
),
]
),
footer=urwid.Pile([self.status_msg_footer_text, self.main_footer_text]),
)
self.loop.set_alarm_in(timeout_v2(), self.update_uiV2)
self.system_alarm = self.loop.set_alarm_in(
timeout_v2() + 1,
lambda loop, user_data: self.system_usage(),
)
try:
urwid.TrustedLoop(self.loop).set_widget(self.main_layout)
except:
self.loop.widget = self.main_layout
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def create_modules_menus(self, listmodulename: list):
def create_button(module_name):
button = PlainButton(module_name)
urwid.connect_signal(button, "click", self.inspect_module, module_name)
return urwid.AttrMap(button, None, focus_map="reversed")
return [create_button(module) for module in listmodulename]
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def inspect_module(self, button, module_name):
result = self.module_package_Python.inspect_module(module_name)
if result:
if "module" in result.keys():
keys = result.keys()
if "classes" in keys or "functions" in keys or "variables" in keys:
result_text = "Module: {modulen}\n\nGlobal Variables:\n".format(modulen = result['module'])
result_text += ", ".join(result["variables"])
if result["classes"]:
result_text += "\n\nClass:\n"
for cls in result["classes"]:
if cls["name"]:
result_text += "Class: {classname}\n".format(classname=cls['name'])
result_text += " Variables:\n"
result_text += (
" " + "\n > ".join(cls["variables"]) + "\n\n"
)
if cls["functions"]:
result_text += " Function:\n"
for func in cls["functions"]:
result_text += (
" > {funcname}{parms}\n\n".format(funcname=func['name'], parms=func['params'])
)
for funcs in result["functions"]:
if funcs["name"]:
result_text += "\nFunction: {funcname}\n".format(funcname=funcs['name'])
result_text += " > {funcname}{parms}\n\n".format(funcname=funcs['name'], parms=funcs['params'])
self.Text_Deinspect_modules_from_package_Python.set_text(
result_text
)
else:
self.Text_Deinspect_modules_from_package_Python.set_text(
"Error inspecting module."
)
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def setup_popup(self, options, title, descrip: str = ""):
"Menyiapkan konten dan layout untuk menu popup dengan judul, deskripsi, dan opsi yang diberikan."
# Konten popup
menu_items = []
if descrip:
menu_items = [urwid.Text(descrip, align="center"), urwid.Divider("-")]
# Tambahkan opsi ke dalam menu popup
for option in options:
menu_items.append(option)
# Tambahkan tombol untuk menutup popup
menu_items.append(PlainButton("Close", on_press=self.close_popup))
# Buat listbox dari opsi yang sudah ada
popup_content = urwid.ListBox(urwid.SimpleFocusListWalker(menu_items))
# Tambahkan border dengan judul
self.popup = urwid.LineBox(popup_content, title=title)
def on_option_selected(self, button):
"Menangani pilihan opsi dari popup dengan menutup popup dan mengembalikan label opsi yang dipilih."
urwid.emit_signal(button, "click")
getbutton = button.get_label()
self.close_popup(None)
return getbutton
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def show_popup(self, title: str, descrip: str, menus: list):
"Menampilkan popup menu dengan judul, deskripsi, dan daftar opsi yang diberikan."
# Siapkan popup dengan judul, descrip, dan opsi
self.setup_popup(title=title, descrip=descrip, options=menus)
# Tentukan ukuran dan posisi popup
popup_width = 35
popup_height = 25
self.overlay_POPUP = urwid.Overlay(
self.popup,
self.main_layout,
"center",
("relative", popup_width),
"middle",
("relative", popup_height),
)
self.loop.widget = self.overlay_POPUP
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def close_popup(self, button):
"Menutup popup menu dan mengembalikan tampilan ke layout utama."
self.overlay_POPUP = None
self.loop.widget = self.main_layout
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def get_file_list(self):
"Mengambil daftar file dan direktori di path saat ini, termasuk opsi untuk naik satu level di direktori jika bukan di direktori root."
files = []
if self.current_path != ".": # Cek apakah bukan di direktori root
button = PlainButton("...")
urwid.connect_signal(button, "click", self.go_up_directory)
files.append(urwid.AttrMap(button, None, focus_map="reversed"))
for f in os.listdir("{msg}".format(msg=self.current_path)):
if os.path.isdir(resolve_relative_path(self.current_path, f)):
f = f + "/"
button = PlainButton(f)
urwid.connect_signal(button, "click", self.open_file, f)
files.append(urwid.AttrMap(button, None, focus_map="reversed"))
return files
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def renameORcreatedPOP(self):
"Menyiapkan konten dan layout untuk menu popup rename dan created"
select = urwid.Edit("Search or Create", "")
replaces = SaveableEdit("Replace ", "")
def on_save(button, *args):
slect = select.get_edit_text().strip()
if slect.__len__() <= 0:
return
getselect = [f for f in os.listdir("{msg}".format(msg=self.current_path)) if slect in f]
if getselect and replaces.get_edit_text():
_y = replaces.get_edit_text().strip()
if isvalidate_folder(_y):
try:
selecfolder = resolve_relative_path(
self.current_path, getselect[0]
)
selecrepcae = resolve_relative_path(self.current_path, _y)
if os.path.isdir(selecfolder) or os.path.isfile(selecfolder):
os.rename(selecfolder, selecrepcae)
ms = str("Success renaming item")
except:
ms = str("Failed renaming item: {msg}".format(msg=getselect[0]))
else:
ms = str("Item to rename not found")
else:
x, _y = os.path.split(slect)
if os.path.isdir(x):
ms = str("Item to rename not found")
else:
if isvalidate_folder(_y) or _y.find(".") == -1:
ms = create_file_or_folder(
resolve_relative_path(self.current_path, slect)
)
elif isvalidate_filename(_y) or _y.find(".") > 0:
ms = create_file_or_folder(
resolve_relative_path(self.current_path, slect)
)
else:
ms = str("Item to rename not found")
self.switch_to_secondary_layout()
self.status_msg_footer_text.set_text(ms)
urwid.connect_signal(replaces, "save", on_save)
return [select, replaces]
def handle_input(self, key):
"Menangani input keyboard dari pengguna untuk berbagai tindakan seperti keluar, menyimpan, menghapus, undo, redo, copy, paste, dan refresh UI."
if key in ("ctrl q", "ctrl Q", "esc"):
self.show_popup(
menus=[PlainButton("OK", on_press=lambda _x: self.quit_app())],
title="Confirm Quit",
descrip="Are you sure you Quit",
)
elif key in ("ctrl n", "ctrl N"):
self.show_popup(
menus=[*self.renameORcreatedPOP()],
title="Rename or Create",
descrip="AChoose to rename an existing item or create a new one in the current directory. Press ENter to done",
)
elif key in ("ctrl s", "ctrl S"):
# self.save_file()
self.show_popup(
menus=[
PlainButton(
"OK",
on_press=lambda _x: self.close_popup(None)
if self.save_file()
else None,
)
],
title="Save File",
descrip="Are you sure you want to save the file changes",
)
elif key in ("ctrl d", "ctrl D"):
self.show_popup(
menus=[
PlainButton(
"OK",
on_press=lambda _x: self.close_popup(None)
if self.delete_file()
else None,
)
],
title="Delete File",
descrip="Are you sure you want to delete the file",
)
elif key in ("ctrl z", "ctrl Z"):
self.undo_edit()
elif key in ("ctrl y", "ctrl Y"):
self.redo_edit()
elif key in ("ctrl c", "ctrl C"):
self.copy_text_to_clipboard()
elif key in ("ctrl v", "ctrl V"):
self.paste_text_from_clipboard()
elif key in ("ctrl r", "ctrl R"):
self.switch_to_secondary_layout()
elif key in ("f1", "ctrl e", "ctrl E"):
self.current_focus = 1 if self.current_focus == 0 else 0
self.status_msg_footer_text.set_text("focus {msg}".format(msg=self.current_focus))
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def get_current_edit(self):
"Mengembalikan widget edit yang sedang difokuskan (text editor atau search edit)."
if self.current_focus == 0:
return self.text_editor.edit.base_widget
elif self.current_focus == 1:
return self.search_edit.base_widget
return None
def set_focus_on_click(self, widget, new_edit_text, index):
"Mengatur fokus pada widget edit berdasarkan klik dan indeks."
self.current_focus = index
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def copy_text_to_clipboard(self):
"Menyalin teks dari widget edit yang sedang aktif ke clipboard."
current_edit = self.get_current_edit()
if current_edit:
if hasattr(current_edit, "edit_pos") and hasattr(
current_edit, "get_edit_text"
):
self.status_msg_footer_text.set_text("Text copied to clipboard.")
cursor_position = current_edit.edit_pos
pyperclip.copy(
current_edit.get_edit_text()[cursor_position:]
or current_edit.get_edit_text()
)
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def paste_text_from_clipboard(self):
"Menempelkan teks dari clipboard ke widget edit yang sedang aktif."
pasted_text = pyperclip.paste() # Mengambil teks dari clipboard
current_edit = self.get_current_edit()
if current_edit:
if hasattr(current_edit, "edit_pos") and hasattr(
current_edit, "get_edit_text"
):
current_text = (
current_edit.get_edit_text()
) # Mendapatkan teks saat ini di widget Edit
cursor_position = (
current_edit.edit_pos
) # Mendapatkan posisi kursor saat ini
# Membagi teks berdasarkan posisi kursor
text_before_cursor = current_text[:cursor_position]
text_after_cursor = current_text[cursor_position:]
# Gabungkan teks sebelum kursor, teks yang ditempelkan, dan teks setelah kursor
new_text = text_before_cursor + pasted_text + text_after_cursor
# Set teks baru dan sesuaikan posisi kursor
current_edit.set_edit_text(new_text)
current_edit.set_edit_pos(cursor_position + len(pasted_text))
self.status_msg_footer_text.set_text("Text paste from clipboard.")
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def go_up_directory(self, button):
"Naik satu level ke direktori atas dan memperbarui daftar file."
self.current_path = os.path.dirname(self.current_path)
self.file_list[:] = self.get_file_list()
@complex_handle_errors(loggering=logging, nomessagesNormal=False)
def open_file(self, button, file_name):
"Membuka file yang dipilih, membaca isinya, dan menampilkannya di text editor. Jika itu adalah direktori, berpindah ke direktori tersebut."
if file_name:
file_path = resolve_relative_path(self.current_path, file_name)
_c, ext = os.path.splitext(file_path)
if os.path.isdir(file_path):
if validate_folder(file_path):
try:
sys.path.remove(self.current_path)
except:
pass