forked from anuragpandey1rkt-cmyk/cpp-online-compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
270 lines (231 loc) · 8.72 KB
/
app.py
File metadata and controls
270 lines (231 loc) · 8.72 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
import streamlit as st
import subprocess
import tempfile
import os
import sys
import time
import shutil
import zipfile
import base64
import io # ← THIS WAS MISSING
from pathlib import Path
from datetime import datetime
import signal
# Page config
st.set_page_config(
page_title="C++ Online IDE",
page_icon="💻",
layout="wide",
initial_sidebar_state="collapsed"
)
# Custom CSS - Fixed IDE Theme
st.markdown("""
<style>
[data-testid="stSidebar"] {position: fixed !important;}
.ide-header {background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%); padding: 1.5rem; border-radius: 0 0 20px 20px; color: white; margin: -1.5rem -1.5rem 2rem -1.5rem;}
.file-tab {background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px 8px 0 0; padding: 8px 16px; margin-right: 4px; cursor: pointer; font-weight: 500;}
.file-tab.active {background: #3b82f6; color: white;}
.panel {background: #0f0f23; color: #e2e8f0; padding: 1.5rem; border-radius: 12px; height: 350px; overflow-y: auto; font-family: 'Monaco', monospace; border: 1px solid #334155;}
.status-bar {background: #1e293b; padding: 12px; border-radius: 0 0 12px 12px; font-size: 14px; color: #94a3b8;}
.control-btn {border-radius: 8px; padding: 10px 20px; font-weight: 600; border: none; margin: 2px;}
</style>
""", unsafe_allow_html=True)
# === STATE INITIALIZATION ===
@st.cache_data(ttl=300)
def init_state():
return {
'files': {
"main.cpp": '''#include <iostream>
using namespace std;
int main() {
cout << "🚀 C++ Online IDE - Hello World!" << endl;
return 0;
}'''
},
'active_file': "main.cpp",
'is_running': False,
'compile_status': "idle",
'output': "",
'error': "",
'compile_output': "",
'exec_time': 0,
'input_data': ""
}
if 'state' not in st.session_state:
st.session_state.state = init_state()
def get_state(key, default=None):
return st.session_state.state.get(key, default)
def set_state(key, value):
st.session_state.state[key] = value
# === SECURE COMPILER FUNCTIONS ===
def secure_compile(_files):
"""Compile multi-file C++ project"""
try:
with tempfile.TemporaryDirectory(prefix="cpp_ide_") as sandbox_path:
sandbox_dir = Path(sandbox_path)
# Write all files
for filename, content in _files.items():
file_path = sandbox_dir / filename
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, 'w') as f:
f.write(content)
# Compile command
cmd = ["g++", "-std=c++17", "-Wall", "-Wextra", "-O2", "-o", "a.out"]
cmd.extend([str(sandbox_dir / f) for f in _files.keys()])
result = subprocess.run(
cmd, cwd=sandbox_dir, capture_output=True, text=True,
timeout=10
)
if result.returncode == 0:
return True, f"✅ Compiled {len(_files)} files", sandbox_dir / "a.out"
else:
return False, result.stdout, None
except Exception as e:
return False, f"❌ Error: {str(e)}", None
def secure_run(exe_path, input_data):
"""Run with timeout"""
try:
with tempfile.TemporaryDirectory() as sandbox_path:
sandbox_dir = Path(sandbox_path)
# Input file
input_file = sandbox_dir / "input.txt"
with open(input_file, 'w') as f:
f.write(input_data)
start_time = time.time()
process = subprocess.Popen(
[str(exe_path)], stdin=open(input_file, 'r'),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=sandbox_dir, text=True, timeout=8
)
stdout, stderr = process.communicate(timeout=8)
exec_time = time.time() - start_time
return True, stdout, stderr, exec_time
except:
return False, "", "⏰ Timeout (8s)", 8.0
# === FILE MANAGER ===
def render_file_manager():
with st.sidebar:
st.markdown("## 💾 Files")
# New file
new_name = st.text_input("New file:", key="new_file_name", placeholder="file.cpp")
if st.button("➕ Create") and new_name:
if new_name not in get_state('files', {}):
files = get_state('files', {})
files[new_name] = "// New file\n"
set_state('files', files)
st.markdown("---")
# File list
files = get_state('files', {})
for filename in list(files.keys()):
col1, col2 = st.columns([4, 1])
with col1:
if st.button(filename, key=f"select_{filename}"):
set_state('active_file', filename)
with col2:
if st.button("🗑️", key=f"del_{filename}"):
del files[filename]
set_state('files', files)
if get_state('active_file') == filename:
set_state('active_file', list(files.keys())[0])
# Download ZIP
if st.button("📦 Download Project"):
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:
for filename, content in files.items():
zf.writestr(filename, content)
zip_buffer.seek(0)
b64 = base64.b64encode(zip_buffer.read()).decode()
st.markdown(f'<a href="data:application/zip;base64,{b64}" download="cpp-ide.zip">💾 Download ZIP</a>', unsafe_allow_html=True)
# === MAIN LAYOUT ===
st.markdown('<div class="ide-header">💻 C++ Online IDE | Production Grade</div>', unsafe_allow_html=True)
# Top controls
cols = st.columns(6)
with cols[0]:
if st.button("🔨 Compile", key="compile"):
with st.spinner("Compiling..."):
files = get_state('files', {})
success, msg, exe_path = secure_compile(files)
set_state('compile_status', "success" if success else "error")
set_state('compile_output', msg)
set_state('sandbox_exe', str(exe_path) if success else None)
with cols[1]:
exe_path = get_state('sandbox_exe')
if st.button("▶️ Run", key="run", disabled=not exe_path):
with st.spinner("Running..."):
input_data = get_state('input_data', '')
success, stdout, stderr, exec_time = secure_run(exe_path, input_data)
set_state('output', stdout)
set_state('error', stderr)
set_state('exec_time', exec_time)
with cols[2]:
if st.button("🗑️ Clear", key="clear"):
set_state('output', '')
set_state('error', '')
set_state('compile_output', '')
with cols[3]:
if st.button("🔄 Reset", key="reset"):
st.session_state.state = init_state()
st.rerun()
# IDE Layout
col1, col2, col3 = st.columns([1, 3, 1.2])
# Left: File Manager
with col1:
render_file_manager()
# Center: Editor
with col2:
st.markdown("### 📝 Code Editor")
active_file = get_state('active_file', 'main.cpp')
# File tabs
for filename in get_state('files', {}).keys():
if st.button(filename, key=f"tab_{filename}"):
set_state('active_file', filename)
# Editor
code = st.text_area(
f"Editing: **{active_file}**",
value=get_state('files', {}).get(active_file, ''),
height=450,
key=f"editor_{active_file}"
)
files = get_state('files', {})
files[active_file] = code
set_state('files', files)
# Right: Panels
with col3:
st.markdown("### 📥 Input")
input_data = st.text_area("stdin:", height=120, key="input_panel")
set_state('input_data', input_data)
# Output tabs
if get_state('output') or get_state('error') or get_state('compile_output'):
tab1, tab2, tab3 = st.tabs(["📤 Output", "❌ Errors", "🔧 Compiler"])
with tab1:
st.text_area(
"Program Output",
value=get_state('output', ''),
height=200,
disabled=True,
key="stdout_box"
)
with tab2:
st.text_area(
"Runtime Errors",
value=get_state('error', ''),
height=200,
disabled=True,
key="stderr_box"
)
with tab3:
st.text_area(
"Compiler Output",
value=get_state('compile_output', ''),
height=200,
disabled=True,
key="compile_box"
)
# Status bar
st.markdown(f'''
<div class="status-bar">
Status: {get_state('compile_status', 'idle')} |
File: {get_state('active_file', 'main.cpp')} |
Time: {get_state('exec_time', 0):.2f}s
</div>
''', unsafe_allow_html=True)