-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1290 lines (1185 loc) · 81.5 KB
/
main.py
File metadata and controls
1290 lines (1185 loc) · 81.5 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 sys
import os
import google.generativeai as genai
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QHBoxLayout, QVBoxLayout,
QTextEdit, QLineEdit, QLabel, QSplitter, QMessageBox, QPushButton,
QFileDialog, QSizePolicy, QListWidget, QListWidgetItem,
QSystemTrayIcon, QMenu, QStyle, QFrame # Added QFrame
)
from PySide6.QtCore import Qt, Slot, Signal, QObject, QBuffer, QIODevice, QRunnable, QThreadPool, QTimer, QRect
from PySide6.QtGui import QPixmap, QImage, QIcon, QTextCursor, QAction, QPainter, QColor, QFont
import threading
from io import BytesIO
import functools
import re
import mss
import tempfile
from PIL import Image
import pytesseract
import datetime
import json
import webbrowser
import urllib.parse
from quick_ask_overlay import InsightOverlay
from plugin_manager import PluginManager
from api_key_dialog import ApiKeyDialog
from region_selector_widget import RegionSelectorWidget
from chat_session_manager import ChatSession, ChatMessage, db_manager
from typing import Optional, List, Dict
from google.generativeai import types as genai_types
from google.ai.generativelanguage_v1beta.types import GroundingMetadata
# Attempt to import autorun, will be handled in auto-start methods if missing
try:
import autorun
except ImportError:
autorun = None
# --- Styling Constants ---
STYLE_CONSTANTS = {
"MAIN_BG_COLOR": "rgba(20, 22, 30, 0.95)",
"PANEL_BG_COLOR": "rgba(40, 42, 54, 0.85)",
"MIDDLE_PANEL_BG_COLOR": "rgba(30, 32, 40, 0.9)",
"ACCENT_VIOLET": "rgba(180, 100, 220, 0.75)",
"ACCENT_BLUE": "rgba(80, 150, 230, 0.75)",
"ACCENT_GREY": "rgba(70, 73, 90, 0.75)",
"BORDER_COLOR": "rgba(220, 220, 255, 0.15)",
"TEXT_COLOR_LIGHT": "rgb(240, 240, 240)",
"TEXT_COLOR_MEDIUM": "rgb(180, 180, 200)",
"TEXT_COLOR_DARK": "rgb(40, 42, 54)",
"INPUT_FIELD_BG": "rgba(20, 22, 30, 0.7)",
"BUTTON_BG_COLOR": "rgba(80, 85, 110, 0.8)",
"BUTTON_HOVER_BG_COLOR": "rgba(100, 105, 130, 0.85)",
"BUTTON_PRESSED_BG_COLOR": "rgba(70, 75, 100, 0.9)",
"SCROLL_BAR_BG": "rgba(20, 22, 30, 0.8)",
"SCROLL_BAR_HANDLE": "rgba(70, 73, 90, 0.9)",
"SCROLL_BAR_HANDLE_HOVER": "rgba(90, 93, 120, 0.95)",
"FONT_FAMILY": "Inter, Roboto, Lato, Sans-Serif",
"FONT_SIZE_NORMAL": "10pt",
"FONT_SIZE_SMALL": "9pt",
"FONT_SIZE_LARGE": "12pt",
"BORDER_RADIUS": "12px",
"BORDER_RADIUS_SM": "8px",
}
def get_base_stylesheet():
return f"""
QWidget {{
font-family: {STYLE_CONSTANTS['FONT_FAMILY']};
font-size: {STYLE_CONSTANTS['FONT_SIZE_NORMAL']};
color: {STYLE_CONSTANTS['TEXT_COLOR_LIGHT']};
}}
QMainWindow {{
background-color: {STYLE_CONSTANTS['MAIN_BG_COLOR']};
}}
QWidget#LeftColumnWidget, QWidget#RightColumnWidget {{
background-color: {STYLE_CONSTANTS['PANEL_BG_COLOR']};
border-radius: {STYLE_CONSTANTS['BORDER_RADIUS']};
}}
QWidget#MiddleColumnWidget {{
background-color: {STYLE_CONSTANTS['MIDDLE_PANEL_BG_COLOR']};
border-radius: {STYLE_CONSTANTS['BORDER_RADIUS']};
}}
QLabel {{
background-color: transparent;
color: {STYLE_CONSTANTS['TEXT_COLOR_MEDIUM']};
}}
QLabel#TitleLabel {{
color: {STYLE_CONSTANTS['TEXT_COLOR_LIGHT']};
font-size: {STYLE_CONSTANTS['FONT_SIZE_LARGE']};
font-weight: bold;
padding: 5px 0px;
}}
QLineEdit {{
background-color: {STYLE_CONSTANTS['INPUT_FIELD_BG']};
border: 1px solid {STYLE_CONSTANTS['BORDER_COLOR']};
border-radius: {STYLE_CONSTANTS['BORDER_RADIUS_SM']};
padding: 6px 10px;
color: {STYLE_CONSTANTS['TEXT_COLOR_LIGHT']};
}}
QLineEdit:focus {{
border: 1px solid {STYLE_CONSTANTS['ACCENT_VIOLET']};
}}
QTextEdit {{
background-color: {STYLE_CONSTANTS['INPUT_FIELD_BG']};
border: 1px solid {STYLE_CONSTANTS['BORDER_COLOR']};
border-radius: {STYLE_CONSTANTS['BORDER_RADIUS_SM']};
padding: 6px;
color: {STYLE_CONSTANTS['TEXT_COLOR_LIGHT']};
}}
QTextEdit#ChatArea {{
border-radius: {STYLE_CONSTANTS['BORDER_RADIUS']};
background-color: rgba(0,0,0,0.1); /* Slightly darker than middle panel for depth */
}}
QPushButton {{
background-color: {STYLE_CONSTANTS['BUTTON_BG_COLOR']};
color: {STYLE_CONSTANTS['TEXT_COLOR_LIGHT']};
border: 1px solid {STYLE_CONSTANTS['BORDER_COLOR']};
border-radius: {STYLE_CONSTANTS['BORDER_RADIUS_SM']};
padding: 6px 12px;
min-height: 20px;
}}
QPushButton:hover {{
background-color: {STYLE_CONSTANTS['BUTTON_HOVER_BG_COLOR']};
border: 1px solid {STYLE_CONSTANTS['ACCENT_BLUE']};
}}
QPushButton:pressed {{
background-color: {STYLE_CONSTANTS['BUTTON_PRESSED_BG_COLOR']};
}}
QPushButton:disabled {{
background-color: rgba(50,50,50,0.7);
color: rgba(150,150,150,0.7);
}}
QListWidget {{
background-color: rgba(0,0,0,0.1);
border: none; /* Remove default border, panel provides container */
border-radius: {STYLE_CONSTANTS['BORDER_RADIUS_SM']};
padding: 4px;
}}
QListWidget::item {{
background-color: rgba(255, 255, 255, 0.03);
color: {STYLE_CONSTANTS['TEXT_COLOR_MEDIUM']};
border-radius: {STYLE_CONSTANTS['BORDER_RADIUS_SM']};
padding: 8px 6px; margin-bottom: 4px;
border: 1px solid transparent; /* For hover/selection border */
}}
QListWidget::item:hover {{
background-color: {STYLE_CONSTANTS['ACCENT_GREY']};
color: {STYLE_CONSTANTS['TEXT_COLOR_LIGHT']};
border: 1px solid {STYLE_CONSTANTS['BORDER_COLOR']};
}}
QListWidget::item:selected {{
background-color: {STYLE_CONSTANTS['ACCENT_VIOLET']};
color: {STYLE_CONSTANTS['TEXT_COLOR_LIGHT']};
border: 1px solid {STYLE_CONSTANTS['ACCENT_BLUE']};
}}
QScrollBar:vertical {{
background: {STYLE_CONSTANTS['SCROLL_BAR_BG']}; width: 10px; margin: 0px; border-radius: 5px;
}}
QScrollBar::handle:vertical {{
background: {STYLE_CONSTANTS['SCROLL_BAR_HANDLE']}; min-height: 20px; border-radius: 5px;
}}
QScrollBar::handle:vertical:hover {{ background: {STYLE_CONSTANTS['SCROLL_BAR_HANDLE_HOVER']}; }}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{ height: 0px; background: none; }}
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {{ background: none; }}
QScrollBar:horizontal {{
background: {STYLE_CONSTANTS['SCROLL_BAR_BG']}; height: 10px; margin: 0px; border-radius: 5px;
}}
QScrollBar::handle:horizontal {{
background: {STYLE_CONSTANTS['SCROLL_BAR_HANDLE']}; min-width: 20px; border-radius: 5px;
}}
QScrollBar::handle:horizontal:hover {{ background: {STYLE_CONSTANTS['SCROLL_BAR_HANDLE_HOVER']}; }}
QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {{ width: 0px; background: none; }}
QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {{ background: none; }}
QSplitter::handle {{ background-color: {STYLE_CONSTANTS['BORDER_COLOR']}; }}
QSplitter::handle:horizontal {{ width: 1px; }}
QSplitter::handle:vertical {{ height: 1px; }}
QSplitter::handle:pressed {{ background-color: {STYLE_CONSTANTS['ACCENT_BLUE']}; }}
QMenu {{
background-color: {STYLE_CONSTANTS['PANEL_BG_COLOR']};
border: 1px solid {STYLE_CONSTANTS['BORDER_COLOR']};
border-radius: {STYLE_CONSTANTS['BORDER_RADIUS_SM']}; padding: 5px;
}}
QMenu::item {{ padding: 5px 20px; color: {STYLE_CONSTANTS['TEXT_COLOR_LIGHT']}; }}
QMenu::item:selected {{ background-color: {STYLE_CONSTANTS['ACCENT_VIOLET']}; }}
QMenu::separator {{ height: 1px; background: {STYLE_CONSTANTS['BORDER_COLOR']}; margin: 4px 0px; }}
QToolTip {{
background-color: {STYLE_CONSTANTS['PANEL_BG_COLOR']};
color: {STYLE_CONSTANTS['TEXT_COLOR_LIGHT']};
border: 1px solid {STYLE_CONSTANTS['BORDER_COLOR']};
padding: 4px; border-radius: {STYLE_CONSTANTS['BORDER_RADIUS_SM']};
}}
"""
# ... (WorkerSignals, GeminiRunnable, HotkeySignal classes remain the same) ...
class WorkerSignals(QObject):
finished = Signal(object, str, list, str, int, str, str)
error = Signal(str, list, str, int, str)
class GeminiRunnable(QRunnable):
def __init__(self, model_to_use, query_content_parts, source, iteration_count,
generation_config: Optional[genai_types.GenerationConfig] = None,
is_context_analysis_request=False):
super().__init__()
self.model_to_use = model_to_use
self.query_content_parts = query_content_parts
self.source = source
self.iteration_count = iteration_count
self.generation_config = generation_config
self.signals = WorkerSignals()
self.is_cancelled = False
self.is_context_analysis_request = is_context_analysis_request
@Slot()
def run(self):
if self.is_cancelled:
self.signals.error.emit("Request cancelled before start", self.query_content_parts, self.source, self.iteration_count, self.model_to_use.model_name)
return
try:
response = self.model_to_use.generate_content(
self.query_content_parts,
generation_config=self.generation_config,
)
actions_json_str = None
if self.is_context_analysis_request:
actions_json_str = response.text
if self.is_cancelled:
self.signals.error.emit("Request cancelled during execution", self.query_content_parts, self.source, self.iteration_count, self.model_to_use.model_name)
return
self.signals.finished.emit(response, None, self.query_content_parts, self.source, self.iteration_count, self.model_to_use.model_name, actions_json_str if actions_json_str is not None else "")
except Exception as e:
print(f"[GeminiRunnable Error] Exception during API call: {e}")
if not self.is_cancelled:
self.signals.error.emit(str(e), self.query_content_parts, self.source, self.iteration_count, self.model_to_use.model_name)
def cancel(self):
print(f"[GeminiRunnable] Attempting to cancel task for source {self.source}, iter {self.iteration_count}")
self.is_cancelled = True
class HotkeySignal(QObject):
toggle_overlay = Signal()
trigger_screen_capture = Signal()
class MainApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Gemini Desktop Agent")
self.setGeometry(100, 100, 1200, 850) # Increased height slightly for new layout
# Set WA_TranslucentBackground if aiming for true desktop passthrough for blur
# self.setAttribute(Qt.WA_TranslucentBackground)
# self.setStyleSheet("background:transparent;") # Required if WA_TranslucentBackground is set
main_widget = QWidget(); self.setCentralWidget(main_widget)
# The main_layout will now be directly on the main_widget (centralWidget)
# and will contain the QSplitter which then holds the columns.
main_layout_for_splitter = QHBoxLayout(main_widget) # Use this for the splitter
main_layout_for_splitter.setContentsMargins(5,5,5,5) # Small margin around splitter
self.thread_pool = QThreadPool(); self.active_gemini_runnable = None
self.gemini_model = None; self.gemini_vision_model = None
self.attached_image_path = None; self.attached_ocr_text = None; self.current_iteration_data = None
self.sessions: List[ChatSession] = []; self.current_session_id: Optional[str] = None
db_manager.initialize_database()
self.insight_overlay = InsightOverlay()
self.insight_overlay.query_submitted.connect(self.handle_insight_overlay_query)
self.insight_overlay.request_close.connect(self.handle_insight_overlay_close_request)
self.insight_overlay.action_button_clicked_signal.connect(self.handle_context_action)
self.insight_overlay.region_selection_initiated.connect(self.initiate_region_selection_for_overlay)
self.region_selector_widget = None
self.hotkey_signal = HotkeySignal()
try:
self.hotkey_listener_thread = threading.Thread(target=self.init_hotkey_listener, daemon=True)
self.hotkey_listener_thread.start()
self.hotkey_signal.toggle_overlay.connect(self.toggle_insight_overlay)
self.hotkey_signal.trigger_screen_capture.connect(functools.partial(self.capture_screen_and_attach, True, None))
print("Hotkey listener started.")
except Exception as e:
print(f"WARNING: Failed to initialize hotkey listener: {e}. Hotkeys will be disabled.")
self.plugin_manager = PluginManager(plugin_folder="plugins")
self.plugin_manager.plugin_loaded.connect(self.on_plugin_loaded)
self.plugin_manager.plugin_error.connect(self.on_plugin_error)
plugins_init_path = os.path.join("plugins", "__init__.py")
if not os.path.exists(plugins_init_path):
if not os.path.exists("plugins"): os.makedirs("plugins")
with open(plugins_init_path, "w") as f: pass
self.plugin_manager.discover_plugins(); self.plugin_manager.load_all_plugins()
self._load_config_settings()
self._setup_ui(main_layout_for_splitter) # Pass the layout for the splitter
self._setup_tray_icon()
self._load_or_create_initial_session()
QTimer.singleShot(0, self.init_gemini_with_key_prompt)
def _load_config_settings(self):
self.config_path = self.get_config_path()
self.app_settings = {"api_key": None, "auto_start_enabled": False}
try:
if os.path.exists(self.config_path):
with open(self.config_path, 'r') as f:
loaded_settings = json.load(f)
for key, default_value in self.app_settings.items():
if key in loaded_settings:
self.app_settings[key] = loaded_settings[key]
print(f"Loaded settings from {self.config_path}: {self.app_settings}")
except json.JSONDecodeError as e:
print(f"Error decoding JSON from {self.config_path}: {e}. Using defaults and attempting to overwrite corrupted file.")
try:
os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
with open(self.config_path, 'w') as f:
json.dump(self.app_settings, f, indent=4)
print(f"Corrupted config file was overwritten with defaults at {self.config_path}")
except Exception as save_e:
print(f"Could not overwrite corrupted config file: {save_e}")
except Exception as e:
print(f"Error loading config from {self.config_path}: {e}. Using defaults.")
if not isinstance(self.app_settings.get("auto_start_enabled"), bool):
self.app_settings["auto_start_enabled"] = False
if self.app_settings.get("api_key") == "":
self.app_settings["api_key"] = None
def _save_config_settings(self):
try:
os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
with open(self.config_path, 'w') as f:
json.dump(self.app_settings, f, indent=4)
print(f"Saved settings to {self.config_path}")
except Exception as e:
print(f"Error saving config to {self.config_path}: {e}")
QMessageBox.warning(self, "Config Error", f"Could not save settings to {self.config_path}:\n{e}")
def _setup_tray_icon(self):
self.tray_icon = QSystemTrayIcon(self)
app_icon = QIcon.fromTheme("application-x-executable", self.style().standardIcon(QStyle.SP_ComputerIcon))
icons_dir = "icons"; custom_icon_path = os.path.join(icons_dir, "app_icon.png")
if not os.path.exists(icons_dir):
try: os.makedirs(icons_dir); print(f"Created '{icons_dir}' directory for application icons.")
except OSError as e: print(f"Warning: Could not create '{icons_dir}' directory: {e}")
if os.path.exists(custom_icon_path): app_icon = QIcon(custom_icon_path)
elif app_icon.isNull():
print("Warning: No suitable application icon found for tray. Using a default generated icon.")
pixmap = QPixmap(32, 32); pixmap.fill(Qt.transparent)
painter = QPainter(pixmap)
try:
font = painter.font(); font.setPointSize(18); painter.setFont(font)
painter.setPen(Qt.blue); painter.drawText(pixmap.rect(), Qt.AlignCenter, "G")
finally: painter.end()
app_icon = QIcon(pixmap)
self.tray_icon.setIcon(app_icon)
self.tray_icon.setToolTip("Gemini Desktop Agent")
tray_menu = QMenu(self)
toggle_window_action = QAction("Show/Hide Agent", self)
toggle_window_action.triggered.connect(self.toggle_main_window_visibility)
tray_menu.addAction(toggle_window_action)
tray_menu.addSeparator()
self.auto_start_action = QAction("Start with System", self)
self.auto_start_action.setCheckable(True)
self.auto_start_action.setChecked(self.app_settings.get("auto_start_enabled", False))
if autorun is None:
self.auto_start_action.setEnabled(False)
self.auto_start_action.setToolTip("Auto-start feature requires 'autorun' library (pip install autorun)")
self.auto_start_action.triggered.connect(self.handle_auto_start_toggle)
tray_menu.addAction(self.auto_start_action)
tray_menu.addSeparator()
quit_action = QAction("Quit Agent", self)
quit_action.triggered.connect(self.actual_quit)
tray_menu.addAction(quit_action)
self.tray_icon.setContextMenu(tray_menu)
self.tray_icon.activated.connect(self.handle_tray_icon_activation)
if QSystemTrayIcon.isSystemTrayAvailable():
self.tray_icon.show(); print("System tray icon initialized.")
else: print("Warning: System tray not available. Tray icon will not be shown.")
self.is_hidden_to_tray = False
def handle_tray_icon_activation(self, reason):
if reason == QSystemTrayIcon.ActivationReason.Trigger: self.toggle_main_window_visibility()
def toggle_main_window_visibility(self):
if self.isHidden() or self.is_hidden_to_tray:
self.showNormal(); self.activateWindow(); self.raise_(); self.is_hidden_to_tray = False
else:
self.hide(); self.is_hidden_to_tray = True
if QSystemTrayIcon.isSystemTrayAvailable() and self.tray_icon.isVisible():
self.tray_icon.showMessage("Agent Minimized", "Gemini Agent is running in the background.", QSystemTrayIcon.Information, 2000)
else: print("Agent hidden (no system tray message as tray is not available/visible).")
def actual_quit(self):
print("Quitting application via tray menu.")
if hasattr(self, 'tray_icon') and self.tray_icon.isVisible(): self.tray_icon.hide()
if self.active_gemini_runnable:
print("actual_quit: Cancelling active Gemini runnable."); self.active_gemini_runnable.cancel()
print("actual_quit: Waiting for QThreadPool to finish...")
self.thread_pool.clear(); self.thread_pool.waitForDone(1000)
QApplication.instance().quit()
@Slot(bool)
def handle_auto_start_toggle(self, checked):
if checked: self.enable_auto_start()
else: self.disable_auto_start()
self.auto_start_action.setChecked(self.app_settings.get("auto_start_enabled", False))
def enable_auto_start(self):
if not autorun:
print("WARNING: 'autorun' library not available. Auto-start feature disabled.")
QMessageBox.warning(self, "Auto-start Error", "The 'autorun' library is not installed or failed to import. Please install it to use this feature (`pip install autorun`).")
self.app_settings["auto_start_enabled"] = False
self._save_config_settings()
return
try:
script_path = os.path.abspath(__file__)
autorun.add("GeminiDesktopAgent", sys.executable, args=[script_path, "--started-from-autorun"])
print("Auto-start enabled successfully.")
self.statusBar().showMessage("Auto-start enabled.", 3000)
self.app_settings["auto_start_enabled"] = True
except Exception as e:
print(f"Error enabling auto-start: {e}")
QMessageBox.warning(self, "Auto-start Error", f"Could not enable auto-start: {e}")
self.app_settings["auto_start_enabled"] = False
self._save_config_settings()
def disable_auto_start(self):
if not autorun:
print("WARNING: 'autorun' library not available. Cannot manage auto-start.")
return
try:
autorun.remove("GeminiDesktopAgent")
print("Auto-start disabled successfully.")
self.statusBar().showMessage("Auto-start disabled.", 3000)
self.app_settings["auto_start_enabled"] = False
except Exception as e:
print(f"Error disabling auto-start (entry might not exist or other issue): {e}")
self.app_settings["auto_start_enabled"] = False
self._save_config_settings()
def _load_or_create_initial_session(self):
self.sessions = db_manager.load_all_sessions()
if not self.sessions:
first_session = self._create_new_session(title="Initial Chat")
db_manager.save_session(first_session)
self._add_message_to_current_session("system", f"Chat session started: {first_session.title}")
else:
sorted_sessions = sorted(self.sessions, key=lambda s: s.last_modified_time, reverse=True)
self.current_session_id = sorted_sessions[0].session_id
current_s = self.get_current_session()
if current_s:
current_s.messages = db_manager.load_messages_for_session(self.current_session_id)
self._redisplay_current_session_messages()
self._update_history_panel()
def _setup_ui(self, main_layout): # main_layout is QHBoxLayout for the central widget
# Main splitter for three columns
splitter = QSplitter(Qt.Horizontal)
main_layout.addWidget(splitter) # Add splitter to the layout of central widget
# --- Left Column (Navigation & Chat History) ---
left_column_widget = QWidget()
left_column_widget.setObjectName("LeftColumnWidget")
left_column_layout = QVBoxLayout(left_column_widget)
left_column_layout.setContentsMargins(10, 10, 10, 10)
left_column_layout.setSpacing(8)
# Profile/Logo area (Placeholder)
profile_area_layout = QHBoxLayout()
profile_pic_label = QLabel() # Placeholder for circle image
profile_pic_label.setFixedSize(32, 32)
profile_pic_label.setStyleSheet("background-color: #50fa7b; border-radius: 16px;") # Temp color
profile_area_layout.addWidget(profile_pic_label)
profile_area_layout.addStretch(1)
left_column_layout.addLayout(profile_area_layout)
chat_history_title = QLabel("Chat History")
chat_history_title.setObjectName("TitleLabel")
left_column_layout.addWidget(chat_history_title)
self.history_search_field = QLineEdit(placeholderText="Search history...")
left_column_layout.addWidget(self.history_search_field)
self.new_chat_button = QPushButton("➕ New Chat")
self.new_chat_button.clicked.connect(self.handle_new_chat_button)
left_column_layout.addWidget(self.new_chat_button)
self.history_list_widget = QListWidget()
self.history_list_widget.setObjectName("historyPanel") # Keep for potential specific styling
self.history_list_widget.itemClicked.connect(self._load_session_from_history_item)
left_column_layout.addWidget(self.history_list_widget, 1) # Stretch factor
# Bottom settings bar (Placeholder)
left_bottom_bar_layout = QHBoxLayout()
settings_btn = QPushButton(); settings_btn.setIcon(self.style().standardIcon(QStyle.SP_FileDialogDetailedView)) # Placeholder icon
settings_btn.setToolTip("Settings")
help_btn = QPushButton(); help_btn.setIcon(self.style().standardIcon(QStyle.SP_MessageBoxQuestion)) # Placeholder icon
help_btn.setToolTip("Help")
left_bottom_bar_layout.addWidget(settings_btn); left_bottom_bar_layout.addWidget(help_btn)
left_bottom_bar_layout.addStretch(1)
left_column_layout.addLayout(left_bottom_bar_layout)
splitter.addWidget(left_column_widget)
# --- Middle Column (Chat Window / KI Interaction) ---
middle_column_widget = QWidget()
middle_column_widget.setObjectName("MiddleColumnWidget")
middle_column_layout = QVBoxLayout(middle_column_widget)
middle_column_layout.setContentsMargins(0, 0, 0, 0) # No margins, panel has radius
middle_column_layout.setSpacing(0) # No spacing, manage padding internally
# Chat Header (Placeholder)
chat_header_widget = QWidget()
chat_header_widget.setObjectName("ChatHeaderWidget") # For styling
chat_header_widget.setFixedHeight(50)
chat_header_widget.setStyleSheet(f"background-color: {STYLE_CONSTANTS['PANEL_BG_COLOR']}; border-bottom: 1px solid {STYLE_CONSTANTS['BORDER_COLOR']}; border-top-left-radius: {STYLE_CONSTANTS['BORDER_RADIUS']}; border-top-right-radius: {STYLE_CONSTANTS['BORDER_RADIUS']};")
chat_header_layout = QHBoxLayout(chat_header_widget)
chat_header_layout.setContentsMargins(10,0,10,0)
ki_pic_label = QLabel(); ki_pic_label.setFixedSize(30,30); ki_pic_label.setStyleSheet("background-color: #6272a4; border-radius: 15px;")
ki_name_label = QLabel("Gemini AI <small style='color:#50fa7b;'>● Active now</small>") # Rich text for status
ki_name_label.setObjectName("TitleLabel") # Reuse title style
video_call_btn = QPushButton(); video_call_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)); video_call_btn.setFixedSize(30,30) # Placeholder
voice_call_btn = QPushButton(); voice_call_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaVolume)); voice_call_btn.setFixedSize(30,30) # Placeholder
more_menu_btn = QPushButton("..."); more_menu_btn.setFixedSize(30,30) # Placeholder
chat_header_layout.addWidget(ki_pic_label); chat_header_layout.addWidget(ki_name_label); chat_header_layout.addStretch(1)
chat_header_layout.addWidget(video_call_btn); chat_header_layout.addWidget(voice_call_btn); chat_header_layout.addWidget(more_menu_btn)
middle_column_layout.addWidget(chat_header_widget)
self.chat_area = QTextEdit(readOnly=True, placeholderText="Initializing Gemini Agent...")
self.chat_area.setObjectName("ChatArea")
self.chat_area.setTextInteractionFlags(Qt.TextBrowserInteraction)
self.chat_area.setOpenExternalLinks(True)
middle_column_layout.addWidget(self.chat_area, 1) # Stretch factor
# Input Area
input_composite_widget = QWidget() # Container for padding and consistent bg
input_composite_widget.setObjectName("ChatInputComposite")
input_composite_widget.setStyleSheet(f"background-color: {STYLE_CONSTANTS['PANEL_BG_COLOR']}; border-top: 1px solid {STYLE_CONSTANTS['BORDER_COLOR']}; border-bottom-left-radius: {STYLE_CONSTANTS['BORDER_RADIUS']}; border-bottom-right-radius: {STYLE_CONSTANTS['BORDER_RADIUS']};")
input_composite_layout = QVBoxLayout(input_composite_widget)
input_composite_layout.setContentsMargins(10,10,10,10); input_composite_layout.setSpacing(5)
self.attached_image_preview_label = QLabel(alignment=Qt.AlignCenter)
self.attached_image_preview_label.setFixedSize(80,80); self.attached_image_preview_label.hide()
self.attached_image_preview_label.setStyleSheet(f"border: 1px dashed {STYLE_CONSTANTS['BORDER_COLOR']}; border-radius: {STYLE_CONSTANTS['BORDER_RADIUS_SM']}; background-color: rgba(0,0,0,0.1);")
self.attached_image_preview_label.mousePressEvent = self.clear_attached_image_preview
input_composite_layout.addWidget(self.attached_image_preview_label, 0, Qt.AlignLeft) # Show preview above input line
input_line_layout = QHBoxLayout()
# Placeholder for Plus icon button
# attach_button = QPushButton("+"); attach_button.setFixedSize(35,35)
# input_line_layout.addWidget(attach_button)
self.input_field = QLineEdit(placeholderText="Type something or pick one from prompt gallery...")
self.input_field.returnPressed.connect(self.handle_user_input)
input_line_layout.addWidget(self.input_field, 1)
# self.attach_image_button, self.screenshot_button moved here if needed, or use the "+" button
# For now, keeping existing attach/screenshot buttons:
self.attach_image_button = QPushButton(); self.attach_image_button.setIcon(self.style().standardIcon(QStyle.SP_FileLinkIcon)); self.attach_image_button.setToolTip("Attach Image")
self.attach_image_button.clicked.connect(self.select_image_to_attach)
input_line_layout.addWidget(self.attach_image_button)
self.screenshot_button = QPushButton(); self.screenshot_button.setIcon(self.style().standardIcon(QStyle.SP_DesktopIcon)); self.screenshot_button.setToolTip("Capture Screen (Ctrl+Shift+C)")
self.screenshot_button.clicked.connect(functools.partial(self.capture_screen_and_attach, True, None))
input_line_layout.addWidget(self.screenshot_button)
# Placeholder for Mic icon button
# mic_button = QPushButton("Mic"); mic_button.setFixedSize(35,35)
# input_line_layout.addWidget(mic_button)
send_button = QPushButton(); send_button.setIcon(self.style().standardIcon(QStyle.SP_ArrowRight)) # Placeholder icon
send_button.setToolTip("Send Message")
send_button.clicked.connect(self.handle_user_input)
input_line_layout.addWidget(send_button)
input_composite_layout.addLayout(input_line_layout)
# Prompt suggestions (Placeholder)
prompt_chips_layout = QHBoxLayout()
# Example chip: chip1 = QPushButton("List recipes in JSON"); chip1.setObjectName("PromptChip")
# prompt_chips_layout.addWidget(chip1)
prompt_chips_layout.addStretch(1)
input_composite_layout.addLayout(prompt_chips_layout)
middle_column_layout.addWidget(input_composite_widget)
splitter.addWidget(middle_column_widget)
# --- Right Column (Settings / Tools / Details) ---
right_column_widget = QWidget()
right_column_widget.setObjectName("RightColumnWidget")
right_column_layout = QVBoxLayout(right_column_widget)
right_column_layout.setContentsMargins(10, 10, 10, 10)
right_column_layout.setSpacing(8)
run_settings_title = QLabel("Run Settings") # Placeholder
run_settings_title.setObjectName("TitleLabel")
right_column_layout.addWidget(run_settings_title)
# Placeholders for settings elements
# Model ComboBox
model_label = QLabel("Model:")
self.model_combo = QPushButton("Gemini Pro (Placeholder)") # Using QPushButton as temp dropdown
# self.model_combo = QComboBox(); self.model_combo.addItems(["Gemini 1.5 Pro", "Gemini 1.0 Pro"])
right_column_layout.addWidget(model_label); right_column_layout.addWidget(self.model_combo)
# Temperature Slider
temp_label = QLabel("Temperature: 0.9")
self.temp_slider = QPushButton("|||||-----") # Using QPushButton as temp slider
# self.temp_slider = QSlider(Qt.Horizontal)
right_column_layout.addWidget(temp_label); right_column_layout.addWidget(self.temp_slider)
tools_title = QLabel("Tools") # Placeholder
tools_title.setObjectName("TitleLabel")
right_column_layout.addWidget(tools_title)
# Placeholder for tool toggles
# tool1_checkbox = QCheckBox("Structured output"); right_column_layout.addWidget(tool1_checkbox)
self.context_panel = QTextEdit(readOnly=True, placeholderText="Context / Search Sources / Files") # Re-purpose for general context
self.context_panel.setObjectName("ContextPanel") # For specific styling if needed
self.context_panel.setTextInteractionFlags(Qt.TextBrowserInteraction)
self.context_panel.setOpenExternalLinks(True)
right_column_layout.addWidget(QLabel("Context Output:"), 0) # Add a label for clarity
right_column_layout.addWidget(self.context_panel, 1) # Stretch factor
right_column_layout.addStretch(1) # Push elements to top
splitter.addWidget(right_column_widget)
# Set initial splitter sizes (adjust as needed)
# Approximate Google AI Studio: Left: 20-25%, Middle: 50-60%, Right: 20-25%
total_width = self.width() # Initial width
splitter.setSizes([int(total_width*0.22), int(total_width*0.56), int(total_width*0.22)])
splitter.setCollapsible(0, False); splitter.setCollapsible(1, False); splitter.setCollapsible(2, False) # Prevent collapsing
self.statusBar().showMessage("Waiting for API Key...")
self.input_field.setEnabled(False); self.attach_image_button.setEnabled(False); self.screenshot_button.setEnabled(False)
def _create_new_session(self, title: Optional[str] = None) -> ChatSession:
if title is None: title = f"Chat {len(self.sessions) + 1} ({datetime.datetime.now().strftime('%H:%M')})"
session = ChatSession(title=title)
self.sessions.append(session); self.current_session_id = session.session_id
print(f"Created new session (in memory): ID={session.session_id}, Title='{session.title}'")
return session
def get_current_session(self) -> Optional[ChatSession]:
if self.current_session_id:
return next((s for s in self.sessions if s.session_id == self.current_session_id), None)
if not self.sessions: return self._create_new_session("Initial Session (fallback)")
self.current_session_id = sorted(self.sessions, key=lambda s: s.last_modified_time, reverse=True)[0].session_id
return self.get_current_session()
def _add_message_to_current_session(self, sender: str, text: str, image_path: Optional[str] = None, ocr_text: Optional[str] = None, is_thinking_message: bool = False, grounding_metadata: Optional[GroundingMetadata] = None):
session = self.get_current_session()
if not session:
print("CRITICAL: No current session. Creating emergency session."); session = self._create_new_session("Emergency")
db_manager.save_session(session)
if hasattr(self, 'history_list_widget'): self._update_history_panel()
formatted_text_for_ui = text
if not is_thinking_message:
if grounding_metadata:
formatted_text_for_ui = self._format_text_with_citations(text, grounding_metadata)
message_obj = session.add_message(sender, formatted_text_for_ui, image_path, ocr_text)
db_manager.save_message(message_obj, session.session_id)
session.last_modified_time = datetime.datetime.now()
db_manager.save_session(session)
if hasattr(self, 'chat_area') and session.session_id == self.current_session_id and \
(self.current_iteration_data is None or self.current_iteration_data.get('source') == "main_chat" or sender == "system" or is_thinking_message):
# Basic HTML structure for chat messages for styling potential
# For actual Glasmorphismus on bubbles, this will need significant work (likely custom delegate or web view)
# For now, simple styled text.
bubble_style = "padding: 8px 12px; border-radius: 10px; margin-bottom: 8px; max-width: 70%;"
align_style = ""
if sender == "user":
bubble_bg = STYLE_CONSTANTS['ACCENT_VIOLET'].replace("0.75", "0.6") # Slightly less opaque for bubbles
align_style = "margin-left: auto; margin-right: 5px;" # Right align
elif sender == "gemini":
bubble_bg = STYLE_CONSTANTS['ACCENT_GREY'].replace("0.75", "0.6")
align_style = "margin-left: 5px; margin-right: auto;" # Left align
else: # System, error, plugin
bubble_bg = "transparent"
# For system messages, we might not want a bubble, just text.
# Using existing logic which prepends sender name.
display_parts = []
if sender == "system_error": display_parts.append("<b>Error:</b>")
elif sender == "plugin_result": display_parts.append("<b>Plugin:</b>")
else: display_parts.append(f"<i>{sender.capitalize()}:</i>") # Italicize system messages
if image_path and not is_thinking_message: display_parts.append(f"<br>[<i>Image: {os.path.basename(image_path)}</i>]")
if ocr_text and image_path and not is_thinking_message: display_parts.append("<br>[<i>OCR Text extracted</i>]")
elif ocr_text and not is_thinking_message: display_parts.append(f"<br>[<i>OCR: {ocr_text[:30]}...</i>]")
display_parts.append(formatted_text_for_ui.replace("\n", "<br>"))
self.chat_area.append("<div>" + " ".join(display_parts) + "</div><br>")
return
# For user/gemini messages with bubbles:
# This HTML structure is a basic attempt. Real chat bubbles are complex.
# QTextEdit's HTML support is limited.
# A simple approach with background color on a div:
html_message = f"""
<div style='display: flex; justify-content: {'flex-end' if sender == 'user' else 'flex-start'};'>
<div style='background-color: {bubble_bg}; {bubble_style} {align_style} color: {STYLE_CONSTANTS['TEXT_COLOR_LIGHT']};'>
<b>{sender.capitalize()}:</b><br>
{formatted_text_for_ui.replace("\n", "<br>")}
</div>
</div>
<br>
"""
# self.chat_area.append(html_message) # This will likely not render flexbox correctly.
# Fallback to simpler append for now, styling will be main focus later.
plain_display_parts = []
if sender == "user": plain_display_parts.append("<b>You:</b>")
elif sender == "gemini": plain_display_parts.append("<b>Gemini:</b>")
# ... (other sender types if needed for non-bubble display)
if image_path and not is_thinking_message: plain_display_parts.append(f"<br>[<i>Image: {os.path.basename(image_path)}</i>]")
if ocr_text and image_path and not is_thinking_message: plain_display_parts.append("<br>[<i>OCR Text extracted</i>]")
elif ocr_text and not is_thinking_message: plain_display_parts.append(f"<br>[<i>OCR: {ocr_text[:30]}...</i>]")
plain_display_parts.append(formatted_text_for_ui.replace("\n", "<br>"))
self.chat_area.append(" ".join(plain_display_parts) + "<br>")
@Slot()
def handle_new_chat_button(self):
print("New Chat button clicked.")
new_session = self._create_new_session()
db_manager.save_session(new_session)
self.chat_area.clear(); self.context_panel.clear()
self._add_message_to_current_session("system", f"New chat started: {new_session.title}")
self._update_history_panel()
def _update_history_panel(self):
self.history_list_widget.clear()
sorted_sessions = sorted(self.sessions, key=lambda s: s.last_modified_time, reverse=True)
self.sessions = sorted_sessions
for session in self.sessions:
item_text = session.title if session.title else f"Session ({session.start_time.strftime('%Y-%m-%d %H:%M')})"
# For custom item rendering later:
# list_item_widget = QWidget()
# item_layout = QHBoxLayout(list_item_widget)
# ... add labels for pic, name, last_msg, timestamp
# item = QListWidgetItem(self.history_list_widget)
# item.setSizeHint(list_item_widget.sizeHint())
# self.history_list_widget.setItemWidget(item, list_item_widget)
item = QListWidgetItem(item_text); item.setData(Qt.UserRole, session.session_id)
self.history_list_widget.addItem(item)
if session.session_id == self.current_session_id: self.history_list_widget.setCurrentItem(item)
def _redisplay_current_session_messages(self):
self.chat_area.clear(); self.context_panel.clear()
session = self.get_current_session()
if session:
self.chat_area.append(f"<i>Loaded chat: {session.title}</i><br><br>") # Add some space
for msg in session.messages:
# Using the same logic as _add_message_to_current_session for display
# This will need to be updated if chat bubble styling is complex
self._add_message_to_current_session(msg.sender, msg.text, msg.image_path, msg.ocr_text, is_thinking_message=False) # Ensure it's not treated as thinking
# ... (The rest of the MainApp methods from previous version) ...
# init_gemini_with_key_prompt, get_config_path, load_api_key_from_config, save_api_key_to_config,
# show_api_key_error, capture_screen_and_attach, select_image_to_attach, clear_attached_image_preview,
# handle_user_input, toggle_insight_overlay, _request_contextual_actions_from_gemini,
# handle_insight_overlay_query, handle_insight_overlay_close_request, handle_context_action,
# _start_gemini_request, process_gemini_query, handle_gemini_finished, handle_gemini_error,
# _format_text_with_citations, _display_grounding_sources, _parse_plugin_params,
# enable_input_areas, remove_last_chat_message, on_plugin_loaded, on_plugin_error,
# init_hotkey_listener, initiate_region_selection_for_overlay, handle_region_selection_for_overlay,
# _process_captured_region_for_overlay, handle_region_selection_cancelled_for_overlay, closeEvent
def init_gemini_with_key_prompt(self):
api_key_from_config = self.app_settings.get("api_key")
if api_key_from_config:
api_key = api_key_from_config
elif os.environ.get("GOOGLE_API_KEY"):
api_key = os.environ.get("GOOGLE_API_KEY")
else:
api_key, should_save = ApiKeyDialog.get_api_key_and_save_preference(self)
if not api_key: self.show_api_key_error("No API Key provided."); return
if should_save:
self.app_settings["api_key"] = api_key; self._save_config_settings()
try:
if not api_key: self.show_api_key_error("API Key not available."); return
genai.configure(api_key=api_key)
self.gemini_model = genai.GenerativeModel(model_name='gemini-pro')
self.gemini_vision_model = genai.GenerativeModel('gemini-pro-vision')
self.enable_input_areas("main_chat"); self.statusBar().showMessage("Gemini Ready.")
self.chat_area.setPlaceholderText("Ask Gemini..."); print("Gemini models initialized.")
except Exception as e:
error_msg = f"Failed to init Gemini: {e}."
if "API key not valid" in str(e):
error_msg += " Check key & Gemini API enablement."
if self.app_settings.get("api_key") == api_key:
self.app_settings["api_key"] = None; self._save_config_settings()
self.show_api_key_error(error_msg)
def get_config_path(self):
home = os.path.expanduser("~"); app_data_dir_name = ".gemini_desktop_agent"
app_dir = os.path.join(home, app_data_dir_name)
if not os.path.exists(app_dir):
try: os.makedirs(app_dir)
except OSError: print(f"Warning: Could not create app data directory: {app_dir}"); return "gemini_agent_config.json"
return os.path.join(app_dir, "config.json")
def load_api_key_from_config(self, path): return self.app_settings.get("api_key")
def save_api_key_to_config(self, key, path): self.app_settings["api_key"] = key; self._save_config_settings()
def show_api_key_error(self, error_message="API Key/Model Init Error."):
if threading.current_thread() is not threading.main_thread(): print(f"API Key Err (non-GUI): {error_message}"); return
QMessageBox.critical(self, "API Key Error", f"{error_message}\nPlease verify your API key and ensure the Google AI (Gemini) API is enabled for your project.\nThe application will have limited functionality.")
for widget_name in ["input_field", "attach_image_button", "screenshot_button"]:
if hasattr(self, widget_name) and getattr(self,widget_name): getattr(self, widget_name).setEnabled(False)
if hasattr(self, 'chat_area'): self.chat_area.setPlaceholderText("Gemini features disabled (API key error).")
self.statusBar().showMessage("Gemini features disabled. API Key error.")
@Slot(bool, QRect)
def capture_screen_and_attach(self, for_main_window_attachment=True, region: Optional[QRect] = None):
if for_main_window_attachment and (self.attached_image_path or self.attached_ocr_text): self.clear_attached_image_preview()
img_path, ocr_text_val = None, None
try:
with mss.mss() as sct:
monitor_to_capture = sct.monitors[1]
if region: capture_area = {"top": region.y() + monitor_to_capture["top"], "left": region.x() + monitor_to_capture["left"], "width": region.width(), "height": region.height(), "mon": monitor_to_capture.get("mon", 1)}
else: capture_area = monitor_to_capture
sct_img = sct.grab(capture_area); pil_image = Image.frombytes('RGB', sct_img.size, sct_img.rgb)
try:
ocr_text_val = pytesseract.image_to_string(pil_image)
if not (ocr_text_val and ocr_text_val.strip()): ocr_text_val = None
if ocr_text_val and for_main_window_attachment: self._add_message_to_current_session("system", "OCR extracted from screen" + (" region." if region else "."))
except pytesseract.TesseractNotFoundError:
msg = "Tesseract OCR not found. OCR disabled."
if for_main_window_attachment: QMessageBox.warning(self, "OCR Error", msg); self._add_message_to_current_session("system", f"Warning: {msg}")
else: print(f"OCR Err for overlay context: {msg}")
ocr_text_val = None
except Exception as e: print(f"OCR error: {e}"); ocr_text_val = None
ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f"); filename_prefix = "screenshot_region_" if region else "screenshot_full_"
app_temp_dir = os.path.join(tempfile.gettempdir(), "gemini_desktop_agent_captures")
if not os.path.exists(app_temp_dir): os.makedirs(app_temp_dir, exist_ok=True)
img_path = os.path.join(app_temp_dir, f"{filename_prefix}{ts}.png"); pil_image.save(img_path, "PNG")
if for_main_window_attachment:
self.attached_image_path = img_path; self.attached_ocr_text = ocr_text_val
pixmap = QPixmap(img_path)
if pixmap.isNull(): self.attached_image_path = None; self.attached_ocr_text = None; return None,None
self.attached_image_preview_label.setPixmap(pixmap.scaled(self.attached_image_preview_label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
self.attached_image_preview_label.setToolTip(f"Screenshot: {os.path.basename(img_path)}\n(Click to remove)"); self.attached_image_preview_label.show()
self.input_field.setPlaceholderText("Screenshot attached. Add prompt or send.")
self._add_message_to_current_session("system", "Screenshot" + (" region" if region else "") +" attached.")
return img_path, ocr_text_val
except Exception as e:
err_msg = f"Screen Capture Error: {e}"; print(err_msg);
if for_main_window_attachment: QMessageBox.warning(self, "Screen Capture Error", err_msg); self._add_message_to_current_session("system", f"Error: {e}")
return None, None
@Slot()
def select_image_to_attach(self):
if self.attached_image_path or self.attached_ocr_text: self.clear_attached_image_preview()
f_path, _ = QFileDialog.getOpenFileName(self, "Select Image", "", "Images (*.png *.jpg *.jpeg *.webp)")
if not f_path: return
if os.path.getsize(f_path) > 4*1024*1024: QMessageBox.warning(self, "Image Too Large", "Max 4MB."); return
self.attached_image_path = f_path; self.attached_ocr_text = None
px = QPixmap(f_path)
if px.isNull(): self.attached_image_path=None; return
self.attached_image_preview_label.setPixmap(px.scaled(self.attached_image_preview_label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
self.attached_image_preview_label.setToolTip(f"Attached: {os.path.basename(f_path)}\n(Click to remove)"); self.attached_image_preview_label.show()
self.input_field.setPlaceholderText("Image file attached. Add prompt or send.")
self._add_message_to_current_session("system", f"Image file {os.path.basename(f_path)} attached.")
def clear_attached_image_preview(self, event=None):
if self.attached_image_path: self._add_message_to_current_session("system", f"Attachment cleared.")
self.attached_image_path = None; self.attached_ocr_text = None
self.attached_image_preview_label.hide(); self.attached_image_preview_label.setPixmap(QPixmap())
self.input_field.setPlaceholderText("Type message or attach image...")
@Slot()
def handle_user_input(self):
txt = self.input_field.text().strip(); current_img_path = self.attached_image_path; current_ocr_text = self.attached_ocr_text
if not txt and not current_img_path: return
active_model = self.gemini_vision_model if current_img_path else self.gemini_model
if not active_model: self.show_api_key_error("Gemini model not ready."); return
self._add_message_to_current_session("user", txt, image_path=current_img_path, ocr_text=current_ocr_text)
parts = []; final_txt_for_gemini = txt
if current_ocr_text: final_txt_for_gemini = f"OCR Context:\n{current_ocr_text}\n\nPrompt:\n{txt}" if txt else f"OCR Context:\n{current_ocr_text}\n\nPrompt: Analyze."
if final_txt_for_gemini: parts.append({'text': final_txt_for_gemini})
if current_img_path:
try:
_, ext = os.path.splitext(current_img_path); mime = f"image/{ext[1:].lower().replace('jpg','jpeg')}"
with open(current_img_path,"rb") as f: parts.append({"inline_data":{"mime_type":mime,"data":f.read()}})
except Exception as e: self._add_message_to_current_session("system_error", f"Error preparing image: {e}"); self.clear_attached_image_preview(); return
if not parts: self._add_message_to_current_session("system_error", "Error: No content to send."); return
self.input_field.clear();
if self.attached_image_path or self.attached_ocr_text: self.clear_attached_image_preview()
available_tools = self.plugin_manager.get_all_tool_declarations()
generation_config = genai_types.GenerationConfig(tools=available_tools if available_tools else None)
self.process_gemini_query(parts, "main_chat", active_model, current_img_path, generation_config=generation_config)
@Slot()
def toggle_insight_overlay(self):
if self.insight_overlay.isVisible(): self.insight_overlay.hide_overlay()
else:
image_path, ocr_text = self.capture_screen_and_attach(for_main_window_attachment=False, region=None)
self.insight_overlay.set_initial_context(image_path, ocr_text)
if self.attached_image_path or self.attached_ocr_text: self.clear_attached_image_preview()
self.insight_overlay.show_overlay()
if image_path or ocr_text: self._request_contextual_actions_from_gemini(image_path, ocr_text)
else:
self.insight_overlay.remove_last_message_from_display()
self.insight_overlay.chat_display.setPlaceholderText("No screen content. Ask or 'Capture Region'.")
self.insight_overlay.update_suggested_actions([])
def _request_contextual_actions_from_gemini(self, image_path: Optional[str], ocr_text: Optional[str]):
model_to_use = self.gemini_vision_model if image_path else self.gemini_model
if not model_to_use:
self.insight_overlay.update_suggested_actions([]); self.insight_overlay.receive_gemini_response("Error: Context model not ready."); return
prompt_parts = []; available_actions_desc = ("Actions: 'email', 'url', 'copy_text', 'search_web_for_text', 'summarize_text'.")
prompt_text = ( "Analyze screen context (image/OCR). Suggest 3-4 relevant actions.\n" f"{available_actions_desc}\n" "JSON ONLY: {\"detected_actions\": [{\"label\": ..., \"type\": ..., \"value\": ...}], \"summary\": \"Optional brief summary.\"}\n" "If no actions, {\"detected_actions\": []}.\n" )
if ocr_text: prompt_text += f"OCR (max 1500 chars):\n\"\"\"\n{ocr_text[:1500]}\n\"\"\"\n"
if image_path: prompt_text += "Image provided.\n"
prompt_parts.append({'text': prompt_text})
if image_path:
try:
_, ext = os.path.splitext(image_path); mime = f"image/{ext[1:].lower().replace('jpg','jpeg')}"
with open(image_path, "rb") as f: img_bytes = f.read()
prompt_parts.append({"inline_data": {"mime_type": mime, "data": img_bytes}})
except Exception as e:
print(f"Error image for context analysis: {e}")
if not ocr_text: self.insight_overlay.update_suggested_actions([]); self.insight_overlay.receive_gemini_response("Error: Could not prep context."); return
if not ocr_text and not image_path: self.insight_overlay.update_suggested_actions([]); self.insight_overlay.receive_gemini_response("No content to analyze."); return
self.process_gemini_query(parts=prompt_parts, source="insight_overlay_context_analysis", model=model_to_use, is_context_analysis=True, generation_config=genai_types.GenerationConfig(temperature=0.2))
@Slot(str)
def handle_insight_overlay_query(self, query_text):
active_model = self.gemini_model
if not active_model: self.insight_overlay.receive_gemini_response("Error: Gemini model not ready."); return
self.insight_overlay.add_message_to_display("Gemini", "<i>Thinking...</i>")
gemini_parts = []; final_text_for_gemini = query_text
ocr_context = self.insight_overlay.context_ocr_text; img_context_path = self.insight_overlay.context_image_path
if img_context_path or ocr_context:
prompt_prefix = "Screen context:"
if img_context_path and ocr_context: prompt_prefix += f" (image provided, OCR: \"{ocr_context[:300]}...\")"
elif img_context_path: prompt_prefix += " (image provided)"
elif ocr_context: prompt_prefix += f" (OCR: \"{ocr_context[:300]}...\")"
final_text_for_gemini = f"{prompt_prefix}\nUser query: {query_text}"
if final_text_for_gemini: gemini_parts.append({'text': final_text_for_gemini})
if img_context_path:
active_model = self.gemini_vision_model
if not active_model: self.insight_overlay.receive_gemini_response("Error: Vision model not ready."); return
try:
_,ext=os.path.splitext(img_context_path); mime=f"image/{ext[1:].lower().replace('jpg','jpeg')}"
with open(img_context_path,"rb") as f: gemini_parts.append({"inline_data":{"mime_type":mime,"data":f.read()}})
except Exception as e: self.insight_overlay.receive_gemini_response(f"Error prep image: {e}"); return
if not gemini_parts: self.insight_overlay.receive_gemini_response("Error: No content."); return
self.process_gemini_query(gemini_parts, "insight_overlay_chat", active_model, img_context_path, generation_config=None)
@Slot()
def handle_insight_overlay_close_request(self):
if self.insight_overlay.isVisible(): self.insight_overlay.hide()
if self.active_gemini_runnable and (self.active_gemini_runnable.source.startswith("insight_overlay")):
self.active_gemini_runnable.cancel(); self.active_gemini_runnable = None
if self.current_iteration_data and (self.current_iteration_data['source'].startswith("insight_overlay")):
self.current_iteration_data = None
@Slot(str, object)
def handle_context_action(self, action_type: str, action_value):
self._add_message_to_current_session("system", f"Context Action: '{action_type}' for '{str(action_value)[:50]}...'")
self.insight_overlay.add_message_to_display("System", f"Action: {action_type}...")
QApplication.processEvents()
if action_type == "email":
try: webbrowser.open(f"mailto:{action_value}")
except Exception as e: self._add_message_to_current_session("system_error", f"Mailto fail: {e}")
elif action_type == "url":
try:
url = str(action_value);
if not (url.startswith("http://") or url.startswith("https://")): url = f"https://{url}"
webbrowser.open(url)
except Exception as e: self._add_message_to_current_session("system_error", f"URL open fail: {e}")
elif action_type == "copy_text":
try:
QApplication.clipboard().setText(str(action_value))
self.statusBar().showMessage(f"Copied: '{str(action_value)[:30]}...'", 3000)
self.insight_overlay.add_message_to_display("System", "Text copied.")
except Exception as e: self._add_message_to_current_session("system_error", f"Clipboard fail: {e}")
elif action_type == "search_web_for_text":
try:
query = str(action_value); search_url = f"https://www.google.com/search?q={urllib.parse.quote_plus(query)}"
webbrowser.open(search_url)
self.insight_overlay.add_message_to_display("System", f"Searching: {query}")
except Exception as e: self._add_message_to_current_session("system_error", f"Web search fail: {e}")
elif action_type == "summarize_text":
self.insight_overlay.add_message_to_display("Gemini (Summary)", str(action_value))
else:
self._add_message_to_current_session("system_error", f"Unknown context action: '{action_type}'.")
self.insight_overlay.add_message_to_display("System", f"Unknown action: {action_type}")
def _start_gemini_request(self):
if not self.current_iteration_data: print("Error: _start_gemini_request no iter_data."); return False
iter_data = self.current_iteration_data; iter_display_count = iter_data.get('iteration_count', 0) + 1
if iter_data['source'] == "main_chat":
thinking_msg_text = f"<i>Gemini (Iter {iter_display_count}): Thinking...</i>"
self._add_message_to_current_session("system", thinking_msg_text, is_thinking_message=True)
iter_data['last_thinking_message_text_content'] = thinking_msg_text