-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtry22.py
More file actions
4123 lines (3448 loc) · 166 KB
/
try22.py
File metadata and controls
4123 lines (3448 loc) · 166 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
"""
FORZEOS Enhanced - Complete GUI Operating System v7.0
A full-featured desktop operating system written in Python with tkinter
Optimized for Android/Pydroid 3 with mobile-friendly interface
Enhanced Features:
- Fixed wallpaper system with proper PIL image handling
- Chess bot with minimax algorithm
- 20+ new applications and tools
- Multi-language support (TR, EN, AR, AZ, RU)
- Theme engine with customizable colors
- Widget system for desktop
- Plugin support
- Session management
- Notification system
- And much more...
"""
import tkinter as tk
from tkinter import ttk, messagebox, filedialog, simpledialog, colorchooser
import os
import sys
import json
import hashlib
import datetime
import threading
import subprocess
import webbrowser
import urllib.request
import socket
import random
import math
import shutil
import sqlite3
import zipfile
import base64
import io
import time
import copy
# Advanced features imports with fallbacks
try:
import fitz # PyMuPDF
PDF_AVAILABLE = True
except ImportError:
PDF_AVAILABLE = False
try:
from PIL import Image, ImageTk, ImageDraw
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
try:
import pygame
PYGAME_AVAILABLE = True
pygame.mixer.init()
except ImportError:
PYGAME_AVAILABLE = False
try:
from cryptography.fernet import Fernet
CRYPTO_AVAILABLE = True
except ImportError:
CRYPTO_AVAILABLE = False
try:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
MATPLOTLIB_AVAILABLE = True
except ImportError:
MATPLOTLIB_AVAILABLE = False
try:
import qrcode
QR_AVAILABLE = True
except ImportError:
QR_AVAILABLE = False
try:
import requests
REQUESTS_AVAILABLE = True
except ImportError:
REQUESTS_AVAILABLE = False
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
PSUTIL_AVAILABLE = False
# Language translations
TRANSLATIONS = {
'EN': {
'welcome': 'Welcome to FORZEOS',
'login': 'Login',
'username': 'Username',
'password': 'Password',
'settings': 'Settings',
'file_manager': 'File Manager',
'calculator': 'Calculator',
'notepad': 'Notepad',
'terminal': 'Terminal',
'paint': 'Paint',
'games': 'Games',
'tools': 'Tools',
'logout': 'Logout',
'shutdown': 'Shutdown',
'error': 'Error',
'success': 'Success',
'cancel': 'Cancel',
'ok': 'OK',
'save': 'Save',
'open': 'Open',
'new': 'New',
'delete': 'Delete',
'copy': 'Copy',
'paste': 'Paste',
'cut': 'Cut'
},
'TR': {
'welcome': 'FORZEOS\'a Hoşgeldiniz',
'login': 'Giriş',
'username': 'Kullanıcı Adı',
'password': 'Şifre',
'settings': 'Ayarlar',
'file_manager': 'Dosya Yöneticisi',
'calculator': 'Hesap Makinesi',
'notepad': 'Not Defteri',
'terminal': 'Terminal',
'paint': 'Boyama',
'games': 'Oyunlar',
'tools': 'Araçlar',
'logout': 'Çıkış',
'shutdown': 'Kapat',
'error': 'Hata',
'success': 'Başarılı',
'cancel': 'İptal',
'ok': 'Tamam',
'save': 'Kaydet',
'open': 'Aç',
'new': 'Yeni',
'delete': 'Sil',
'copy': 'Kopyala',
'paste': 'Yapıştır',
'cut': 'Kes'
},
'AR': {
'welcome': 'مرحباً بك في FORZEOS',
'login': 'تسجيل الدخول',
'username': 'اسم المستخدم',
'password': 'كلمة المرور',
'settings': 'الإعدادات',
'file_manager': 'مدير الملفات',
'calculator': 'الآلة الحاسبة',
'notepad': 'دفتر الملاحظات',
'terminal': 'الطرفية',
'paint': 'الرسام',
'games': 'الألعاب',
'tools': 'الأدوات',
'logout': 'تسجيل الخروج',
'shutdown': 'إغلاق',
'error': 'خطأ',
'success': 'نجح',
'cancel': 'إلغاء',
'ok': 'موافق',
'save': 'حفظ',
'open': 'فتح',
'new': 'جديد',
'delete': 'حذف',
'copy': 'نسخ',
'paste': 'لصق',
'cut': 'قص'
}
}
class NotificationSystem:
"""System notification manager"""
def __init__(self, parent):
self.parent = parent
self.notifications = []
def show_notification(self, title, message, duration=3000, type="info"):
"""Show a notification popup"""
try:
notification = tk.Toplevel(self.parent)
notification.title(title)
notification.geometry("300x80")
notification.resizable(False, False)
# Position at top-right
x = notification.winfo_screenwidth() - 320
y = 20 + len(self.notifications) * 90
notification.geometry(f"300x80+{x}+{y}")
# Style based on type
colors = {
'info': '#3498DB',
'success': '#27AE60',
'warning': '#F39C12',
'error': '#E74C3C'
}
bg_color = colors.get(type, '#3498DB')
notification.configure(bg=bg_color)
# Content
tk.Label(notification, text=title, bg=bg_color, fg='white',
font=('Arial', 12, 'bold')).pack(pady=5)
tk.Label(notification, text=message, bg=bg_color, fg='white',
font=('Arial', 10), wraplength=280).pack()
# Auto-close
notification.after(duration, notification.destroy)
self.notifications.append(notification)
# Remove from list when destroyed
def on_destroy():
if notification in self.notifications:
self.notifications.remove(notification)
notification.bind('<Destroy>', lambda e: on_destroy())
except Exception as e:
print(f"Notification error: {e}")
class ChessBot:
"""Minimax algorithm chess bot"""
def __init__(self, depth=3):
self.depth = depth
self.piece_values = {
'pawn': 1, 'knight': 3, 'bishop': 3,
'rook': 5, 'queen': 9, 'king': 100
}
def evaluate_board(self, board):
"""Simple board evaluation"""
score = 0
for i in range(8):
for j in range(8):
piece = board[i][j]
if piece:
value = self.piece_values.get(piece.lower(), 0)
if piece.isupper(): # White pieces
score += value
else: # Black pieces
score -= value
return score
def minimax(self, board, depth, maximizing_player, alpha=-float('inf'), beta=float('inf')):
"""Minimax algorithm with alpha-beta pruning"""
if depth == 0:
return self.evaluate_board(board)
if maximizing_player:
max_eval = -float('inf')
for move in self.get_all_moves(board, True):
new_board = self.make_move(board, move)
eval_score = self.minimax(new_board, depth-1, False, alpha, beta)
max_eval = max(max_eval, eval_score)
alpha = max(alpha, eval_score)
if beta <= alpha:
break
return max_eval
else:
min_eval = float('inf')
for move in self.get_all_moves(board, False):
new_board = self.make_move(board, move)
eval_score = self.minimax(new_board, depth-1, True, alpha, beta)
min_eval = min(min_eval, eval_score)
beta = min(beta, eval_score)
if beta <= alpha:
break
return min_eval
def get_best_move(self, board, is_white):
"""Get the best move for the current player"""
best_move = None
best_value = -float('inf') if is_white else float('inf')
for move in self.get_all_moves(board, is_white):
new_board = self.make_move(board, move)
move_value = self.minimax(new_board, self.depth-1, not is_white)
if is_white and move_value > best_value:
best_value = move_value
best_move = move
elif not is_white and move_value < best_value:
best_value = move_value
best_move = move
return best_move
def get_all_moves(self, board, is_white):
"""Get all possible moves for the current player"""
moves = []
for i in range(8):
for j in range(8):
piece = board[i][j]
if piece and ((is_white and piece.isupper()) or (not is_white and piece.islower())):
moves.extend(self.get_piece_moves(board, i, j))
return moves
def get_piece_moves(self, board, row, col):
"""Get possible moves for a piece at given position"""
piece = board[row][col].lower()
moves = []
if piece == 'pawn':
moves = self.get_pawn_moves(board, row, col)
elif piece == 'rook':
moves = self.get_rook_moves(board, row, col)
elif piece == 'knight':
moves = self.get_knight_moves(board, row, col)
elif piece == 'bishop':
moves = self.get_bishop_moves(board, row, col)
elif piece == 'queen':
moves = self.get_queen_moves(board, row, col)
elif piece == 'king':
moves = self.get_king_moves(board, row, col)
return moves
def get_pawn_moves(self, board, row, col):
"""Get pawn moves"""
moves = []
piece = board[row][col]
is_white = piece.isupper()
direction = -1 if is_white else 1
# Forward move
new_row = row + direction
if 0 <= new_row < 8 and not board[new_row][col]:
moves.append((row, col, new_row, col))
# Double move from starting position
if (is_white and row == 6) or (not is_white and row == 1):
if not board[new_row + direction][col]:
moves.append((row, col, new_row + direction, col))
# Captures
for dc in [-1, 1]:
new_col = col + dc
if 0 <= new_row < 8 and 0 <= new_col < 8:
target = board[new_row][new_col]
if target and ((is_white and target.islower()) or (not is_white and target.isupper())):
moves.append((row, col, new_row, new_col))
return moves
def get_rook_moves(self, board, row, col):
"""Get rook moves"""
moves = []
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dr, dc in directions:
for i in range(1, 8):
new_row, new_col = row + dr * i, col + dc * i
if not (0 <= new_row < 8 and 0 <= new_col < 8):
break
target = board[new_row][new_col]
if not target:
moves.append((row, col, new_row, new_col))
else:
if self.is_enemy_piece(board[row][col], target):
moves.append((row, col, new_row, new_col))
break
return moves
def get_knight_moves(self, board, row, col):
"""Get knight moves"""
moves = []
knight_moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]
for dr, dc in knight_moves:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < 8 and 0 <= new_col < 8:
target = board[new_row][new_col]
if not target or self.is_enemy_piece(board[row][col], target):
moves.append((row, col, new_row, new_col))
return moves
def get_bishop_moves(self, board, row, col):
"""Get bishop moves"""
moves = []
directions = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
for dr, dc in directions:
for i in range(1, 8):
new_row, new_col = row + dr * i, col + dc * i
if not (0 <= new_row < 8 and 0 <= new_col < 8):
break
target = board[new_row][new_col]
if not target:
moves.append((row, col, new_row, new_col))
else:
if self.is_enemy_piece(board[row][col], target):
moves.append((row, col, new_row, new_col))
break
return moves
def get_queen_moves(self, board, row, col):
"""Get queen moves (combination of rook and bishop)"""
return self.get_rook_moves(board, row, col) + self.get_bishop_moves(board, row, col)
def get_king_moves(self, board, row, col):
"""Get king moves"""
moves = []
directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < 8 and 0 <= new_col < 8:
target = board[new_row][new_col]
if not target or self.is_enemy_piece(board[row][col], target):
moves.append((row, col, new_row, new_col))
return moves
def is_enemy_piece(self, piece1, piece2):
"""Check if two pieces are enemies"""
return (piece1.isupper() and piece2.islower()) or (piece1.islower() and piece2.isupper())
def make_move(self, board, move):
"""Make a move on the board (returns new board)"""
new_board = [row[:] for row in board]
from_row, from_col, to_row, to_col = move
new_board[to_row][to_col] = new_board[from_row][from_col]
new_board[from_row][from_col] = None
return new_board
class DatabaseManager:
"""SQLite database manager for system data"""
def __init__(self, db_path="forzeos.db"):
self.db_path = db_path
self.init_database()
def init_database(self):
"""Initialize database tables"""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# System logs table
cursor.execute('''
CREATE TABLE IF NOT EXISTS system_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
user TEXT NOT NULL,
action TEXT NOT NULL,
details TEXT,
app TEXT
)
''')
# Password vault table
cursor.execute('''
CREATE TABLE IF NOT EXISTS password_vault (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user TEXT NOT NULL,
title TEXT NOT NULL,
username TEXT,
password TEXT NOT NULL,
notes TEXT,
category TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
''')
# Notes table
cursor.execute('''
CREATE TABLE IF NOT EXISTS secure_notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user TEXT NOT NULL,
title TEXT NOT NULL,
content TEXT NOT NULL,
category TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
''')
# App store table
cursor.execute('''
CREATE TABLE IF NOT EXISTS app_store (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
version TEXT,
download_url TEXT,
icon_url TEXT,
category TEXT,
rating REAL,
downloads INTEGER
)
''')
conn.commit()
conn.close()
except Exception as e:
print(f"Database initialization error: {e}")
def log_action(self, user, action, details="", app="System"):
"""Log system action"""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
timestamp = datetime.datetime.now().isoformat()
cursor.execute('''
INSERT INTO system_logs (timestamp, user, action, details, app)
VALUES (?, ?, ?, ?, ?)
''', (timestamp, user, action, details, app))
conn.commit()
conn.close()
except Exception as e:
print(f"Logging error: {e}")
def get_logs(self, user=None, limit=100):
"""Get system logs"""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
if user:
cursor.execute('''
SELECT * FROM system_logs WHERE user = ?
ORDER BY timestamp DESC LIMIT ?
''', (user, limit))
else:
cursor.execute('''
SELECT * FROM system_logs
ORDER BY timestamp DESC LIMIT ?
''', (limit,))
logs = cursor.fetchall()
conn.close()
return logs
except Exception as e:
print(f"Get logs error: {e}")
return []
class ForzeOS:
def __init__(self):
self.root = tk.Tk()
self.root.title("FORZEOS Enhanced - Advanced Desktop OS v7.0")
# Get screen dimensions
self.screen_width = self.root.winfo_screenwidth()
self.screen_height = self.root.winfo_screenheight()
# Detect orientation
self.is_horizontal = self.screen_width > self.screen_height
# Try fullscreen mode
try:
self.root.attributes('-fullscreen', True)
except:
self.root.geometry(f"{self.screen_width}x{self.screen_height}")
# System variables
self.current_user = None
self.current_language = 'EN'
self.running_apps = {}
self.windows = {}
self.desktop_icons = []
self.widgets = []
self.plugins = []
self.open_sessions = {}
# File paths
self.config_file = "forzeos_config_v7.json"
self.file_system_root = "forze_users"
self.plugins_dir = "forze_plugins"
self.themes_dir = "forze_themes"
# Initialize systems
self.notification_system = NotificationSystem(self.root)
self.db = DatabaseManager()
self.chess_bot = ChessBot()
# Color schemes and themes
self.themes = {
'dark': {
'bg': '#2C3E50',
'fg': '#ECF0F1',
'accent': '#3498DB',
'success': '#27AE60',
'warning': '#F39C12',
'danger': '#E74C3C',
'dark': '#34495E',
'light': '#BDC3C7'
},
'light': {
'bg': '#ECF0F1',
'fg': '#2C3E50',
'accent': '#3498DB',
'success': '#27AE60',
'warning': '#F39C12',
'danger': '#E74C3C',
'dark': '#BDC3C7',
'light': '#FFFFFF'
},
'blue': {
'bg': '#1E3A8A',
'fg': '#F1F5F9',
'accent': '#3B82F6',
'success': '#10B981',
'warning': '#F59E0B',
'danger': '#EF4444',
'dark': '#1E40AF',
'light': '#DBEAFE'
}
}
self.current_theme = 'dark'
self.colors = self.themes[self.current_theme]
# Initialize system
self.init_file_system()
self.load_config()
# Show login first
self.root.withdraw()
self.show_login()
def init_file_system(self):
"""Initialize the file system structure"""
directories = [
self.file_system_root,
self.plugins_dir,
self.themes_dir,
os.path.join(self.file_system_root, "shared"),
os.path.join(self.file_system_root, "shared", "documents"),
os.path.join(self.file_system_root, "shared", "images"),
os.path.join(self.file_system_root, "shared", "music"),
os.path.join(self.file_system_root, "shared", "videos"),
os.path.join(self.file_system_root, "shared", "downloads")
]
for directory in directories:
if not os.path.exists(directory):
os.makedirs(directory)
def get_text(self, key):
"""Get translated text"""
return TRANSLATIONS.get(self.current_language, TRANSLATIONS['EN']).get(key, key)
def change_language(self, lang):
"""Change system language"""
if lang in TRANSLATIONS:
self.current_language = lang
self.config['settings']['language'] = lang
self.save_config()
self.notification_system.show_notification(
"Language Changed",
f"Language changed to {lang}",
type="success"
)
def change_theme(self, theme_name):
"""Change system theme"""
if theme_name in self.themes:
self.current_theme = theme_name
self.colors = self.themes[theme_name]
self.config['settings']['theme'] = theme_name
self.save_config()
self.update_theme()
self.notification_system.show_notification(
"Theme Changed",
f"Theme changed to {theme_name}",
type="success"
)
def update_theme(self):
"""Update all UI elements with new theme"""
try:
# Update root window
self.root.configure(bg=self.colors['bg'])
# Update desktop
if hasattr(self, 'desktop'):
self.desktop.configure(bg=self.colors['bg'])
# Update taskbar
if hasattr(self, 'taskbar'):
self.taskbar.configure(bg=self.colors['dark'])
self.forze_btn.configure(bg=self.colors['accent'])
self.system_label.configure(bg=self.colors['dark'], fg=self.colors['fg'])
self.clock_label.configure(bg=self.colors['dark'], fg=self.colors['fg'])
# Update desktop icons
for icon in self.desktop_icons:
icon.configure(bg=self.colors['light'])
for child in icon.winfo_children():
if isinstance(child, tk.Button):
child.configure(bg=self.colors['light'])
except Exception as e:
print(f"Theme update error: {e}")
def load_config(self):
"""Load system configuration"""
if os.path.exists(self.config_file):
try:
with open(self.config_file, 'r', encoding='utf-8') as f:
self.config = json.load(f)
except Exception as e:
self.config = self.get_default_config()
else:
self.config = self.get_default_config()
self.save_config()
# Apply loaded settings
self.current_language = self.config.get('settings', {}).get('language', 'EN')
theme_name = self.config.get('settings', {}).get('theme', 'dark')
if theme_name in self.themes:
self.current_theme = theme_name
self.colors = self.themes[theme_name]
def get_default_config(self):
"""Get default system configuration"""
return {
'users': {
'admin': {
'password': hashlib.md5('Forze esp32'.encode()).hexdigest(),
'created': datetime.datetime.now().isoformat(),
'last_login': None,
'settings': {
'wallpaper': None,
'icon_size': 'medium',
'startup_apps': []
}
}
},
'settings': {
'language': 'EN',
'theme': 'dark',
'wallpaper_color': '#2C3E50',
'wallpaper_image': None,
'taskbar_position': 'bottom',
'auto_login': False,
'session_timeout': 0,
'enable_notifications': True,
'enable_sounds': True,
'icon_arrangement': 'auto',
'widget_enabled': True
},
'desktop_layout': {
'icon_positions': {},
'widgets': [],
'icon_size': 'medium'
},
'plugins': {
'enabled': [],
'available': []
}
}
def save_config(self):
"""Save system configuration"""
try:
with open(self.config_file, 'w', encoding='utf-8') as f:
json.dump(self.config, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"Config save error: {e}")
def save_session(self):
"""Save current session state"""
try:
session_data = {
'user': self.current_user,
'timestamp': datetime.datetime.now().isoformat(),
'running_apps': list(self.running_apps.keys()),
'desktop_state': {
'icon_positions': self.config.get('desktop_layout', {}).get('icon_positions', {}),
'widgets': []
}
}
session_file = f"session_{self.current_user}.json"
with open(session_file, 'w', encoding='utf-8') as f:
json.dump(session_data, f, indent=2)
except Exception as e:
print(f"Session save error: {e}")
def restore_session(self):
"""Restore previous session"""
try:
session_file = f"session_{self.current_user}.json"
if os.path.exists(session_file):
with open(session_file, 'r', encoding='utf-8') as f:
session_data = json.load(f)
# Restore running apps
for app_name in session_data.get('running_apps', []):
if hasattr(self, f'open_{app_name.lower().replace(" ", "_")}'):
threading.Thread(
target=getattr(self, f'open_{app_name.lower().replace(" ", "_")}'),
daemon=True
).start()
self.notification_system.show_notification(
"Session Restored",
"Previous session has been restored",
type="success"
)
except Exception as e:
print(f"Session restore error: {e}")
def show_login(self):
"""Show enhanced login screen"""
self.login_window = tk.Toplevel()
self.login_window.title("FORZEOS Enhanced Login")
self.login_window.geometry("450x400")
self.login_window.configure(bg=self.colors['bg'])
self.login_window.resizable(False, False)
# Center the login window
x = (self.screen_width - 450) // 2
y = (self.screen_height - 400) // 2
self.login_window.geometry(f"450x400+{x}+{y}")
# Main container
main_frame = tk.Frame(self.login_window, bg=self.colors['bg'])
main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
# Logo/Title
title_frame = tk.Frame(main_frame, bg=self.colors['bg'])
title_frame.pack(pady=20)
tk.Label(title_frame, text="FORZEOS", font=('Arial', 28, 'bold'),
bg=self.colors['bg'], fg=self.colors['accent']).pack()
tk.Label(title_frame, text="Enhanced v7.0", font=('Arial', 12),
bg=self.colors['bg'], fg=self.colors['fg']).pack()
# Login form
form_frame = tk.Frame(main_frame, bg=self.colors['bg'])
form_frame.pack(pady=20, fill=tk.X)
# Username
tk.Label(form_frame, text=self.get_text('username') + ":",
bg=self.colors['bg'], fg=self.colors['fg'],
font=('Arial', 12)).pack(anchor=tk.W, pady=(0, 5))
self.username_entry = tk.Entry(form_frame, font=('Arial', 14), width=25)
self.username_entry.pack(fill=tk.X, pady=(0, 15))
self.username_entry.insert(0, "admin")
# Password
tk.Label(form_frame, text=self.get_text('password') + ":",
bg=self.colors['bg'], fg=self.colors['fg'],
font=('Arial', 12)).pack(anchor=tk.W, pady=(0, 5))
self.password_entry = tk.Entry(form_frame, show='*', font=('Arial', 14), width=25)
self.password_entry.pack(fill=tk.X, pady=(0, 20))
# Buttons
button_frame = tk.Frame(form_frame, bg=self.colors['bg'])
button_frame.pack(fill=tk.X)
login_btn = tk.Button(button_frame, text=self.get_text('login'), command=self.login,
bg=self.colors['accent'], fg='white', font=('Arial', 14, 'bold'),
width=15, height=2, relief=tk.FLAT)
login_btn.pack(side=tk.LEFT, padx=(0, 10))
# Language selector
lang_frame = tk.Frame(main_frame, bg=self.colors['bg'])
lang_frame.pack(side=tk.BOTTOM, fill=tk.X, pady=10)
tk.Label(lang_frame, text="Language:", bg=self.colors['bg'],
fg=self.colors['fg'], font=('Arial', 10)).pack(side=tk.LEFT)
self.lang_var = tk.StringVar(value=self.current_language)
lang_menu = ttk.Combobox(lang_frame, textvariable=self.lang_var,
values=['EN', 'TR', 'AR', 'AZ', 'RU'],
state='readonly', width=10)
lang_menu.pack(side=tk.LEFT, padx=10)
lang_menu.bind('<<ComboboxSelected>>',
lambda e: self.change_language(self.lang_var.get()))
# Bind Enter key
self.login_window.bind('<Return>', lambda e: self.login())
self.password_entry.focus()
def login(self):
"""Handle user login with enhanced features"""
try:
username = self.username_entry.get().strip()
password = self.password_entry.get()
if not username or not password:
messagebox.showerror(self.get_text('error'),
"Please enter both username and password")
return
# Check credentials
if username in self.config['users']:
stored_password = self.config['users'][username]['password']
entered_password = hashlib.md5(password.encode()).hexdigest()
if stored_password == entered_password:
self.current_user = username
# Update last login
self.config['users'][username]['last_login'] = datetime.datetime.now().isoformat()
self.save_config()
# Log login
self.db.log_action(username, "Login", "User logged in successfully")
# Close login window
self.login_window.destroy()
# Create desktop
self.create_desktop()
self.root.deiconify()
# Welcome notification
self.notification_system.show_notification(
self.get_text('welcome'),
f"Welcome back, {username}!",
type="success"
)
# Restore session if available
if self.config.get('settings', {}).get('restore_session', True):
threading.Thread(target=self.restore_session, daemon=True).start()
else:
messagebox.showerror(self.get_text('error'), "Invalid password")
self.db.log_action(username, "Failed Login", "Invalid password attempt")
else:
# Create new user
response = messagebox.askyesno("New User",
f"User '{username}' not found. Create new user?")
if response:
self.create_new_user(username, password)
except Exception as e:
print(f"Login error: {e}")
messagebox.showerror(self.get_text('error'), "Login failed")
def create_new_user(self, username, password):
"""Create a new user account"""
try:
# Create user directory
user_dir = os.path.join(self.file_system_root, username)
if not os.path.exists(user_dir):
os.makedirs(user_dir)
os.makedirs(os.path.join(user_dir, "documents"))
os.makedirs(os.path.join(user_dir, "images"))
os.makedirs(os.path.join(user_dir, "downloads"))
# Add to config
self.config['users'][username] = {
'password': hashlib.md5(password.encode()).hexdigest(),
'created': datetime.datetime.now().isoformat(),
'last_login': None,
'settings': {
'wallpaper': None,
'icon_size': 'medium',
'startup_apps': []
}
}
self.save_config()
self.db.log_action(username, "Account Created", "New user account created")
messagebox.showinfo("Success", f"User '{username}' created successfully!")
except Exception as e:
print(f"User creation error: {e}")
messagebox.showerror(self.get_text('error'), "Failed to create user")
def create_desktop(self):
"""Create the enhanced desktop environment"""
# Configure main window
wallpaper_color = self.config.get('settings', {}).get('wallpaper_color', self.colors['bg'])
# Load wallpaper image if set
wallpaper_image = self.config.get('settings', {}).get('wallpaper_image')
if wallpaper_image and os.path.exists(wallpaper_image) and PIL_AVAILABLE:
try:
self.load_wallpaper(wallpaper_image)
except Exception as e:
print(f"Wallpaper load error: {e}")
self.root.configure(bg=wallpaper_color)
else:
self.root.configure(bg=wallpaper_color)
# Create desktop frame
self.desktop = tk.Frame(self.root, bg=wallpaper_color)
self.desktop.pack(fill=tk.BOTH, expand=True)
# Create taskbar