File size: 12,580 Bytes
655b364
33fee17
80f8f81
 
655b364
772c871
 
 
33fee17
 
772c871
33fee17
12f115d
 
 
33fee17
 
772c871
 
80f8f81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33fee17
 
 
 
 
772c871
668c0c5
772c871
33fee17
 
 
 
668c0c5
772c871
 
 
 
 
 
 
 
 
 
 
12f115d
772c871
 
12f115d
772c871
12f115d
772c871
33fee17
12f115d
668c0c5
772c871
12f115d
 
 
 
772c871
12f115d
668c0c5
772c871
 
 
33fee17
 
772c871
33fee17
 
772c871
80f8f81
12f115d
772c871
 
 
 
 
 
 
 
 
33fee17
 
 
772c871
80f8f81
772c871
 
 
 
 
80f8f81
772c871
 
 
 
12f115d
 
 
772c871
 
80f8f81
772c871
33fee17
772c871
33fee17
 
 
772c871
 
80f8f81
772c871
 
 
 
 
 
 
 
 
 
12f115d
33fee17
 
 
772c871
 
655b364
772c871
668c0c5
772c871
 
 
 
 
33fee17
772c871
33fee17
12f115d
80f8f81
 
 
 
 
 
 
33fee17
772c871
668c0c5
772c871
 
 
 
 
668c0c5
772c871
 
 
 
 
 
80f8f81
772c871
 
 
 
 
 
 
 
 
12f115d
772c871
12f115d
655b364
772c871
1b97373
33fee17
772c871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33fee17
772c871
 
 
 
 
33fee17
 
772c871
33fee17
 
 
772c871
33fee17
 
772c871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33fee17
772c871
 
 
 
 
33fee17
12f115d
772c871
 
80f8f81
 
 
 
 
 
 
33fee17
 
772c871
 
33fee17
772c871
33fee17
772c871
33fee17
 
 
 
772c871
 
33fee17
 
12f115d
772c871
 
 
 
 
 
 
 
 
 
 
33fee17
 
668c0c5
12f115d
 
772c871
12f115d
 
668c0c5
772c871
80f8f81
772c871
12f115d
 
668c0c5
12f115d
33fee17
772c871
 
 
 
 
 
 
 
80f8f81
668c0c5
12f115d
772c871
 
 
 
 
 
 
 
33fee17
 
772c871
 
80f8f81
772c871
 
 
 
12f115d
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
import gradio as gr
import time
import os
from pathlib import Path

# Simulated file storage (in-memory dictionary)
files = {"untitled.py": ""}  # file_name: content
open_files = ["untitled.py"]  # List of open files

# Load file content into editor
def load_file(file, current_file, open_files):
    global files
    if file is not None:
        with open(file.name, "r") as f:
            code = f.read()
        filename = file.name.split("/")[-1]
        files[filename] = code
        if filename not in open_files:
            open_files.append(filename)
        return code, filename, open_files, code
    return files.get(current_file, ""), current_file, open_files, files.get(current_file, "")

# Load file from FileExplorer
def load_from_explorer(selected_files, files, open_files):
    if isinstance(selected_files, str):  # Single file selected
        selected_files = [selected_files]
    if selected_files and selected_files[0]:
        filename = os.path.basename(selected_files[0])
        with open(selected_files[0], "r") as f:
            code = f.read()
        files[filename] = code
        if filename not in open_files:
            open_files.append(filename)
        return code, filename, open_files, code
    return "", list(files.keys())[0], open_files, ""

# Save current file content
def save_file(code, current_file):
    global files
    files[current_file] = code
    return f"Saved {current_file}"

# Simulate running code
def run_code(code, terminal_history):
    timestamp = time.strftime("%H:%M:%S")
    output = f"[{timestamp}] Ran:\n{code}\nOutput: Simulated execution successful"
    return f"{terminal_history}\n{output}".strip()

# Process terminal commands
def process_command(cmd, files, history):
    if cmd.strip() == "ls":
        output = "\n".join(files.keys())
    elif cmd.startswith("echo "):
        output = cmd[5:]
    else:
        output = f"Command not recognized: {cmd}"
    return f"{history}\n$ {cmd}\n{output}"

# AI-powered suggestions
def get_suggestions(code):
    code = code.lower()
    if "def" in code:
        return ["def function_name():", "def main():", "def __init__(self):"]
    elif "print" in code:
        return ["print('Hello, World!')", "print(variable)", "print(f'String: {var}')"]
    elif "import" in code:
        return ["import os", "import sys", "import numpy as np"]
    return ["# Start typing for suggestions"]

# Insert suggestion
def insert_suggestion(code, suggestion):
    if suggestion:
        lines = code.split("\n")
        last_line = lines[-1]
        return code + ("\n" + suggestion if last_line.strip() else suggestion)
    return code

# Switch tabs
def switch_tab(selected, files):
    return files.get(selected, ""), selected

# Add new file
def add_new_file(open_files, files):
    new_file = f"untitled_{len(files)}.py"
    files[new_file] = ""
    open_files.append(new_file)
    return "", new_file, open_files, files[new_file]

# Close tab
def close_tab(open_files, current_file, files):
    if len(open_files) > 1:
        new_open_files = [f for f in open_files if f != current_file]
        new_current = new_open_files[0]
        return new_open_files, new_current, files[new_current]
    return open_files, current_file, files[current_file]

# Download file
def download_code(code, current_file):
    return code, current_file

# Process command palette
def process_palette(cmd, theme, files, current_file, code):
    if cmd == "theme dark":
        return "dark", "Theme set to dark"
    elif cmd == "theme light":
        return "light", "Theme set to light"
    elif cmd == "save":
        files[current_file] = code
        return theme, f"Saved {current_file}"
    return theme, f"Command not found: {cmd}"

# Gradio interface
with gr.Blocks(
    title="VS Code Clone",
    css="""
        .gradio-container { background-color: #1e1e1e; color: #d4d4d4; font-family: 'Consolas', monospace; height: 100vh; margin: 0; }
        .activity-bar { background-color: #333; padding: 10px; width: 50px; min-width: 50px; }
        .sidebar { background-color: #252526; padding: 10px; width: 250px; min-width: 250px; }
        .editor { background-color: #1e1e1e; border: none; }
        .terminal { background-color: #0e0e0e; color: #b5cea8; font-size: 12px; }
        .status-bar { background-color: #007acc; color: white; padding: 5px; }
        .tabs { display: flex; gap: 5px; background-color: #1e1e1e; padding: 5px; border-bottom: 1px solid #3c3c3c; }
        .tab { background-color: #2d2d2d; padding: 5px 10px; cursor: pointer; }
        .tab.active { background-color: #007acc; }
        button { background-color: #007acc; color: white; border: none; padding: 5px; margin: 2px; }
        button:hover { background-color: #005f99; }
        .file-explorer { max-height: 300px; overflow-y: auto; }
        .command-palette { position: absolute; top: 20%; left: 30%; width: 40%; background: #252526; z-index: 1000; padding: 10px; }
        .light .gradio-container { background-color: #ffffff; color: #000000; }
        .light .editor { background-color: #ffffff; color: #000000; }
        .light .sidebar { background-color: #f3f3f3; }
        .light .terminal { background-color: #f0f0f0; color: #000000; }
        .light .status-bar { background-color: #0066cc; }
        .light .tabs { background-color: #ffffff; }
        .light .tab { background-color: #e0e0e0; }
        .light .tab.active { background-color: #0066cc; }
    """
) as app:
    # States
    current_file = gr.State(value="untitled.py")
    terminal_history = gr.State(value="")
    theme_state = gr.State(value="dark")
    cursor_position = gr.State(value="Ln 1, Col 1")

    # Layout
    with gr.Row():
        # Activity Bar
        with gr.Column(scale=0, elem_classes="activity-bar"):
            explorer_btn = gr.Button("πŸ“")
            terminal_btn = gr.Button("πŸ–₯️")

        # Sidebar (File Explorer)
        with gr.Column(scale=1, visible=False, elem_classes="sidebar") as sidebar:
            gr.Markdown("### Explorer")
            file_upload = gr.File(label="Upload File")
            file_explorer = gr.FileExplorer(
                label="Files",
                glob="*.py",
                file_count="single",
                root_dir=os.getcwd(),
                elem_classes="file-explorer"
            )

        # Editor Pane
        with gr.Column(scale=4):
            with gr.Row(elem_classes="tabs"):
                file_tabs = gr.Dropdown(label="Open Files", choices=open_files, value="untitled.py", interactive=True)
                new_file_btn = gr.Button("βž•")
                close_tab_btn = gr.Button("❌")
            code_editor = gr.Code(label="Editor", language="python", lines=20, elem_classes="editor")
            with gr.Row():
                with gr.Column(scale=3):
                    terminal_panel = gr.Column(visible=False, elem_classes="terminal")
                    with terminal_panel:
                        terminal_output = gr.Textbox(label="Terminal", lines=10, interactive=False)
                        terminal_input = gr.Textbox(label=">", placeholder="Type command and press Enter")
                with gr.Column(scale=1):
                    suggestions_list = gr.Radio(choices=[], label="Suggestions", type="value")

    # Status Bar
    with gr.Row(elem_classes="status-bar"):
        run_btn = gr.Button("β–Ά Run")
        save_btn = gr.Button("πŸ’Ύ Save")
        status_info = gr.Textbox(value="Python β€’ Ln 1, Col 1", interactive=False)

    # Command Palette
    command_palette = gr.Textbox(label="> Command Palette", visible=False, elem_classes="command-palette")

    # Hidden Download Output
    download_output = gr.File(label="Download", visible=False)

    # JavaScript for shortcuts and cursor tracking
    app.load(js="""
    () => {
        const editor = document.querySelector('#code_editor textarea');
        const status = document.querySelector('#status_info input');
        const palette = document.querySelector('#command_palette');
        const themeInput = document.querySelector('#theme_state input');
        const container = document.querySelector('.gradio-container');

        // Cursor position
        function getCursorPosition(textarea) {
            const text = textarea.value;
            const pos = textarea.selectionStart;
            const lines = text.substr(0, pos).split('\\n');
            return `Python β€’ Ln ${lines.length}, Col ${lines[lines.length - 1].length + 1}`;
        }
        editor.addEventListener('keyup', () => {
            status.value = getCursorPosition(editor);
            status.dispatchEvent(new Event('input'));
        });
        editor.addEventListener('click', () => {
            status.value = getCursorPosition(editor);
            status.dispatchEvent(new Event('input'));
        });

        // Shortcuts
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.shiftKey && e.key === 'P') {
                e.preventDefault();
                palette.style.display = 'block';
                palette.querySelector('input').focus();
            }
            if (e.ctrlKey && e.key === 's') {
                e.preventDefault();
                document.querySelector('#save_btn').click();
            }
            if (e.ctrlKey && e.key === 'r') {
                e.preventDefault();
                document.querySelector('#run_btn').click();
            }
        });

        // Hide palette on Escape
        palette.querySelector('input').addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                palette.style.display = 'none';
            }
        });

        // Theme switching
        container.classList.add(themeInput.value);
        const observer = new MutationObserver(() => {
            container.classList.remove('light', 'dark');
            container.classList.add(themeInput.value);
        });
        observer.observe(themeInput, {attributes: true});
    }
    """, outputs=[status_info])

    # Event Handlers
    explorer_btn.click(lambda v: gr.update(visible=not v), inputs=[sidebar.visible], outputs=[sidebar])
    terminal_btn.click(lambda v: gr.update(visible=not v), inputs=[terminal_panel.visible], outputs=[terminal_panel])

    file_upload.change(
        load_file,
        inputs=[file_upload, current_file, file_tabs.choices],
        outputs=[code_editor, current_file, file_tabs, code_editor]
    )

    file_explorer.change(
        load_from_explorer,
        inputs=[file_explorer, files, file_tabs.choices],
        outputs=[code_editor, current_file, file_tabs, code_editor]
    )

    save_btn.click(
        save_file,
        inputs=[code_editor, current_file],
        outputs=[status_info]
    ).then(
        download_code,
        inputs=[code_editor, current_file],
        outputs=[download_output]
    )

    run_btn.click(
        run_code,
        inputs=[code_editor, terminal_history],
        outputs=[terminal_output]
    ).then(
        lambda x: x,
        inputs=[terminal_output],
        outputs=[terminal_history]
    )

    terminal_input.submit(
        process_command,
        inputs=[terminal_input, files, terminal_history],
        outputs=[terminal_output]
    ).then(lambda: "", outputs=[terminal_input]).then(
        lambda x: x,
        inputs=[terminal_output],
        outputs=[terminal_history]
    )

    code_editor.change(
        get_suggestions,
        inputs=[code_editor],
        outputs=[suggestions_list]
    )

    suggestions_list.change(
        insert_suggestion,
        inputs=[code_editor, suggestions_list],
        outputs=[code_editor]
    )

    file_tabs.change(
        switch_tab,
        inputs=[file_tabs, files],
        outputs=[code_editor, current_file]
    )

    new_file_btn.click(
        add_new_file,
        inputs=[file_tabs.choices, files],
        outputs=[code_editor, current_file, file_list, code_editor]
    )

    close_tab_btn.click(
        close_tab,
        inputs=[file_tabs.choices, current_file, files],
        outputs=[file_tabs.choices, current_file, code_editor]
    ).then(
        lambda open_files, current_file: gr.update(choices=open_files, value=current_file),
        inputs=[file_tabs.choices, current_file],
        outputs=[file_tabs]
    )

    command_palette.submit(
        process_palette,
        inputs=[command_palette, theme_state, files, current_file, code_editor],
        outputs=[theme_state, status_info]
    ).then(lambda: gr.update(visible=False), outputs=[command_palette])

# Launch
app.launch()