-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesktop_companion.py
More file actions
2365 lines (2196 loc) · 104 KB
/
Copy pathdesktop_companion.py
File metadata and controls
2365 lines (2196 loc) · 104 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
import os
import threading
import time
import random
import re
import tkinter as tk
from tkinter import Toplevel, Frame, Label, Entry, Text, Scrollbar, Button
try:
from PIL import Image, ImageTk
PIL_AVAILABLE = True
except Exception:
Image = None
ImageTk = None
PIL_AVAILABLE = False
# logger may not be configured yet; safe to create one earlier in file
try:
logger.warning('PIL not available: companion will use tkinter fallbacks for images')
except Exception:
pass
from typing import TYPE_CHECKING
import math
try:
import math_engine
except Exception:
math_engine = None
try:
logger.warning('math_engine module not available; math features disabled')
except Exception:
pass
# hint to analyzers but avoid importing at runtime to prevent unresolved import warnings
if TYPE_CHECKING:
# type-checker only: this helps editors like Pylance know the symbol exists
from function_art import FunctionArtWindow # type: ignore
FUNCTION_ART_AVAILABLE = False
FunctionArtWindow = None
import logging
logger = logging.getLogger(__name__)
# Assistant availability: prefer the offline enhanced assistant, fallback to the
# small rule-based assistant. Use dynamic importlib loading so static analyzers
# (Pylance) don't error when the file is present only at runtime or outside the
# current analysis root.
AssistantClass = None
try:
# Prefer the canonical modular assistant if present (assistant_ai). Fall back to
# the lightweight offline assistant (assistant_ai_offline) or older modules.
import importlib
try:
mod = importlib.import_module('assistant_ai')
AssistantClass = getattr(mod, 'AssistantAI', None)
if AssistantClass:
logger.debug("Using assistant_ai.AssistantAI as primary assistant")
except Exception:
# not available - try the offline embedded style module
try:
mod = importlib.import_module('assistant_ai_offline')
AssistantClass = getattr(mod, 'EnhancedAssistantAI', None)
if AssistantClass:
logger.debug("Using assistant_ai_offline.EnhancedAssistantAI as fallback")
except Exception:
# final attempt: older assistant_ai variant names
try:
mod2 = importlib.import_module('assistant_ai')
AssistantClass = getattr(mod2, 'EnhancedAssistantAI', getattr(mod2, 'AssistantAI', None))
if AssistantClass:
logger.debug("Using legacy assistant_ai.* as fallback")
except Exception:
AssistantClass = None
except Exception:
# best-effort: leave AssistantClass as None; runtime code will handle missing assistant
AssistantClass = None
class DesktopCompanion:
"""A small draggable desktop companion for ForzeOS.
Usage (from ForzeOS):
from desktop_companion import DesktopCompanion
self.companion = DesktopCompanion(self)
self.companion.install(x=80, y=150)
Features:
- Loads sprites from "forzeos_assets" folder using names like
companion_idle_0.png, companion_talk_0.png, etc.
- Shows a borderless Tk Toplevel with animation.
- Click to open a chat balloon (simple Entry + Text history).
- Rule-based commands mapped to ForzeOS methods (open_social_media, ...).
- Optional pyttsx3 TTS (non-blocking) if installed.
"""
ASSET_DIR = os.path.join(os.path.dirname(__file__), "forzeos_assets")
def __init__(self, forzeos_instance, size=96, fps=6):
self.forzeos = forzeos_instance
self.root = getattr(forzeos_instance, 'root', None)
if self.root is None:
raise RuntimeError("ForzeOS instance must expose a Tk root as `root` attribute")
self.size = size
self.fps = fps
self.ai_enabled = True
self._stop_anim = False
# awaiting a follow-up topic for wiki command
self._expecting_wiki_topic = False
# Prefer the host-attached assistant if available to keep session state
# centralized. Fall back to the imported AssistantClass only when needed.
host_ai = getattr(forzeos_instance, 'assistant', None) or getattr(forzeos_instance, 'ai', None)
if host_ai:
# Use host-provided assistant instance to avoid duplicate/conflicting assistants
self.ai = host_ai
else:
# No host assistant attached; instantiate the local AssistantClass if present.
if AssistantClass is not None:
try:
self.ai = AssistantClass()
except Exception:
logger.exception('Failed to instantiate AssistantClass for DesktopCompanion')
self.ai = None
else:
self.ai = None
# host open mapping placeholder (populated later)
self._host_open_map = {}
# sprite lists
self.idle_imgs = []
self.talk_imgs = []
self.tap_imgs = []
self.wave_imgs = []
# tkinter widgets
self.win = None
self.canvas_label = None
# animation state
self._anim_thread = None
self._anim_state = 'idle' # idle, talk, tap, wave
self._frame_index = 0
self._last_blink = 0
# chat
self.chat_win = None
self.history_text = None
self.input_entry = None
# TTS
self._tts_engine = None
self._tts_available = False
try:
import pyttsx3
self.pyttsx3 = pyttsx3
self._tts_engine = pyttsx3.init()
# try to set a friendly voice if available
try:
voices = self._tts_engine.getProperty('voices')
if voices:
# pick first non-empty
for v in voices:
if 'female' in getattr(v, 'name', '').lower() or 'female' in getattr(v, 'id', '').lower():
self._tts_engine.setProperty('voice', v.id)
break
except Exception:
pass
self._tts_available = True
except Exception:
self._tts_available = False
# commands mapping: lowercased trigger -> (callable, friendly_reply)
# use local wrapper methods so mapping can be self-contained and easier to test
self.command_map = {
'open browser': (self.open_social_media, "Tarayıcıyı açıyorum — iyi gezmeler!"),
'open social': (self.open_social_media, "Sosyal medyaya geçiyoruz — dikkatli ol!"),
'open music': (self.open_music_studio, "Müziğe geçiliyor — ritmi yakala!"),
'music studio': (self.open_music_studio, "Müzik stüdyosu açıldı — kaliteli sesler bekliyor"),
'open video editor': (self.open_video_editor, "Video editör hazır — kes, kopyala, yapıştır"),
'open gallery': (self.open_gallery, "Galeriyi açıyorum — anıları karıştırma!"),
'open pdf': (self.open_pdf_reader, "PDF okuyucuyu açıyorum — sayfaları yıpratma"),
'show pdf': (self.open_pdf_reader, "Belgeyi açıyorum"),
# Explicit log/audio mappings so companion recognizes common phrases
'open log file': (self.open_log_file, "Log dosyasını açıyorum"),
'open log': (self.open_log_file, "Log dosyasını açıyorum"),
'show logs': (self.open_log_file, "Log dosyasını açıyorum"),
'open audio settings': (self.open_audio_settings, "Ses ayarlarını açıyorum"),
'help': (None, "Şunu yazabilirsin: open browser, open music, open video editor, open gallery, open pdf, shortcuts, companion settings"),
'shortcuts': (self.open_shortcuts_manager, "Kısayollar penceresini açıyorum"),
'companion settings': (self.open_companion_settings, "Asistan ayarlarını açıyorum"),
'open function art': (self.open_function_art, "Function ART penceresini açıyorum"),
'open settings': (self.open_companion_settings, "Ayarları açıyorum"),
'ayarlar': (self.open_companion_settings, "Ayarları açıyorum"),
'weather': (self.ai_weather, "Hava durumu bilgilerini getiriyorum..."),
'sosyal medya': (self.open_social_media, "Sosyal medyayı açıyorum — dikkatli ol!"),
'wikipedia': (self._cmd_wikipedia if hasattr(self, '_cmd_wikipedia') else None, "Wikipedia araması: wiki <konu>"),
'wiki': (self._cmd_wikipedia if hasattr(self, '_cmd_wikipedia') else None, "Wikipedia araması: wiki <konu>"),
}
# extend with advanced commands (lowercased keys)
try:
self.command_map.update({
'delete app': (self.delete_app, "Uygulamayı siliyorum..."),
'open path': (self.open_path, "Dosya yöneticisini açıyorum..."),
'dosya aç': (self.open_path, "Dosya yöneticisini açıyorum..."),
'screenshot': (self.take_screenshot, "Ekran görüntüsü alınıyor..."),
'change wallpaper': (self.change_wallpaper, "Duvar kağıdı ayarları açılıyor..."),
'system info': (self.system_info, "Sistem bilgileri alınıyor..."),
'joke': (self.ai_joke if getattr(self, 'ai', None) else None, "Bir şaka arıyorum..."),
'şaka': (self.ai_joke if getattr(self, 'ai', None) else None, "Bir şaka arıyorum..."),
'teach python': (self.ai_teach if getattr(self, 'ai', None) else None, "Python dersi getiriyorum..."),
'motivate': (self.ai_motivate if getattr(self, 'ai', None) else None, "Motivasyon mesajı geliyor...")
})
except Exception:
pass
# polite random replies for unknown queries
self.default_replies = [
"Hehe, komik soru. Bunu yapamam ama başka bir şey dene!",
"Bana bir görev ver: open browser, open music, open gallery...",
"Hmm bunu bilmiyorum ama öğrenebilirim — merak etme, not aldım."
]
# mouse drag
self._drag_data = {'x': 0, 'y': 0}
# allow move-on-rightclick (can be toggled via chat or host config)
self.allow_move_on_rightclick = True
try:
self.allow_move_on_rightclick = bool(self.forzeos.config.get('desktop', {}).get('companion_allow_move', True))
except Exception:
pass
# companion visibility behaviors
try:
dcfg = self.forzeos.config.get('desktop', {}) if hasattr(self.forzeos, 'config') else {}
self.hide_on_open = bool(dcfg.get('companion_hide_on_open', False))
self.keep_on_top_when_open = bool(dcfg.get('companion_keep_on_top', True))
except Exception:
self.hide_on_open = False
self.keep_on_top_when_open = True
# AI assistant enabled flag (persisted in host config)
self.ai_enabled = True
try:
self.ai_enabled = bool(self.forzeos.config.get('desktop', {}).get('companion_ai_enabled', True))
except Exception:
pass
# instantiate assistant if available (prefer AssistantClass set at module import)
try:
if AssistantClass is not None:
# Try common constructor signatures; some assistants accept session_size/name
try:
self.ai = AssistantClass(session_size=40, name='Forzos')
except TypeError:
try:
self.ai = AssistantClass()
except Exception:
self.ai = None
# inject available companion commands into assistant so help shows them
try:
if getattr(self, 'ai', None):
cmds = sorted(list(self.command_map.keys()))
# only inject the command names (no duplicates)
self.ai.external_commands = cmds
except Exception:
pass
# also try to add host app names (if host exposes FILE_ASSOCIATIONS or desktops)
try:
if getattr(self, 'ai', None):
app_names = [v[0] for v in getattr(self.forzeos, 'FILE_ASSOCIATIONS', {}).values() if isinstance(v, (list, tuple)) and v]
# add desktops listed in config
cfg_apps = []
try:
cfg = getattr(self.forzeos, 'config', {}) or {}
desktops = cfg.get('desktop', {}).get('desktops', {})
for k, lst in (desktops or {}).items():
for it in lst:
n = it.get('name') if isinstance(it, dict) else None
if n:
cfg_apps.append(n)
except Exception:
pass
all_apps = sorted(set(app_names + cfg_apps))
if all_apps:
try:
existing = list(getattr(self.ai, 'external_commands', []) or [])
merged = sorted(set(existing + [a for a in all_apps if a]))
self.ai.external_commands = merged
except Exception:
pass
except Exception:
pass
# attach assistant to host for easy host-level access
try:
setattr(self.forzeos, 'assistant', self.ai)
except Exception:
pass
else:
self.ai = None
except Exception:
self.ai = None
# Build a mapping of available host open_* methods and friendly app names
try:
self._host_open_map = {} # lower-name -> callable
# check ForzeOS FILE_ASSOCIATIONS first (maps ext -> (AppName, handler_name))
try:
fa = getattr(self.forzeos, 'FILE_ASSOCIATIONS', {}) or {}
for v in fa.values():
if isinstance(v, (list, tuple)) and len(v) >= 2:
app_name = str(v[0]).strip().lower()
handler = v[1]
if isinstance(handler, str) and hasattr(self.forzeos, handler):
self._host_open_map[app_name] = getattr(self.forzeos, handler)
except Exception:
pass
# Inspect ForzeOS methods starting with open_
try:
for name in dir(getattr(self.forzeos, '__class__', self.forzeos)):
if name.startswith('open_') or name.startswith('open'):
# friendly name: drop leading 'open_' and replace '_' with ' '
friendly = name
if friendly.startswith('open_'):
friendly = friendly[5:]
elif friendly.startswith('open'):
friendly = friendly[4:]
friendly = friendly.replace('_', ' ').strip().lower()
if hasattr(self.forzeos, name):
try:
self._host_open_map[friendly] = getattr(self.forzeos, name)
except Exception:
pass
except Exception:
pass
except Exception:
self._host_open_map = {}
# Expand companion command_map with discovered host methods and useful aliases.
# This keeps the companion's commands in sync with ForzeOS without manual edits.
try:
# For each discovered host open_* method, add 'open <name>' and short name aliases
for friendly, func in list(self._host_open_map.items()):
if not friendly:
continue
key_open = f"open {friendly}"
key_simple = friendly
# prefer not to overwrite existing explicit mappings
if key_open not in self.command_map:
# store the raw host callable; caller will use forzeos._call_cmd_safe
self.command_map[key_open] = (func, f"Açıyorum: {friendly}")
if key_simple not in self.command_map:
self.command_map[key_simple] = (func, f"Açıyorum: {friendly}")
# Add commonly useful control aliases if the host exposes them
def _bind_cmd(name, func, reply=None):
if not func:
return
if name not in self.command_map:
self.command_map[name] = (func, reply or f"Komut: {name}")
# Music controls
try:
_bind_cmd('play music', getattr(self.forzeos, 'music_play', None), 'Müziği oynatıyorum')
_bind_cmd('pause music', getattr(self.forzeos, 'music_pause', None), 'Müziği duraklatıyorum')
_bind_cmd('stop music', getattr(self.forzeos, 'music_stop', None), 'Müziği durduruyorum')
_bind_cmd('export track', getattr(self.forzeos, 'export_wav', None) if hasattr(self.forzeos, 'export_wav') else None, 'Dışa aktarıyorum')
except Exception:
pass
# File / system helpers
try:
_bind_cmd('open file manager', getattr(self.forzeos, 'open_file_manager', None), 'Dosya yöneticisini açıyorum')
_bind_cmd('open terminal', getattr(self.forzeos, 'open_terminal', None), 'Terminal açılıyor')
_bind_cmd('open notepad', getattr(self.forzeos, 'open_notepad', None), 'Notepad açılıyor')
_bind_cmd('screenshot', getattr(self.forzeos, 'take_screenshot', None), 'Ekran görüntüsü alınıyor')
except Exception:
pass
# Settings and helpers
try:
_bind_cmd('open settings', getattr(self.forzeos, 'open_desktop_settings', None) or getattr(self.forzeos, 'open_companion_settings', None), 'Ayarlar açılıyor')
except Exception:
pass
# Improve help reply to include discovered commands
try:
discovered = sorted([k for k in self.command_map.keys() if isinstance(k, str)])
short_list = ', '.join(discovered[:18]) + (', ...' if len(discovered) > 18 else '')
help_text = "Kullanılabilir komut örnekleri: " + short_list
# Replace generic 'help' mapping reply if present
if 'help' in self.command_map:
cmd, _ = self.command_map['help']
self.command_map['help'] = (cmd, help_text)
else:
self.command_map['help'] = (None, help_text)
except Exception:
pass
except Exception:
# non-fatal: companion will still work with manual mappings defined earlier
pass
# Load sprites now (non-blocking)
self._load_sprites()
# Idle reply scheduling handle (will call assistant.random_idle_reply occasionally)
self._idle_job_id = None
try:
if getattr(self, 'ai', None) and getattr(self, 'ai_enabled', True):
# schedule first idle
self._schedule_next_idle()
except Exception:
pass
# -------------------- Sprites --------------------
def _list_asset_files(self, prefix):
files = []
if not os.path.isdir(self.ASSET_DIR):
return files
for f in os.listdir(self.ASSET_DIR):
if f.lower().startswith(prefix) and f.lower().endswith('.png'):
files.append(os.path.join(self.ASSET_DIR, f))
# sort by filename to ensure order
files.sort()
return files
def _load_image(self, path):
try:
# Prefer PIL when available for robust PNG alpha support and resizing
if PIL_AVAILABLE and Image is not None and ImageTk is not None:
img = Image.open(path).convert('RGBA')
img = img.resize((self.size, self.size), Image.LANCZOS)
return ImageTk.PhotoImage(img)
# Fallback: try tk.PhotoImage which can load some formats on some platforms
try:
return tk.PhotoImage(file=path)
except Exception:
# Last resort: create an empty transparent PhotoImage placeholder
try:
return tk.PhotoImage(width=self.size, height=self.size)
except Exception:
return None
except Exception:
return None
def _load_sprites(self):
# idle
idle_files = self._list_asset_files('companion_idle_')
for p in idle_files:
im = self._load_image(p)
if im:
self.idle_imgs.append(im)
# talk
talk_files = self._list_asset_files('companion_talk_')
for p in talk_files:
im = self._load_image(p)
if im:
self.talk_imgs.append(im)
# tap
tap_files = self._list_asset_files('companion_tap_')
for p in tap_files:
im = self._load_image(p)
if im:
self.tap_imgs.append(im)
# wave
wave_files = self._list_asset_files('companion_wave_')
for p in wave_files:
im = self._load_image(p)
if im:
self.wave_imgs.append(im)
# If some lists are empty, duplicate idle frames to avoid crashes
if not self.idle_imgs:
# create a simple placeholder from a blank Image
blank = Image.new('RGBA', (self.size, self.size), (0, 0, 0, 0))
self.idle_imgs = [ImageTk.PhotoImage(blank)]
if not self.talk_imgs:
self.talk_imgs = self.idle_imgs
if not self.tap_imgs:
self.tap_imgs = self.idle_imgs
if not self.wave_imgs:
self.wave_imgs = self.idle_imgs
# -------------------- Wikipedia command --------------------
def _cmd_wikipedia(self, text: str = None):
"""Handle Wikipedia commands via host assistant or fallback module.
`text` may be the full user input or just the argument passed by the
companion command dispatcher. Method returns a short string reply.
"""
q = (text or '').strip()
# If only keyword was provided, ask for topic (handled elsewhere too)
if not q or q.lower() in ('wikipedia', 'wiki'):
try:
import forze_wikipedia
return forze_wikipedia.handle_command('wikipedia')
except Exception:
return 'Wikipedia komutu: bir konu söyle (ör: wiki Türkiye)'
candidate = q
if not any(candidate.lower().startswith(p) for p in ('wiki ', 'wikipedia ', 'nedir ', 'kimdir ')):
candidate = 'wiki ' + candidate
# Prefer host assistant if available
try:
host_ai = getattr(self.forze, 'assistant', None) or getattr(self.forze, 'ai', None)
if host_ai and hasattr(host_ai, 'execute_command'):
res = host_ai.execute_command(candidate)
if res:
return str(res)
except Exception:
pass
# Fallback to local module
try:
import forze_wikipedia
return forze_wikipedia.handle_command(candidate)
except Exception:
return 'Wikipedia araması yapılamıyor.'
# -------------------- Install / Window --------------------
def install(self, x=100, y=100):
"""Create the companion window and begin animation."""
if self.win and tk.Toplevel.winfo_exists(self.win):
# already installed
return
# Create a top-level window without decorations so it looks like a sprite
self.win = Toplevel(self.root)
self.win.overrideredirect(True)
# Keep above the main window but not always on top of everything
try:
self.win.attributes('-topmost', True)
except Exception:
pass
# Attempt to apply a transparent background for the toplevel so PNG alpha shows through.
# On Windows, Tk supports a single-color transparency via '-transparentcolor'. We'll choose
# a magic color that we'll use as the Label background for areas that should be transparent.
transparent_color = '#123456'
try:
# Set the transparent color on the window (Windows-only; other platforms will ignore)
self.win.attributes('-transparentcolor', transparent_color)
except Exception:
# Not supported on some platforms; fall back to matching desktop bg by using no border
transparent_color = None
self.win.geometry(f"+{x}+{y}")
# store initial position in host config so settings toggle can restore
try:
if hasattr(self.forzeos, 'config'):
self.forzeos.config.setdefault('desktop', {})['companion_position'] = {'x': int(x), 'y': int(y)}
try:
if hasattr(self.forzeos, 'save_config'):
self.forzeos.save_config()
except Exception:
pass
except Exception:
pass
frame = Frame(self.win, bg=(transparent_color or 'white'))
frame.pack()
# label to hold image — set bg to transparent_color when available so PNG alpha blends
self.canvas_label = Label(frame, bd=0, bg=(transparent_color or 'white'))
self.canvas_label.pack()
# bindings
# Left-click opens chat (dragging disabled)
self.canvas_label.bind('<Button-1>', self._on_click)
self.canvas_label.bind('<ButtonRelease-1>', self._on_release)
# Right-click toggles move or waves depending on setting
self.canvas_label.bind('<Button-3>', self._on_right_click)
# start anim thread, but only show static idle image by default
self._stop_anim = False
self._anim_thread = threading.Thread(target=self._anim_loop, daemon=True)
self._anim_thread.start()
# display first idle frame immediately
try:
if self.idle_imgs:
img = self.idle_imgs[0]
self.canvas_label.config(image=img)
except Exception:
pass
# If host config says companion was hidden, hide immediately after install
try:
if hasattr(self.forzeos, 'config'):
hidden = bool(self.forzeos.config.get('desktop', {}).get('companion_hidden', False))
if hidden:
try:
self.win.withdraw()
except Exception:
pass
except Exception:
pass
def uninstall(self):
self._stop_anim = True
try:
if getattr(self, '_idle_job_id', None):
try:
self.root.after_cancel(self._idle_job_id)
except Exception:
pass
self._idle_job_id = None
except Exception:
pass
if self.win:
try:
self.win.destroy()
except Exception:
pass
self.win = None
def hide_companion(self):
"""Hide the companion window (withdraw)."""
try:
if self.win and tk.Toplevel.winfo_exists(self.win):
try:
self.win.withdraw()
except Exception:
pass
# persist flag
try:
if hasattr(self.forzeos, 'config'):
self.forzeos.config.setdefault('desktop', {})['companion_hidden'] = True
if hasattr(self.forzeos, 'save_config'):
try:
self.forzeos.save_config()
except Exception:
pass
except Exception:
pass
except Exception:
pass
def restore_companion(self):
"""Restore the companion window (deiconify)."""
try:
if self.win:
try:
self.win.deiconify()
try:
self.win.lift()
except Exception:
pass
except Exception:
pass
# persist flag
try:
if hasattr(self.forzeos, 'config'):
self.forzeos.config.setdefault('desktop', {})['companion_hidden'] = False
if hasattr(self.forzeos, 'save_config'):
try:
self.forzeos.save_config()
except Exception:
pass
except Exception:
pass
except Exception:
pass
# -------------------- Drag handlers --------------------
def _on_click(self, event):
# open chat when quickly clicked (if not dragging)
# small delay to detect click
self._click_time = time.time()
# react to touch with a short, humorous annoyed reply
try:
# don't spam on repeated clicks; allow immediate short reply
annoyed = "Hey! Çok nazikçe dokun, ben de hassas bir botum — rahatsız oldum ama seni affediyorum."
self._speak_and_reply(annoyed)
# small tap animation
self._set_anim_state('tap', duration=0.9)
except Exception:
pass
def _on_drag_motion(self, event):
# dragging is disabled; leave handler as no-op for compatibility
return
def _on_release(self, event):
# if click was short and there was minimal movement, treat as click (open chat)
click_duration = time.time() - getattr(self, '_click_time', 0)
if click_duration < 0.3:
# open chat
self.open_chat()
# notify host that the position may have changed so it can persist
try:
if hasattr(self, '_on_position_changed') and callable(self._on_position_changed):
try:
# schedule on main thread
self.forzeos.root.after(10, self._on_position_changed)
except Exception:
try:
self._on_position_changed()
except Exception:
pass
except Exception:
pass
# Also persist position directly into host config if available (defensive)
try:
if hasattr(self, 'win') and getattr(self, 'win') is not None and hasattr(self.forzeos, 'config'):
try:
wx = self.win.winfo_x()
wy = self.win.winfo_y()
self.forzeos.config.setdefault('desktop', {})['companion_position'] = {'x': int(wx), 'y': int(wy)}
try:
if hasattr(self.forzeos, 'save_config'):
self.forzeos.save_config()
except Exception:
pass
except Exception:
pass
except Exception:
pass
def _on_right_click(self, event):
# Right-click behavior: either move the mascot (if allowed) or play a wave
try:
allow = bool(getattr(self, 'allow_move_on_rightclick', True))
except Exception:
allow = True
if allow:
# Move mascot to bottom-right above host taskbar
try:
tb_size = self.forzeos.config.get('settings', {}).get('taskbar_size', 'medium') if hasattr(self, 'forzeos') else 'medium'
size_map = {'small': 30, 'medium': 50, 'large': 70}
tb_dim = size_map.get(tb_size, 50)
except Exception:
tb_dim = 50
try:
screen_w = self.forzeos.root.winfo_screenwidth()
screen_h = self.forzeos.root.winfo_screenheight()
except Exception:
screen_w = self.root.winfo_screenwidth()
screen_h = self.root.winfo_screenheight()
try:
comp_w = self.size
comp_h = self.size
except Exception:
comp_w = comp_h = 128
new_x = max(10, screen_w - comp_w - 20)
new_y = max(10, screen_h - tb_dim - comp_h - 10)
try:
self.win.geometry(f"+{new_x}+{new_y}")
except Exception:
pass
# persist position via host callback if available
try:
if hasattr(self, '_on_position_changed') and callable(self._on_position_changed):
try:
self.forzeos.root.after(10, self._on_position_changed)
except Exception:
self._on_position_changed()
except Exception:
pass
# feedback animation
self._set_anim_state('wave', duration=1.0)
else:
self._set_anim_state('wave', duration=0.8)
# -------------------- Wrapper command methods --------------------
def open_social_media(self):
"""Wrapper that calls host's social media / browser open routine."""
try:
if hasattr(self.forzeos, 'open_social_media'):
# hide companion if configured
try:
if self.hide_on_open and hasattr(self, 'win') and self.win:
try:
self.win.withdraw()
except Exception:
pass
except Exception:
pass
self.forzeos.open_social_media()
elif hasattr(self.forzeos, '_call_cmd_safe'):
# only call host methods (not arbitrary strings)
self.forzeos._call_cmd_safe(self.forzeos.open_social_media)
except Exception:
pass
def open_music_studio(self):
try:
if hasattr(self.forzeos, 'open_music_studio'):
if self.hide_on_open and hasattr(self, 'win') and self.win:
try:
self.win.withdraw()
except Exception:
pass
self.forzeos.open_music_studio()
elif hasattr(self.forzeos, '_call_cmd_safe'):
self.forzeos._call_cmd_safe(self.forzeos.open_music_studio)
except Exception:
pass
def open_video_editor(self):
try:
if hasattr(self.forzeos, 'open_video_editor'):
if self.hide_on_open and hasattr(self, 'win') and self.win:
try:
self.win.withdraw()
except Exception:
pass
self.forzeos.open_video_editor()
elif hasattr(self.forzeos, '_call_cmd_safe'):
self.forzeos._call_cmd_safe(self.forzeos.open_video_editor)
except Exception:
pass
def open_gallery(self):
try:
if hasattr(self.forzeos, 'open_gallery'):
if self.hide_on_open and hasattr(self, 'win') and self.win:
try:
self.win.withdraw()
except Exception:
pass
self.forzeos.open_gallery()
elif hasattr(self.forzeos, '_call_cmd_safe'):
self.forzeos._call_cmd_safe(self.forzeos.open_gallery)
except Exception:
pass
def open_pdf_reader(self):
try:
if hasattr(self.forzeos, 'open_pdf_reader'):
if self.hide_on_open and hasattr(self, 'win') and self.win:
try:
self.win.withdraw()
except Exception:
pass
self.forzeos.open_pdf_reader()
elif hasattr(self.forzeos, '_call_cmd_safe'):
self.forzeos._call_cmd_safe(self.forzeos.open_pdf_reader)
except Exception:
pass
def open_log_file(self, path: str = None):
"""Open host's log file via ForzeOS helper."""
try:
# Prefer host helper that can accept an optional filepath
if hasattr(self.forzeos, '_call_cmd_with_optional_filepath'):
try:
ok = self.forzeos._call_cmd_with_optional_filepath(self.forzeos.open_log_file, path)
if ok:
try:
if self.hide_on_open and getattr(self, 'win', None):
try:
self.win.withdraw()
except Exception:
pass
except Exception:
pass
return True
except Exception:
logger.exception('Companion: _call_cmd_with_optional_filepath failed for open_log_file')
# Fallback to the generic safe caller
if hasattr(self.forzeos, '_call_cmd_safe'):
try:
if path:
self.forzeos._call_cmd_safe(self.forzeos.open_log_file, path)
else:
self.forzeos._call_cmd_safe(self.forzeos.open_log_file)
try:
if self.hide_on_open and getattr(self, 'win', None):
try:
self.win.withdraw()
except Exception:
pass
except Exception:
pass
return True
except Exception:
logger.exception('Companion: _call_cmd_safe failed for open_log_file')
# Last resort: direct call
if hasattr(self.forzeos, 'open_log_file'):
try:
if path:
self.forzeos.open_log_file(path)
else:
self.forzeos.open_log_file()
try:
if self.hide_on_open and getattr(self, 'win', None):
try:
self.win.withdraw()
except Exception:
pass
except Exception:
pass
return True
except Exception as e:
logger.exception('Companion: direct open_log_file call failed')
try:
self._speak_and_reply(f'Log açılamadı: {e}')
except Exception:
pass
else:
try:
self._speak_and_reply('Host üzerinde log açma fonksiyonu bulunamadı.')
except Exception:
pass
except Exception:
logger.exception('Companion: open_log_file encountered an unexpected error')
return False
def open_audio_settings(self):
"""Open host's audio settings window."""
try:
if hasattr(self.forzeos, 'open_audio_settings'):
try:
if hasattr(self.forzeos, '_call_cmd_safe'):
self.forzeos._call_cmd_safe(self.forzeos.open_audio_settings)
else:
self.forzeos.open_audio_settings()
except Exception:
try:
self.forzeos.open_audio_settings()
except Exception:
pass
except Exception:
pass
# -------------------- Advanced command wrappers --------------------
def delete_app(self, name: str):
try:
if not name:
self._speak_and_reply('Silinecek uygulama adı verilmedi.')
return
# attempt host method first
try:
if hasattr(self.forzeos, 'delete_app'):
self.forzeos.delete_app(name)
else:
# try to remove desktop icon if such helper exists
try:
self.forzeos.remove_desktop_icon(name)
except Exception:
pass
self._speak_and_reply(f'Uygulama silindi: {name}')
except Exception as e:
self._speak_and_reply(f'App silme hatası: {e}')
except Exception:
pass
def open_path(self, path: str = None):
try:
if not path:
# open generic file manager
if hasattr(self.forzeos, 'open_file_manager'):
self.forzeos.open_file_manager()
return
# sanitize path
p = path.strip().strip('"')
try:
if hasattr(self.forzeos, 'open_file_manager'):
self.forzeos.open_file_manager(p)
else:
# fallback: try to open path via host safe caller
self.forzeos._call_cmd_safe(lambda: None)
except Exception:
try:
# platform open
if os.path.exists(p):
os.startfile(p)
except Exception:
pass
except Exception:
pass
def take_screenshot(self):
try:
# prefer host implementation
if hasattr(self.forzeos, 'take_screenshot'):
self.forzeos.take_screenshot()
self._speak_and_reply('Ekran görüntüsü alındı.')
return
# fallback using PIL.ImageGrab if available
try:
from PIL import ImageGrab
img = ImageGrab.grab()
# save to user's file_system_root if available
base = getattr(self.forzeos, 'file_system_root', os.getcwd())
os.makedirs(base, exist_ok=True)
fname = os.path.join(base, f'screenshot_{int(time.time())}.png')
img.save(fname)
self._speak_and_reply(f'Ekran görüntüsü kaydedildi: {fname}')
except Exception as e:
self._speak_and_reply(f'Ekran görüntüsü alınamadı: {e}')