-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileBinder.py
456 lines (361 loc) · 16.3 KB
/
FileBinder.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
import sys
import os
from PyQt6.QtWidgets import (QApplication, QMainWindow, QPushButton, QVBoxLayout, QHBoxLayout, QWidget, QListWidget,
QFileDialog, QMessageBox, QProgressBar, QTextEdit, QLabel, QDialog, QGridLayout,
QScrollArea, QTabWidget, QListWidgetItem)
from PyQt6.QtGui import QIcon, QPixmap
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QSize, QUrl
from PyQt6.QtGui import QDesktopServices
import subprocess
import shutil
import tempfile
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
class BinderThread(QThread):
progress = pyqtSignal(int)
log = pyqtSignal(str)
finished = pyqtSignal()
def __init__(self, selected_files, output_file, icon_file):
super().__init__()
self.selected_files = selected_files
self.output_file = output_file
self.icon_file = icon_file
self.cancelled = False
def run(self):
try:
self.progress.emit(0)
self.log.emit("Starting file binding process...")
with tempfile.TemporaryDirectory() as temp_dir:
if self.cancelled:
return
self.progress.emit(10)
self.log.emit("Created temporary directory")
opener_script = os.path.join(temp_dir, "opener_script.py")
with open(opener_script, "w") as f:
f.write("""
import os
import sys
import tempfile
import shutil
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def extract_file(filename):
temp_dir = tempfile.mkdtemp()
shutil.copy2(resource_path(filename), temp_dir)
return os.path.join(temp_dir, filename)
""")
for file in self.selected_files:
f.write(f"""
temp_file = extract_file("{os.path.basename(file)}")
os.startfile(temp_file)
""")
if self.cancelled:
return
self.progress.emit(30)
self.log.emit("Created opener script")
for file in self.selected_files:
shutil.copy2(file, temp_dir)
if self.cancelled:
return
self.progress.emit(50)
self.log.emit(f"Copied {len(self.selected_files)} files to temporary directory")
if self.cancelled:
return
icon_param = f"--icon={self.icon_file}" if self.icon_file else ""
output_name = os.path.splitext(os.path.basename(self.output_file))[0]
pyinstaller_command = [
"pyinstaller",
"--onefile",
"--windowed",
"--add-data", f"{temp_dir}/*;.",
icon_param,
"--name", output_name,
opener_script
]
self.log.emit("Running PyInstaller...")
result = subprocess.run(pyinstaller_command, capture_output=True, text=True)
if result.returncode != 0:
self.log.emit("PyInstaller encountered an error:")
for line in result.stderr.split('\n'):
if line.strip():
self.log.emit(f" {line.strip()}")
raise Exception("PyInstaller failed to create the executable")
self.progress.emit(80)
self.log.emit("Created executable with PyInstaller")
output_dir = os.path.dirname(self.output_file)
exe_name = f"{output_name}.exe"
source_exe = os.path.join("dist", exe_name)
if not os.path.exists(source_exe):
self.log.emit(f"Error: Expected executable not found")
raise FileNotFoundError(f"PyInstaller did not create the expected executable")
shutil.move(source_exe, self.output_file)
if self.cancelled:
return
self.progress.emit(90)
self.log.emit(f"Moved executable to: {self.output_file}")
# Careful cleanup
if os.path.exists("build"):
shutil.rmtree("build", ignore_errors=True)
self.log.emit("Cleaned up build directory")
spec_file = f"{output_name}.spec"
if os.path.exists(spec_file):
os.remove(spec_file)
self.log.emit(f"Removed {spec_file}")
else:
self.log.emit(f"Note: {spec_file} not found for cleanup")
if os.path.exists("dist"):
shutil.rmtree("dist", ignore_errors=True)
self.log.emit("Cleaned up dist directory")
self.progress.emit(100)
self.log.emit("File binding process completed successfully")
self.finished.emit()
except Exception as e:
self.log.emit(f"Error: {str(e)}")
self.finished.emit()
def cancel(self):
self.cancelled = True
class IconBrowser(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Icon Browser")
self.setFixedSize(400, 300)
self.selected_icon = ""
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
scroll_area = QScrollArea()
scroll_area.setWidgetResizable(True)
scroll_content = QWidget()
grid_layout = QGridLayout(scroll_content)
icon_dir = resource_path("icons") # Directory containing built-in icons
row, col = 0, 0
for icon_file in os.listdir(icon_dir):
if icon_file.endswith(".ico"):
icon_path = os.path.join(icon_dir, icon_file)
icon_button = QPushButton()
icon_button.setIcon(QIcon(icon_path))
icon_button.setIconSize(QSize(32, 32))
icon_button.clicked.connect(lambda _, path=icon_path: self.select_icon(path))
grid_layout.addWidget(icon_button, row, col)
col += 1
if col > 4:
col = 0
row += 1
scroll_area.setWidget(scroll_content)
layout.addWidget(scroll_area)
custom_icon_button = QPushButton("Select Custom Icon")
custom_icon_button.clicked.connect(self.select_custom_icon)
layout.addWidget(custom_icon_button)
self.setLayout(layout)
def select_icon(self, icon_path):
self.selected_icon = icon_path
self.accept()
def select_custom_icon(self):
file_dialog = QFileDialog()
icon_path, _ = file_dialog.getOpenFileName(self, "Select Custom Icon", "", "Icon Files (*.ico)")
if icon_path:
self.selected_icon = icon_path
self.accept()
class AboutDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("About File Binder")
self.setFixedSize(400, 400)
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
logo_label = QLabel()
logo_pixmap = QPixmap(resource_path('logo.png'))
logo_label.setPixmap(logo_pixmap.scaled(100, 100, Qt.AspectRatioMode.KeepAspectRatio))
logo_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(logo_label)
app_name = QLabel("File Binder")
app_name.setAlignment(Qt.AlignmentFlag.AlignCenter)
app_name.setStyleSheet("font-size: 24px; font-weight: bold;")
layout.addWidget(app_name)
description = QLabel("File Binder, Designed and Developed For Vth Semester, Mini Project by:-")
description.setAlignment(Qt.AlignmentFlag.AlignCenter)
description.setWordWrap(True)
layout.addWidget(description)
developer = [
{"name": "Arshan Mansuri", "Portfolio": "https://arsn72.github.io/INTRO/"},
]
for dev in developer:
dev_name = QLabel(dev['name'])
dev_name.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(dev_name)
portfolio_button = QPushButton("Portfolio")
portfolio_button.clicked.connect(lambda _, url=dev['Portfolio']: QDesktopServices.openUrl(QUrl(url)))
layout.addWidget(portfolio_button)
contribute_button = QPushButton("Wanna Contribute to this project?")
contribute_button.clicked.connect(lambda: QDesktopServices.openUrl(QUrl("https://github.com/ARSN72/FileBinder")))
layout.addWidget(contribute_button)
self.setLayout(layout)
class FileBinder(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("File Binder")
self.setGeometry(100, 100, 800, 600)
self.setWindowIcon(QIcon(resource_path("app_icon.ico")))
self.selected_files = []
self.icon_file = ""
self.output_file = ""
self.default_icon = resource_path("app_icon.ico")
self.init_ui()
def init_ui(self):
main_widget = QWidget()
main_layout = QVBoxLayout()
self.tabs = QTabWidget()
self.tabs.addTab(self.create_files_tab(), "Files")
self.tabs.addTab(self.create_icon_tab(), "Icon")
self.tabs.addTab(self.create_log_tab(), "Log")
main_layout.addWidget(self.tabs)
button_layout = QHBoxLayout()
bind_button = QPushButton("Bind Files")
bind_button.clicked.connect(self.bind_files)
button_layout.addWidget(bind_button)
about_button = QPushButton("About")
about_button.clicked.connect(self.show_about)
button_layout.addWidget(about_button)
main_layout.addLayout(button_layout)
self.status_layout = QHBoxLayout()
self.progress_bar = QProgressBar()
self.progress_bar.setVisible(False)
self.status_layout.addWidget(self.progress_bar)
self.cancel_button = QPushButton("Cancel")
self.cancel_button.clicked.connect(self.cancel_binding)
self.cancel_button.setVisible(False)
self.status_layout.addWidget(self.cancel_button)
main_layout.addLayout(self.status_layout)
main_widget.setLayout(main_layout)
self.setCentralWidget(main_widget)
def create_files_tab(self):
widget = QWidget()
layout = QVBoxLayout()
select_button = QPushButton("Select Files")
select_button.clicked.connect(self.select_files)
layout.addWidget(select_button)
self.file_list = QListWidget()
self.file_list.setStyleSheet("QListWidget::item { padding: 5px; }")
layout.addWidget(self.file_list)
remove_button = QPushButton("Remove Selected File")
remove_button.clicked.connect(self.remove_file)
layout.addWidget(remove_button)
output_layout = QHBoxLayout()
output_label = QLabel("Output File:")
self.output_edit = QLabel("No output file selected")
output_browse = QPushButton("Browse")
output_browse.clicked.connect(self.browse_output)
output_layout.addWidget(output_label)
output_layout.addWidget(self.output_edit)
output_layout.addWidget(output_browse)
layout.addLayout(output_layout)
widget.setLayout(layout)
return widget
def create_icon_tab(self):
widget = QWidget()
layout = QVBoxLayout()
select_icon_button = QPushButton("Browse Icons")
select_icon_button.clicked.connect(self.browse_icons)
layout.addWidget(select_icon_button)
self.icon_label = QLabel("No icon selected (default app icon will be used)")
self.icon_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(self.icon_label)
widget.setLayout(layout)
return widget
def create_log_tab(self):
widget = QWidget()
layout = QVBoxLayout()
self.log_display = QTextEdit()
self.log_display.setReadOnly(True)
layout.addWidget(self.log_display)
widget.setLayout(layout)
return widget
def select_files(self):
files, _ = QFileDialog.getOpenFileNames(self, "Select Files")
self.selected_files.extend(files)
self.update_file_list()
def remove_file(self):
current_item = self.file_list.currentItem()
if current_item:
file_path = current_item.text()
self.selected_files.remove(file_path)
self.update_file_list()
def update_file_list(self):
self.file_list.clear()
for file in self.selected_files:
item = QListWidgetItem(QIcon(resource_path("file_icon.png")), file)
self.file_list.addItem(item)
def browse_icons(self):
icon_browser = IconBrowser(self)
if icon_browser.exec() == QDialog.DialogCode.Accepted:
self.icon_file = icon_browser.selected_icon
self.update_icon_display()
def update_icon_display(self):
if self.icon_file:
self.icon_label.setText(f"Selected icon: {os.path.basename(self.icon_file)}")
icon_pixmap = QPixmap(self.icon_file)
if not icon_pixmap.isNull():
icon_pixmap = icon_pixmap.scaled(32, 32, Qt.AspectRatioMode.KeepAspectRatio)
self.icon_label.setPixmap(icon_pixmap)
else:
self.icon_label.setText(f"Selected icon: {os.path.basename(self.icon_file)} (Preview not available)")
else:
self.icon_label.setText("No icon selected (default app icon will be used)")
self.icon_label.setPixmap(QPixmap())
def browse_output(self):
file_name, _ = QFileDialog.getSaveFileName(self, "Save Bound File", "", "Executable (*.exe)")
if file_name:
self.output_edit.setText(file_name)
self.output_file = file_name
def bind_files(self):
if len(self.selected_files) < 2:
QMessageBox.warning(self, "Warning", "Please select at least two files to bind.")
return
if not self.output_file:
QMessageBox.warning(self, "Warning", "Please specify an output file.")
return
self.progress_bar.setVisible(True)
self.cancel_button.setVisible(True)
self.log_display.clear()
icon_to_use = self.icon_file if self.icon_file else self.default_icon
self.binder_thread = BinderThread(self.selected_files, self.output_file, icon_to_use)
self.binder_thread.progress.connect(self.update_progress)
self.binder_thread.log.connect(self.update_log)
self.binder_thread.finished.connect(self.binding_finished)
self.binder_thread.start()
def update_progress(self, value):
self.progress_bar.setValue(value)
def update_log(self, message):
self.log_display.append(message)
self.tabs.setCurrentIndex(2) # Switch to Log tab
def binding_finished(self):
self.progress_bar.setVisible(False)
self.cancel_button.setVisible(False)
if not self.binder_thread.cancelled:
QMessageBox.information(self, "Success", "Bound file created successfully!")
else:
QMessageBox.information(self, "Cancelled", "File binding process was cancelled.")
def cancel_binding(self):
if self.binder_thread and self.binder_thread.isRunning():
self.binder_thread.cancel()
self.log_display.append("Cancelling binding process...")
def show_about(self):
about_dialog = AboutDialog(self)
about_dialog.exec()
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setStyle("Fusion")
binder = FileBinder()
binder.show()
sys.exit(app.exec())