-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui_components.py
More file actions
2147 lines (1804 loc) · 76.7 KB
/
ui_components.py
File metadata and controls
2147 lines (1804 loc) · 76.7 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
#!/usr/bin/env python3
import os
import requests
import markdown
import re
import base64
from dotenv import load_dotenv, set_key, find_dotenv
from PyQt5.QtWidgets import (
QWidget, QDialog, QVBoxLayout, QHBoxLayout, QFormLayout, QDialogButtonBox,
QLabel, QPushButton, QListWidget, QListWidgetItem, QCheckBox, QProgressBar,
QTextEdit, QLineEdit, QFileDialog, QGroupBox, QSplitter, QComboBox, QTreeWidget,
QTreeWidgetItem, QMessageBox, QInputDialog, QStackedWidget, QButtonGroup,
QScrollArea, QPlainTextEdit, QStyle
)
from PyQt5.QtCore import Qt, pyqtSignal, QRect, QPoint, QMimeData, QUrl
from PyQt5.QtGui import QPainter, QBrush, QPixmap, QColor, QIcon, QDragEnterEvent, QDropEvent
from PyQt5.QtWebEngineWidgets import QWebEngineView
from github_api import GitHubAPI
# Modern dark style with improved visual hierarchy
DARK_STYLE = """
QMainWindow, QDialog, QWidget {
background-color: #1e1e2e;
font-family: 'Segoe UI', 'SF Pro Display', system-ui, sans-serif;
color: #e0e0e0;
}
QLabel {
font-size: 11pt;
color: #ffffff;
}
QLineEdit, QTextEdit, QPlainTextEdit {
background: #2a2a3a;
border: 1px solid #3f3f5f;
border-radius: 6px;
padding: 8px;
color: #ffffff;
selection-background-color: #505080;
}
QPushButton {
background-color: #565695;
padding: 9px 14px;
border-radius: 6px;
color: #ffffff;
font-weight: 500;
}
QPushButton:hover {
background-color: #6868a6;
}
QPushButton:pressed {
background-color: #4a4a8c;
}
QPushButton:disabled {
background-color: #3a3a4a;
color: #888888;
}
QPushButton:checked {
background-color: #6c6cb0;
font-weight: bold;
border-bottom: 2px solid #a0a0ff;
}
QCheckBox {
spacing: 8px;
color: #e0e0e0;
}
QCheckBox::indicator {
width: 18px;
height: 18px;
border-radius: 4px;
border: 1px solid #5f5f8f;
}
QCheckBox::indicator:checked {
background-color: #6c6cb0;
border: 1px solid #6c6cb0;
image: url(check.png);
}
QProgressBar {
background-color: #2a2a3a;
border-radius: 4px;
text-align: center;
color: #ffffff;
height: 10px;
}
QProgressBar::chunk {
background-color: #7c7cff;
border-radius: 4px;
}
QMenu {
background: #2a2a3a;
border: 1px solid #3f3f5f;
border-radius: 6px;
}
QMenu::item:selected {
background: #3f3f5f;
}
QTabWidget::pane {
border: 1px solid #3f3f5f;
border-radius: 6px;
}
QTabBar::tab {
background: #2a2a3a;
padding: 10px 16px;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
}
QTabBar::tab:selected {
background: #565695;
color: #ffffff;
}
QComboBox {
background-color: #2a2a3a;
border: 1px solid #3f3f5f;
border-radius: 6px;
padding: 8px;
color: #ffffff;
min-width: 6em;
}
QComboBox:hover {
border: 1px solid #5f5f8f;
}
QComboBox::drop-down {
subcontrol-origin: padding;
subcontrol-position: top right;
width: 20px;
border-left: 1px solid #3f3f5f;
}
QTreeWidget, QListWidget {
background-color: #2a2a3a;
border: 1px solid #3f3f5f;
border-radius: 6px;
color: #ffffff;
}
QTreeWidget::item, QListWidget::item {
height: 28px;
padding: 4px;
}
QTreeWidget::item:selected, QListWidget::item:selected {
background-color: #565695;
border-radius: 4px;
}
QScrollBar:vertical {
border: none;
background: #2a2a3a;
width: 12px;
margin: 0px;
border-radius: 6px;
}
QScrollBar::handle:vertical {
background: #565695;
min-height: 20px;
border-radius: 6px;
}
QScrollBar::handle:vertical:hover {
background: #6868a6;
}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical,
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
background: none;
height: 0px;
}
QScrollBar:horizontal {
border: none;
background: #2a2a3a;
height: 12px;
margin: 0px;
border-radius: 6px;
}
QScrollBar::handle:horizontal {
background: #565695;
min-width: 20px;
border-radius: 6px;
}
QScrollBar::handle:horizontal:hover {
background: #6868a6;
}
QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal,
QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {
background: none;
width: 0px;
}
QWebEngineView {
background-color: #2a2a3a;
}
QGroupBox {
border: 1px solid #3f3f5f;
border-radius: 6px;
margin-top: 1.5em;
padding-top: 1em;
font-weight: bold;
}
QGroupBox::title {
subcontrol-origin: margin;
subcontrol-position: top center;
padding: 0 5px;
}
QSplitter::handle {
background-color: #3f3f5f;
}
QSplitter::handle:horizontal {
width: 2px;
}
QSplitter::handle:vertical {
height: 2px;
}
QStatusBar {
background-color: #2a2a3a;
color: #c0c0c0;
border-top: 1px solid #3f3f5f;
}
/* Custom toolbar styling */
QToolBar {
background-color: #2a2a3a;
border: none;
spacing: 6px;
padding: 4px;
}
QToolButton {
background-color: transparent;
border-radius: 4px;
padding: 4px;
}
QToolButton:hover {
background-color: #3f3f5f;
}
QToolButton:pressed {
background-color: #5f5f8f;
}
"""
class AvatarLabel(QLabel):
"""Custom label widget for displaying rounded user avatars."""
def __init__(self, parent=None):
super().__init__(parent)
self.setMinimumSize(40, 40)
self.setAlignment(Qt.AlignCenter)
self.setStyleSheet("font-size: 24pt; color: #a0a0ff; background: #3f3f5f; border-radius: 20px;")
# Set default avatar
self.setText("👤")
def set_avatar(self, url):
"""Load and display an avatar from a URL with rounded corners."""
if not url:
self.setText("👤")
return
try:
px = QPixmap()
px.loadFromData(requests.get(url).content)
round_px = QPixmap(px.size())
round_px.fill(Qt.transparent)
painter = QPainter(round_px)
painter.setRenderHint(QPainter.Antialiasing)
painter.setBrush(QBrush(px))
painter.setPen(Qt.NoPen)
painter.drawEllipse(0, 0, px.width(), px.height())
painter.end()
scaled = round_px.scaled(self.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.setPixmap(scaled)
except:
# Set a default placeholder if avatar can't be loaded
self.setText("👤")
self.setAlignment(Qt.AlignCenter)
self.setStyleSheet("font-size: 24pt; color: #a0a0ff; background: #3f3f5f; border-radius: 20px;")
class AccountSelector(QComboBox):
"""Custom combobox for selecting GitHub accounts with built-in token management."""
user_changed = pyqtSignal(str, dict) # Signal emitted when user is changed (token, user_data)
tokens_managed = pyqtSignal() # Signal emitted when tokens are managed
def __init__(self, parent=None):
super().__init__(parent)
self.setStyleSheet("""
QComboBox {
background-color: #2a2a3a;
border: 1px solid #3f3f5f;
border-radius: 6px;
padding: 6px;
color: white;
}
""")
self.all_tokens = {}
self.load_tokens()
# Connect signal
self.currentIndexChanged.connect(self.on_index_changed)
def load_tokens(self):
"""Load tokens from environment."""
self.clear()
self.all_tokens = {}
# Load .env file
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv(usecwd=True))
# Get all tokens
for k, v in os.environ.items():
if k.startswith("GITHUB_TOKEN_"):
name = k[13:] # Remove "GITHUB_TOKEN_" prefix
self.all_tokens[name] = v
# Validate token and get user data
api = GitHubAPI(v)
ok, user_data = api.validate_token()
if ok and isinstance(user_data, dict):
display_name = f"{name} ({user_data.get('login', 'Unknown')})"
# Store user data with the token
self.addItem(display_name)
self.setItemData(self.count()-1, (v, user_data), Qt.UserRole)
def on_index_changed(self, index):
"""Handle change of selected account."""
if index >= 0:
data = self.itemData(index, Qt.UserRole)
if data:
token, user_data = data
self.user_changed.emit(token, user_data)
class ReadmeCreatorTab(QWidget):
"""Tab for creating and editing GitHub README.md files."""
def __init__(self, api, user_data):
super().__init__()
self.api = api
self.user_data = user_data
layout = QVBoxLayout(self)
# Top control row - Repository selector, save button, preview toggle
top_controls = QHBoxLayout()
self.repo_selector = QComboBox()
self.repo_selector.setMinimumWidth(200)
self.load_repos_btn = QPushButton("Load Repos")
self.save_btn = QPushButton("Save README")
self.save_btn.clicked.connect(self.save_readme)
self.preview_toggle = QPushButton("Preview")
self.preview_toggle.setCheckable(True)
self.preview_toggle.toggled.connect(self.toggle_preview)
top_controls.addWidget(self.save_btn)
top_controls.addWidget(self.preview_toggle)
top_controls.addStretch()
# Template elements buttons
template_controls = QHBoxLayout()
self.template_buttons = [
("Table", self.insert_table),
("Header", self.insert_header),
("List", self.insert_list),
("Link", self.insert_link),
("Image", self.insert_image),
("Code Block", self.insert_code_block),
("Badge", self.insert_badge)
]
for btn_text, btn_func in self.template_buttons:
btn = QPushButton(btn_text)
btn.clicked.connect(btn_func)
template_controls.addWidget(btn)
# Main editor and preview area
self.editor_preview = QStackedWidget()
# Editor
self.editor = QPlainTextEdit()
self.editor.setPlaceholderText("# Your README.md content here...\n\nStart writing your GitHub README or use the template buttons above.")
# Preview
self.preview = MarkdownPreview()
self.editor_preview.addWidget(self.editor)
self.editor_preview.addWidget(self.preview)
# Connect editor changes to preview updates
self.editor.textChanged.connect(self.update_preview)
# Add everything to the main layout
layout.addLayout(top_controls)
layout.addLayout(template_controls)
layout.addWidget(self.editor_preview)
# Initial state
self.load_repositories()
def load_repositories(self):
"""Load user repositories into the combo box."""
self.repo_selector.clear()
ok, repos = self.api.get_repos()
if ok and isinstance(repos, list):
for repo in repos:
self.repo_selector.addItem(repo["name"])
def toggle_preview(self, checked):
"""Toggle between editor and preview views."""
if checked:
# Update preview before switching
self.update_preview()
self.editor_preview.setCurrentIndex(1)
self.preview_toggle.setText("Edit")
else:
self.editor_preview.setCurrentIndex(0)
self.preview_toggle.setText("Preview")
def update_preview(self):
"""Update markdown preview."""
content = self.editor.toPlainText()
self.preview.update_preview(content, "markdown")
def save_readme(self):
"""Save README.md to the selected repository."""
repo_name = self.repo_selector.currentText()
if not repo_name:
QMessageBox.warning(self, "Error", "Please select a repository")
return
content = self.editor.toPlainText()
owner = self.user_data.get("login", "")
# Check if README.md already exists in the repository
ok, result = self.api.get_contents(owner, repo_name, "README.md")
if ok and isinstance(result, dict) and "sha" in result:
# Update existing README
sha = result["sha"]
success, msg = self.api.update_file(
owner, repo_name, "README.md", "Update README.md", content, sha
)
else:
# Create new README
success, msg = self.api.upload_file(
owner, repo_name, "README.md", content.encode('utf-8')
)
if success:
QMessageBox.information(self, "Success", f"README.md saved to {repo_name}")
else:
QMessageBox.warning(self, "Error", f"Failed to save README.md: {msg}")
# Template insertion functions
def insert_table(self):
"""Insert a markdown table template."""
table = """
| Header 1 | Header 2 | Header 3 |
|----------|----------|----------|
| Row 1 | Data | Data |
| Row 2 | Data | Data |
| Row 3 | Data | Data |
"""
self.editor.insertPlainText(table)
def insert_header(self):
"""Insert header template."""
headers = """# Main Header
## Secondary Header
### Tertiary Header
"""
self.editor.insertPlainText(headers)
def insert_list(self):
"""Insert list template."""
list_template = """
- Item 1
- Item 2
- Item 3
- Nested item 1
- Nested item 2
"""
self.editor.insertPlainText(list_template)
def insert_link(self):
"""Insert link template."""
self.editor.insertPlainText("[Link Text](https://example.com)")
def insert_image(self):
"""Insert image template."""
self.editor.insertPlainText("")
def insert_code_block(self):
"""Insert code block template."""
code_block = """```python
# Python code example
def hello_world():
print("Hello, GitHub!")
```"""
self.editor.insertPlainText(code_block)
def insert_badge(self):
"""Insert badge template."""
badge = "[](https://opensource.org/licenses/MIT)"
self.editor.insertPlainText(badge)
def insert_hr(self):
"""Insert horizontal rule."""
self.editor.insertPlainText("\n---\n")
class ModifiedRepoBrowserTab(QWidget):
"""Modified Repo Browser tab with search/replace moved and no New Folder button."""
def __init__(self, api, user_data):
super().__init__()
self.api = api
self.user_data = user_data
self.layout = QVBoxLayout(self)
self.setLayout(self.layout)
# Current navigation path
self.current_path = ""
self.current_repo = ""
self.path_history = []
# Repository selection section with Create New button (not including search/replace anymore)
top_row = QHBoxLayout()
# Combobox with placeholder text
self.cmb_repos = QComboBox()
self.cmb_repos.addItem("Select Repo")
self.cmb_repos.setItemData(0, QColor(120, 120, 120), Qt.ForegroundRole)
self.cmb_repos.setCurrentIndex(0)
self.cmb_repos.currentIndexChanged.connect(self.on_repo_changed)
# Add Create Repository button next to dropdown
btn_create_repo = QPushButton("Create Repo")
btn_create_repo.clicked.connect(self.show_create_repo_dialog)
# Add repo controls to top row
top_row.addWidget(self.cmb_repos)
top_row.addWidget(btn_create_repo)
top_row.addStretch()
# Main content area
content_layout = QVBoxLayout()
# Tree view header with back button
tree_header = QHBoxLayout()
self.btn_back = QPushButton("⬅ Back")
self.btn_back.clicked.connect(self.go_back)
self.btn_back.setEnabled(False)
self.path_label = QLabel("/")
self.path_label.setStyleSheet("color: #ffffff;")
tree_header.addWidget(self.btn_back)
tree_header.addWidget(self.path_label)
tree_header.addStretch()
# Files and editor
main_splitter = QSplitter(Qt.Horizontal)
# Left side - tree and drop area
left_widget = QWidget()
left_layout = QVBoxLayout(left_widget)
left_layout.addLayout(tree_header)
self.tree_files = QTreeWidget()
self.tree_files.setColumnCount(1)
self.tree_files.setHeaderLabels([""])
self.tree_files.setStyleSheet("""
QTreeWidget {
background-color: #2c2c2c;
color: #e0e0e0;
border: 1px solid #444;
}
QTreeWidget::item {
height: 24px;
}
QTreeWidget::item:selected {
background-color: #565656;
}
QHeaderView::section {
background-color: #3a3a3a;
color: #e0e0e0;
padding: 5px;
border: 1px solid #444;
}
""")
self.tree_files.itemClicked.connect(self.on_item_clicked)
self.tree_files.itemDoubleClicked.connect(self.on_item_double_clicked)
# Button group - file operations buttons on left side (No New Folder button)
button_layout = QHBoxLayout()
# New File button only (No New Folder button)
self.btn_new_file = QPushButton("New File")
self.btn_save_file = QPushButton("Save File")
self.btn_delete_file = QPushButton("Delete File")
self.btn_delete_folder = QPushButton("Delete Folder")
self.btn_new_file.clicked.connect(self.create_new_file)
self.btn_save_file.clicked.connect(self.save_current_file)
self.btn_delete_file.clicked.connect(self.delete_current_file)
self.btn_delete_folder.clicked.connect(self.delete_current_folder)
button_layout.addWidget(self.btn_new_file)
button_layout.addWidget(self.btn_save_file)
button_layout.addWidget(self.btn_delete_file)
button_layout.addWidget(self.btn_delete_folder)
button_layout.addStretch()
# Drop and select area
self.drop_area = DropArea()
self.drop_area.fileDrop.connect(self.handle_file_drop)
# Add browse button to drop area
browse_btn = QPushButton("Browse Files")
browse_btn.clicked.connect(self.browse_files)
left_layout.addWidget(self.tree_files)
left_layout.addLayout(button_layout)
left_layout.addWidget(self.drop_area)
left_layout.addWidget(browse_btn)
# Right side - editor and preview
right_widget = QWidget()
right_layout = QVBoxLayout(right_widget)
# Find/Replace controls moved here above the editor
search_replace_layout = QHBoxLayout()
search_label = QLabel("Find:")
self.search_edit = QLineEdit()
self.search_edit.returnPressed.connect(self.find_text)
replace_label = QLabel("Replace:")
self.replace_edit = QLineEdit()
self.find_btn = QPushButton("Find")
self.replace_btn = QPushButton("Replace")
self.replace_all_btn = QPushButton("Replace All")
self.find_btn.clicked.connect(self.find_text)
self.replace_btn.clicked.connect(self.replace_text)
self.replace_all_btn.clicked.connect(self.replace_all_text)
search_replace_layout.addWidget(search_label)
search_replace_layout.addWidget(self.search_edit)
search_replace_layout.addWidget(replace_label)
search_replace_layout.addWidget(self.replace_edit)
search_replace_layout.addWidget(self.find_btn)
search_replace_layout.addWidget(self.replace_btn)
search_replace_layout.addWidget(self.replace_all_btn)
right_layout.addLayout(search_replace_layout)
# Text editor with live preview in a vertical splitter
self.editor_preview_splitter = QSplitter(Qt.Vertical)
# Text editor for code/markdown
self.text_content = QPlainTextEdit()
self.text_content.setPlaceholderText("File content here...")
self.text_content.setReadOnly(True)
self.text_content.textChanged.connect(self.update_preview)
# Make text content scrollbar match preview scrollbar style
self.text_content.setStyleSheet("""
QPlainTextEdit {
background-color: #2c2c2c;
color: #e0e0e0;
border: 1px solid #444;
}
QScrollBar:vertical {
border: none;
background: #2c2c2c;
width: 10px;
margin: 0px;
}
QScrollBar::handle:vertical {
background: #565656;
min-height: 20px;
border-radius: 5px;
}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical,
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
background: none;
}
""")
# Markdown/code preview panel
self.preview = MarkdownPreview()
self.editor_preview_splitter.addWidget(self.text_content)
self.editor_preview_splitter.addWidget(self.preview)
# Set split sizes (40% editor, 60% preview)
self.editor_preview_splitter.setSizes([400, 600])
right_layout.addWidget(self.editor_preview_splitter)
# Add widgets to main splitter
main_splitter.addWidget(left_widget)
main_splitter.addWidget(right_widget)
main_splitter.setSizes([300, 700]) # Proportional sizes
content_layout.addWidget(main_splitter)
# Add to main layout
self.layout.addLayout(top_row)
self.layout.addLayout(content_layout)
# Initialize
self.selected_file = None
self.selected_sha = None
self.selected_path = ""
self.current_file_type = "text"
self.selected_folder = None
# Load repos
self.load_user_repos()
def find_text(self):
"""Find text in the editor."""
search_text = self.search_edit.text()
if not search_text:
return
# Start search from current cursor position
cursor = self.text_content.textCursor()
# If nothing is selected, start from beginning
if not cursor.hasSelection():
cursor.setPosition(0)
self.text_content.setTextCursor(cursor)
# Find next occurrence
found = self.text_content.find(search_text)
if not found:
# Try from the beginning
cursor.setPosition(0)
self.text_content.setTextCursor(cursor)
found = self.text_content.find(search_text)
if not found:
QMessageBox.information(self, "Search", f"No occurrences of '{search_text}' found")
def replace_text(self):
"""Replace selected text in the editor."""
search_text = self.search_edit.text()
replace_text = self.replace_edit.text()
if not search_text:
return
# Replace selected text if it matches search text
cursor = self.text_content.textCursor()
if cursor.hasSelection() and cursor.selectedText() == search_text:
cursor.insertText(replace_text)
# Find next occurrence
self.find_text()
def replace_all_text(self):
"""Replace all occurrences of search text."""
search_text = self.search_edit.text()
replace_text = self.replace_edit.text()
if not search_text:
return
content = self.text_content.toPlainText()
if search_text in content:
new_content = content.replace(search_text, replace_text)
self.text_content.setPlainText(new_content)
count = content.count(search_text)
QMessageBox.information(self, "Replace All", f"Replaced {count} occurrences")
else:
QMessageBox.information(self, "Replace All", f"No occurrences of '{search_text}' found")
def create_new_file(self):
"""Create a new file in the current directory."""
if not self.current_repo:
QMessageBox.warning(self, "Error", "Please select a repository first")
return
filename, ok = QInputDialog.getText(
self,
"Create New File",
"Enter file name:",
QLineEdit.Normal,
""
)
if ok and filename:
# Create empty file
owner = self.user_data.get("login", "")
repo_name = self.current_repo
# Build path
path = self.current_path
if path:
path += "/"
path += filename
# Empty content
content = ""
# Upload file
success, msg = self.api.upload_file(owner, repo_name, path, content.encode('utf-8'))
if success:
QMessageBox.information(self, "Success", f"File '{filename}' created successfully")
self.load_directory_contents()
else:
QMessageBox.warning(self, "Error", f"Failed to create file: {msg}")
def delete_current_folder(self):
"""Delete the selected folder."""
if not self.selected_folder:
QMessageBox.warning(self, "Error", "Please select a folder first")
return
folder_path = self.selected_folder["path"]
folder_name = self.selected_folder["name"]
reply = QMessageBox.question(
self,
"Confirm Delete",
f"Really delete folder '{folder_name}' and all its contents?\nThis action cannot be undone!",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No
)
if reply == QMessageBox.Yes:
# GitHub API doesn't directly support folder deletion
# We need to recursively delete all files in the folder
self.recursive_delete_folder(folder_path)
def recursive_delete_folder(self, folder_path):
"""Recursively delete all files in a folder."""
owner = self.user_data.get("login", "")
repo_name = self.current_repo
# Get all files in the folder
ok, contents = self.api.get_contents(owner, repo_name, folder_path)
if not ok:
QMessageBox.warning(self, "Error", f"Failed to list folder contents: {contents}")
return
if not isinstance(contents, list):
contents = [contents]
# Track success and failure counts
success_count = 0
failure_count = 0
# Process all items
for item in contents:
if item["type"] == "dir":
# Recursively delete subfolder
self.recursive_delete_folder(item["path"])
else:
# Delete file
message = f"Delete file {item['path']}"
ok, res = self.api.delete_file(owner, repo_name, item["path"], message, item["sha"])
if ok:
success_count += 1
else:
failure_count += 1
# Show results
if failure_count == 0:
QMessageBox.information(self, "Success", f"Folder deleted successfully")
else:
QMessageBox.warning(self, "Partial Success",
f"Deleted {success_count} files, but failed to delete {failure_count} files")
# Refresh directory listing
self.load_directory_contents()
self.selected_folder = None
def show_create_repo_dialog(self):
"""Show dialog to create a new repository."""
dialog = QDialog(self)
dialog.setWindowTitle("Create Repository")
layout = QFormLayout(dialog)
name_edit = QLineEdit()
desc_edit = QLineEdit()
private_check = QCheckBox()
layout.addRow("Name:", name_edit)
layout.addRow("Description:", desc_edit)
layout.addRow("Private:", private_check)
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttons.accepted.connect(dialog.accept)
buttons.rejected.connect(dialog.reject)
layout.addRow(buttons)
if dialog.exec_():
name = name_edit.text().strip()
desc = desc_edit.text().strip()
private = private_check.isChecked()
if not name:
QMessageBox.warning(self, "Error", "Repository name is required")
return
self.create_repo(name, desc, private)
def create_repo(self, name, desc, private):
"""Create a new repository."""
ok, r = self.api.create_repo(name, desc, private)
if ok:
QMessageBox.information(
self,
"Success",
f"Repository '{name}' created successfully"
)
# Refresh repos
self.load_user_repos()
# Select the newly created repo
index = self.cmb_repos.findText(name)
if index >= 0:
self.cmb_repos.setCurrentIndex(index)
else:
QMessageBox.warning(self, "Error", f"Failed to create repository: {r}")
def browse_files(self):
"""Open file browser to select files to upload."""
files, _ = QFileDialog.getOpenFileNames(self, "Select Files to Upload")
if files:
self.handle_file_drop(files)
def go_back(self):
"""Navigate back to the previous directory."""
if self.path_history:
# Get previous path
prev_path = self.path_history.pop()
self.current_path = prev_path
# Update UI
self.path_label.setText(f"/{self.current_path}")
self.btn_back.setEnabled(bool(self.path_history))
# Load directory contents
self.load_directory_contents()
def on_repo_changed(self, index):
"""Automatically load repo contents when a repo is selected."""
if index > 0: # Skip placeholder item
self.current_repo = self.cmb_repos.currentText()
self.current_path = ""
self.path_history = []
self.btn_back.setEnabled(False)
self.path_label.setText("/")
self.load_directory_contents()
def on_item_double_clicked(self, item, column):
"""Handle double click on tree items (for directory navigation)."""
data = item.data(0, Qt.UserRole)
if not data:
return
if data["type"] == "dir":
# Save selected folder (for delete operation)
self.selected_folder = data
# Navigate into directory