forked from bocaletto-luca/SDFormatter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdFormatterGUI.py
More file actions
636 lines (542 loc) · 22.1 KB
/
sdFormatterGUI.py
File metadata and controls
636 lines (542 loc) · 22.1 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
import sys
import os
import json
import ctypes
import subprocess
import shutil
from dataclasses import dataclass
from typing import List, Dict, Any, Optional
from PySide6.QtCore import Qt, QThread, Signal
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
QTableWidget, QTableWidgetItem, QLabel, QLineEdit, QComboBox, QCheckBox,
QTextEdit, QMessageBox, QProgressBar, QDialog, QDialogButtonBox, QFormLayout,
QFrame
)
# =========================
# Helpers di sistema
# =========================
def is_windows() -> bool:
return os.name == "nt"
def is_admin() -> bool:
if not is_windows():
return False
try:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except Exception:
return False
def relaunch_as_admin():
if not is_windows():
return
params = " ".join([f'"{arg}"' for arg in sys.argv])
try:
ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, params, None, 1
)
sys.exit(0)
except Exception as e:
QMessageBox.critical(None, "Elevazione fallita", f"Non riesco a elevare i privilegi: {e}")
def run_powershell(ps_command: str) -> subprocess.CompletedProcess:
exe = shutil.which("powershell") or shutil.which("powershell.exe")
if not exe:
raise RuntimeError("PowerShell non trovato nel PATH.")
return subprocess.run(
[exe, "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps_command],
capture_output=True, text=True, encoding="utf-8", errors="replace"
)
def run_powershell_json(ps_command: str) -> Any:
cp = run_powershell(ps_command)
if cp.returncode != 0:
raise RuntimeError(cp.stderr.strip() or "Errore PowerShell sconosciuto.")
text = cp.stdout.strip()
if not text:
return None
try:
return json.loads(text)
except json.JSONDecodeError as e:
raise RuntimeError(f"JSON non valido da PowerShell: {e}\nOutput: {text[:1000]}")
def bytes_human(n: int) -> str:
step = 1024.0
units = ["B", "KB", "MB", "GB", "TB", "PB"]
size = float(n)
for u in units:
if size < step:
return f"{size:.1f} {u}"
size /= step
return f"{size:.1f} PB"
def cluster_bytes_from_label(label: str) -> Optional[int]:
if label.lower().startswith("auto"):
return None
num = label.split()[0]
try:
return int(num) * 1024
except Exception:
return None
# =========================
# Backend dischi
# =========================
@dataclass
class DiskInfo:
number: int
size: int
bus_type: str
friendly_name: str
is_system: bool
is_boot: bool
is_readonly: bool
partition_style: str
letters: List[str]
def list_disks() -> List[DiskInfo]:
if not is_windows():
raise RuntimeError("Questa app supporta solo Windows.")
ps = r"""
$disks = Get-Disk | Select-Object Number, Size, BusType, FriendlyName, IsSystem, IsBoot, IsReadOnly, PartitionStyle
$result = @()
foreach ($d in $disks) {
$letters = @()
try {
$letters = (Get-Partition -DiskNumber $d.Number | Where-Object { $_.DriveLetter } | Select-Object -ExpandProperty DriveLetter)
} catch {}
if ($letters -eq $null) { $letters = @() }
$obj = [PSCustomObject]@{
Number = $d.Number
Size = $d.Size
BusType = [string]$d.BusType
FriendlyName = [string]$d.FriendlyName
IsSystem = [bool]$d.IsSystem
IsBoot = [bool]$d.IsBoot
IsReadOnly = [bool]$d.IsReadOnly
PartitionStyle = [string]$d.PartitionStyle
Letters = $letters
}
$result += $obj
}
$result | ConvertTo-Json -Depth 4
"""
data = run_powershell_json(ps)
if data is None:
return []
if isinstance(data, dict):
data = [data]
disks: List[DiskInfo] = []
for d in data:
disks.append(DiskInfo(
number=int(d.get("Number")),
size=int(d.get("Size") or 0),
bus_type=str(d.get("BusType") or ""),
friendly_name=str(d.get("FriendlyName") or ""),
is_system=bool(d.get("IsSystem")),
is_boot=bool(d.get("IsBoot")),
is_readonly=bool(d.get("IsReadOnly")),
partition_style=str(d.get("PartitionStyle") or ""),
letters=list(d.get("Letters") or [])
))
return disks
# =========================
# Worker di formattazione
# =========================
class FormatWorker(QThread):
progress = Signal(str)
step = Signal(int)
finished = Signal(dict)
failed = Signal(str)
def __init__(self, args: Dict[str, Any]):
super().__init__()
self.args = args
self._cancelled = False
def cancel(self):
self._cancelled = True
def _emit(self, msg: str, pct: Optional[int] = None):
self.progress.emit(msg)
if pct is not None:
self.step.emit(pct)
def _check_cancel(self):
if self._cancelled:
raise RuntimeError("Operazione annullata dall'utente.")
def run(self):
try:
self._run_pipeline()
except Exception as e:
self.failed.emit(str(e))
def _run_pipeline(self):
dry_run: bool = self.args.get("dry_run", True)
disk: int = int(self.args["disk"])
label: str = self.args.get("label", "").strip()
fs: str = self.args.get("fs", "AUTO").upper()
quick: bool = bool(self.args.get("quick", True))
deep_clean: bool = bool(self.args.get("deep_clean", False))
cam_compat: bool = bool(self.args.get("cam_compat", False))
cluster_label: str = self.args.get("cluster_label", "Auto")
# Determina dimensione e regole AUTO
try:
size_bytes = next((d.size for d in list_disks() if d.number == disk), None)
except Exception:
size_bytes = None
if fs == "AUTO":
if size_bytes is not None and size_bytes <= 32 * 1024**3:
fs = "FAT32"
else:
fs = "exFAT"
if cam_compat:
if size_bytes is not None and size_bytes <= 32 * 1024**3:
fs = "FAT32"
cluster_bytes = 32 * 1024
else:
cluster_bytes = cluster_bytes_from_label(cluster_label)
if fs == "FAT32" and (size_bytes is None or size_bytes > 32 * 1024**3):
raise RuntimeError("FAT32 selezionato ma la capacità supera 32 GB. Usa exFAT o AUTO.")
self._emit(
f"Disco #{disk} — FS: {fs}, Etichetta: '{label}', Quick: {quick}, "
f"Pulizia profonda: {deep_clean}, Dry-run: {dry_run}", 0
)
self._check_cancel()
# Step 1: online e scrivibile
self._emit("Verifica e sblocco disco...", 10)
if not dry_run:
ps1 = f"Set-Disk -Number {disk} -IsOffline $false -IsReadOnly $false -ErrorAction Stop"
cp = run_powershell(ps1)
if cp.returncode != 0:
raise RuntimeError(cp.stderr.strip() or "Impossibile sbloccare il disco.")
self._check_cancel()
# Step 2: pulizia
if deep_clean:
self._emit("Pulizia profonda del disco (può richiedere molto tempo)...", 25)
if not dry_run:
ps2 = f"Clear-Disk -Number {disk} -RemoveData -Confirm:$false -ErrorAction Stop"
cp = run_powershell(ps2)
if cp.returncode != 0:
raise RuntimeError(cp.stderr.strip() or "Errore in Clear-Disk con rimozione dati.")
else:
self._emit("Pulizia tabella partizioni...", 25)
if not dry_run:
ps2 = f"Clear-Disk -Number {disk} -RemoveData:$false -Confirm:$false -ErrorAction Stop"
cp = run_powershell(ps2)
if cp.returncode != 0:
raise RuntimeError(cp.stderr.strip() or "Errore in Clear-Disk.")
self._check_cancel()
# Step 3: inizializzazione MBR
self._emit("Inizializzazione MBR...", 40)
if not dry_run:
ps3 = f"Initialize-Disk -Number {disk} -PartitionStyle MBR -ErrorAction Stop"
cp = run_powershell(ps3)
if cp.returncode != 0:
raise RuntimeError(cp.stderr.strip() or "Errore in Initialize-Disk.")
self._check_cancel()
# Step 4: partizione e lettera
self._emit("Creazione partizione primaria e assegnazione lettera...", 55)
drive_letter = "X"
if not dry_run:
ps4 = f"(New-Partition -DiskNumber {disk} -UseMaximumSize -AssignDriveLetter -ErrorAction Stop).DriveLetter"
cp = run_powershell(ps4)
if cp.returncode != 0:
raise RuntimeError(cp.stderr.strip() or "Errore in New-Partition.")
drive_letter = (cp.stdout.strip() or "X").replace(":", "")
if len(drive_letter) != 1:
raise RuntimeError(f"Lettera unità non valida: '{drive_letter}'")
else:
drive_letter = "Z"
self._check_cancel()
# Step 5: format
self._emit(f"Formattazione {fs} sulla lettera {drive_letter}: ...", 80)
if not dry_run:
full_flag = "$true" if not quick else "$false"
label_param = f'-NewFileSystemLabel "{label}"' if label else ""
aus_param = f"-AllocationUnitSize {cluster_bytes}" if cluster_bytes else ""
ps5 = f'Format-Volume -DriveLetter {drive_letter} -FileSystem {fs} {label_param} {aus_param} -Full:{full_flag} -Force -Confirm:$false -ErrorAction Stop'
cp = run_powershell(ps5)
if cp.returncode != 0:
raise RuntimeError(cp.stderr.strip() or "Errore in Format-Volume.")
self._check_cancel()
self._emit("Operazione completata.", 100)
self.finished.emit({
"status": "OK",
"disk": disk,
"fs": fs,
"label": label,
"drive_letter": drive_letter,
"dry_run": dry_run
})
# =========================
# Dialog di conferma
# =========================
class ConfirmDialog(QDialog):
def __init__(self, parent, disk_number: int, summary_text: str):
super().__init__(parent)
self.setWindowTitle("Conferma formattazione")
self.setModal(True)
self.setMinimumWidth(520)
layout = QVBoxLayout(self)
info = QLabel(summary_text)
info.setWordWrap(True)
info.setStyleSheet("QLabel { color: #444; }")
layout.addWidget(info)
layout.addWidget(self._hline())
form = QFormLayout()
self.code_label = QLabel(f"Scrivi esattamente: CONFIRM-{disk_number}")
self.code_edit = QLineEdit()
self.code_edit.setPlaceholderText(f"CONFIRM-{disk_number}")
form.addRow(self.code_label, self.code_edit)
layout.addLayout(form)
layout.addWidget(self._hline())
self.buttons = QDialogButtonBox(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
self.buttons.button(QDialogButtonBox.Ok).setText("Conferma")
self.buttons.button(QDialogButtonBox.Cancel).setText("Annulla")
self.buttons.accepted.connect(self._on_ok)
self.buttons.rejected.connect(self.reject)
layout.addWidget(self.buttons)
def _hline(self):
line = QFrame()
line.setFrameShape(QFrame.HLine)
line.setFrameShadow(QFrame.Sunken)
return line
def _on_ok(self):
if self.code_edit.text().strip() == self.code_label.text().split(":")[-1].strip():
self.accept()
else:
QMessageBox.warning(self, "Conferma errata", "Il testo inserito non corrisponde. Ricontrolla e riprova.")
# =========================
# Interfaccia principale
# =========================
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("SD Formatter Pro — GUI")
self.resize(1000, 700)
self.worker: Optional[FormatWorker] = None
self._disks: List[DiskInfo] = []
root = QWidget()
self.setCentralWidget(root)
main = QVBoxLayout(root)
# Banner admin
self.admin_banner = QLabel("")
self.admin_banner.setWordWrap(True)
self.admin_banner.setStyleSheet("QLabel { background:#FFF3CD; color:#7A5E00; border:1px solid #FFECB5; padding:8px; }")
main.addWidget(self.admin_banner)
# Tabella dischi
self.table = QTableWidget(0, 8)
self.table.setHorizontalHeaderLabels([
"#", "Capacità", "Bus", "Nome", "Lettere", "Sistema", "Boot", "Sola lettura"
])
self.table.setSelectionBehavior(self.table.SelectRows)
self.table.setEditTriggers(self.table.NoEditTriggers)
main.addWidget(self.table)
# Opzioni
opts = QHBoxLayout()
self.label_edit = QLineEdit()
self.label_edit.setPlaceholderText("Etichetta volume (opzionale)")
self.fs_combo = QComboBox()
self.fs_combo.addItems(["AUTO", "FAT32", "exFAT", "NTFS"])
self.quick_check = QCheckBox("Quick format")
self.quick_check.setChecked(True)
self.deep_clean_check = QCheckBox("Pulizia profonda")
self.cam_check = QCheckBox("Compatibilità fotocamere")
self.cluster_combo = QComboBox()
self.cluster_combo.addItems(["Auto", "4 KB", "8 KB", "16 KB", "32 KB", "64 KB", "128 KB", "256 KB", "512 KB", "1024 KB"])
self.cluster_combo.setCurrentText("Auto")
self.dry_run_check = QCheckBox("Modalità prova (dry-run)")
self.dry_run_check.setChecked(True)
opts.addWidget(QLabel("Etichetta:"))
opts.addWidget(self.label_edit, 2)
opts.addWidget(QLabel("File system:"))
opts.addWidget(self.fs_combo)
opts.addWidget(QLabel("Cluster:"))
opts.addWidget(self.cluster_combo)
opts.addWidget(self.quick_check)
opts.addWidget(self.deep_clean_check)
opts.addWidget(self.cam_check)
opts.addWidget(self.dry_run_check)
main.addLayout(opts)
# Bottoni
btns = QHBoxLayout()
self.refresh_btn = QPushButton("Aggiorna")
self.format_btn = QPushButton("Formatta")
self.cancel_btn = QPushButton("Annulla")
self.cancel_btn.setEnabled(False)
self.elevate_btn = QPushButton("Riavvia come amministratore")
btns.addWidget(self.refresh_btn)
btns.addWidget(self.format_btn)
btns.addWidget(self.cancel_btn)
btns.addStretch(1)
btns.addWidget(self.elevate_btn)
main.addLayout(btns)
# Log + progresso
self.log = QTextEdit()
self.log.setReadOnly(True)
main.addWidget(self.log)
self.progress = QProgressBar()
self.progress.setRange(0, 100)
self.progress.setValue(0)
main.addWidget(self.progress)
# Segnali
self.refresh_btn.clicked.connect(self.load_disks)
self.format_btn.clicked.connect(self.on_format)
self.cancel_btn.clicked.connect(self.on_cancel)
self.elevate_btn.clicked.connect(relaunch_as_admin)
self.fs_combo.currentTextChanged.connect(self.on_fs_changed)
self.cam_check.stateChanged.connect(self.on_cam_changed)
self.update_admin_banner()
self.load_disks()
# -------- Stato UI
def update_admin_banner(self):
if not is_windows():
self.admin_banner.setText("Questa applicazione funziona solo su Windows.")
self.elevate_btn.setEnabled(False)
self.format_btn.setEnabled(False)
return
if is_admin():
self.admin_banner.setText("Esecuzione con privilegi amministrativi.")
self.elevate_btn.setEnabled(False)
else:
self.admin_banner.setText("Privilegi amministrativi mancanti. Per formattare è necessario riavviare come amministratore.")
self.elevate_btn.setEnabled(True)
def set_busy(self, busy: bool):
self.refresh_btn.setEnabled(not busy)
self.format_btn.setEnabled(not busy)
self.cancel_btn.setEnabled(busy)
self.elevate_btn.setEnabled(not busy)
self.table.setEnabled(not busy)
# -------- Dischi
def load_disks(self):
try:
self._disks = list_disks()
except Exception as e:
QMessageBox.critical(self, "Errore", str(e))
self._disks = []
self.table.setRowCount(0)
for d in self._disks:
row = self.table.rowCount()
self.table.insertRow(row)
self.table.setItem(row, 0, QTableWidgetItem(str(d.number)))
self.table.setItem(row, 1, QTableWidgetItem(bytes_human(d.size)))
self.table.setItem(row, 2, QTableWidgetItem(d.bus_type))
self.table.setItem(row, 3, QTableWidgetItem(d.friendly_name))
self.table.setItem(row, 4, QTableWidgetItem(",".join(str(x) for x in d.letters)))
self.table.setItem(row, 5, QTableWidgetItem("Sì" if d.is_system else "No"))
self.table.setItem(row, 6, QTableWidgetItem("Sì" if d.is_boot else "No"))
self.table.setItem(row, 7, QTableWidgetItem("Sì" if d.is_readonly else "No"))
if d.is_system or d.is_boot or d.is_readonly:
for c in range(self.table.columnCount()):
item = self.table.item(row, c)
if item:
item.setFlags(item.flags() & ~Qt.ItemIsSelectable)
item.setForeground(Qt.gray)
self.table.resizeColumnsToContents()
def selected_disk(self) -> Optional[DiskInfo]:
row = self.table.currentRow()
if row < 0 or row >= len(self._disks):
return None
return self._disks[row]
# -------- Opzioni/UX
def on_fs_changed(self):
fs = self.fs_combo.currentText().upper()
if fs == "NTFS":
self.cam_check.setChecked(False)
self.cam_check.setEnabled(False)
else:
self.cam_check.setEnabled(True)
def on_cam_changed(self):
if self.cam_check.isChecked():
self.cluster_combo.setCurrentText("32 KB")
self.cluster_combo.setEnabled(False)
else:
self.cluster_combo.setEnabled(True)
# -------- Azioni
def on_format(self):
if not is_admin():
res = QMessageBox.question(
self, "Privilegi richiesti",
"Per formattare sono necessari privilegi amministrativi. Vuoi riavviare ora come amministratore?",
QMessageBox.Yes | QMessageBox.No
)
if res == QMessageBox.Yes:
relaunch_as_admin()
return
d = self.selected_disk()
if not d:
QMessageBox.warning(self, "Nessun disco", "Seleziona un disco dalla tabella.")
return
if d.is_system or d.is_boot:
QMessageBox.critical(self, "Bloccato", "Non è consentito formattare dischi di sistema o di boot.")
return
if d.is_readonly:
QMessageBox.critical(self, "Sola lettura", "Il disco risulta in sola lettura. Rimuovi la protezione e riprova.")
return
label = self.label_edit.text().strip()
fs = self.fs_combo.currentText().upper()
quick = self.quick_check.isChecked()
deep_clean = self.deep_clean_check.isChecked()
cam_compat = self.cam_check.isChecked()
cluster_label = self.cluster_combo.currentText()
dry_run = self.dry_run_check.isChecked()
if fs == "FAT32" and d.size > 32 * 1024**3:
QMessageBox.warning(self, "Limite FAT32", "FAT32 supportato fino a circa 32 GB. Seleziona exFAT o AUTO.")
return
summary = (
f"Stai per formattare il disco #{d.number}\n"
f"- Capacità: {bytes_human(d.size)}\n"
f"- Bus: {d.bus_type}\n"
f"- Nome: {d.friendly_name}\n"
f"- File system: {fs}\n"
f"- Etichetta: '{label}'\n"
f"- Quick: {quick}\n"
f"- Pulizia profonda: {deep_clean}\n"
f"- Compatibilità fotocamere: {cam_compat}\n"
f"- Cluster: {cluster_label}\n"
f"- Modalità prova (dry-run): {dry_run}\n\n"
"ATTENZIONE: tutti i dati sul disco verranno eliminati."
)
dlg = ConfirmDialog(self, d.number, summary)
if dlg.exec() != QDialog.Accepted:
return
args = {
"disk": d.number,
"label": label,
"fs": fs,
"quick": quick,
"deep_clean": deep_clean,
"cam_compat": cam_compat,
"cluster_label": cluster_label,
"dry_run": dry_run
}
self.log.clear()
self.progress.setValue(0)
self.set_busy(True)
self.worker = FormatWorker(args)
self.worker.progress.connect(self.on_progress)
self.worker.step.connect(self.progress.setValue)
self.worker.finished.connect(self.on_finished)
self.worker.failed.connect(self.on_failed)
self.worker.start()
def on_cancel(self):
if self.worker and self.worker.isRunning():
self.worker.cancel()
self.cancel_btn.setEnabled(False)
self.log.append("Richiesta di annullamento inviata...")
# -------- Callback worker
def on_progress(self, msg: str):
self.log.append(msg)
def on_finished(self, result: Dict[str, Any]):
self.set_busy(False)
self.progress.setValue(100)
self.log.append(f"Completato: {json.dumps(result, ensure_ascii=False)}")
if result.get("status") == "OK":
dry = result.get("dry_run", False)
if dry:
QMessageBox.information(self, "Simulazione completata", "Dry-run concluso con successo. Disattiva la modalità prova per formattare realmente.")
else:
QMessageBox.information(self, "Successo", "Formattazione completata.")
self.load_disks()
else:
QMessageBox.critical(self, "Errore", f"Operazione non riuscita:\n{result}")
def on_failed(self, err: str):
self.set_busy(False)
self.log.append(f"Errore: {err}")
QMessageBox.critical(self, "Errore", err)
# =========================
# Avvio applicazione
# =========================
if __name__ == "__main__":
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec())