-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pippy Latest code -1.txt
1753 lines (1506 loc) · 67.9 KB
/
Pippy Latest code -1.txt
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/python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007,2008,2009 Chris Ball, based on Collabora's
# "hellomesh" demo.
#
# Copyright (C) 2013,14 Walter Bender
# Copyright (C) 2013,14 Ignacio Rodriguez
# Copyright (C) 2013 Jorge Gomez
# Copyright (C) 2013,14 Sai Vineet
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""Pippy Activity: A simple Python programming activity ."""
import re
import os
import subprocess
from random import uniform
import locale
import json
import sys
from shutil import copy2
from signal import SIGTERM
from gettext import gettext as _
import uuid
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi import require_version
require_version('Gdk', '3.0')
require_version('Gtk', '3.0')
from gi.repository import Gdk
from gi.repository import Gtk
from gi.repository import GLib
from gi.repository import Pango
try:
require_version('Vte', '2.91')
except:
require_version('Vte', '2.90')
from gi.repository import Vte
from gi.repository import GObject
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
from sugar3.datastore import datastore
from sugar3.activity import activity as activity
from sugar3.activity.widgets import EditToolbar
from sugar3.activity.widgets import StopButton
from sugar3.activity.activity import get_bundle_path
from sugar3.graphics.alert import Alert
from sugar3.graphics.alert import ConfirmationAlert
from sugar3.graphics.alert import NotifyAlert
from sugar3.graphics.icon import Icon
from sugar3.graphics.objectchooser import ObjectChooser
from sugar3.graphics.toggletoolbutton import ToggleToolButton
from sugar3.graphics.toolbarbox import ToolbarButton
from sugar3.graphics.toolbutton import ToolButton
from sugar3.graphics.toolbarbox import ToolbarBox
from sugar3.activity.widgets import ActivityToolbarButton
from sugar3.graphics import style
from sugar3.graphics.icon import EventIcon, Icon
from gi.repository import TelepathyGLib
from jarabe.view.customizebundle import generate_unique_id
from activity import ViewSourceActivity
from activity import TARGET_TYPE_TEXT
from collabwrapper import CollabWrapper
from filedialog import FileDialog
from icondialog import IconDialog
from notebook import SourceNotebook, tab_object
from toolbars import DevelopViewToolbar
import sound_check
import logging
SLASH = '-x-SLASH-x-'
text_buffer = None
# magic prefix to use utf-8 source encoding
PYTHON_PREFIX = '''#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
# Force category names into Pootle
DEFAULT_CATEGORIES = [_('graphics'), _('math'), _('python'), _('sound'),
_('string'), _('tutorials')]
_logger = logging.getLogger('pippy-activity')
DISTUTILS_SETUP_SCRIPT = """#!/usr/bin/python3
# -*- coding: utf-8 -*-
from distutils.core import setup
setup(name='{modulename}',
version='1.0',
py_modules=[
{filenames}
],
)
""" # This is .format()'ed with the list of the file names.
DISTUTILS_SETUP_SCRIPT = """#!/usr/bin/python3
# -*- coding: utf-8 -*-
from distutils.core import setup
setup(name='{modulename}',
version='1.0',
py_modules=[
{filenames}
],
)
""" # This is .format()'ed with the list of the file names.
def _has_new_vte_api():
try:
return (Vte.MAJOR_VERSION >= 0 and
Vte.MINOR_VERSION >= 38)
except:
# Really old versions of Vte don't have VERSION
return False
def _find_object_id(activity_id, mimetype='text/x-python'):
''' Round-about way of accessing self._jobject.object_id '''
dsobjects, nobjects = datastore.find({'mime_type': [mimetype]})
for dsobject in dsobjects:
if 'activity_id' in dsobject.metadata and \
dsobject.metadata['activity_id'] == activity_id:
return dsobject.object_id
return None
class PippyActivity(ViewSourceActivity):
'''Pippy Activity as specified in activity.info'''
def __init__(self, handle):
self._pippy_instance = self
self.session_data = [] # Used to manage saving
self._loaded_session = [] # Used to manage tabs
self._py_file_loaded_from_journal = False
self._py_object_id = None
self._dialog = None
self.ai_window = None
self.chat_messages = []
sys.path.append(os.path.join(self.get_activity_root(), 'Library'))
ViewSourceActivity.__init__(self, handle)
self._collab = CollabWrapper(self)
self._collab.message.connect(self.__message_cb)
self.set_canvas(self.initialize_display())
self.after_init()
self.connect("notify::active", self.__active_cb)
self._collab.setup()
def focus():
""" Enforce focus for the text view once. """
widget = self.get_toplevel().get_focus()
textview = self._source_tabs.get_text_view()
if widget is None and textview is not None:
textview.grab_focus()
return True
return False
GLib.timeout_add(100, focus)
def initialize_display(self):
'''Build activity toolbar with title input, share button and export
buttons
'''
toolbar_box = ToolbarBox()
activity_button = ActivityToolbarButton(self)
toolbar_box.toolbar.insert(activity_button, 0)
self.set_toolbar_box(toolbar_box)
activity_button.show()
toolbar_box.show()
activity_toolbar = activity_button.page
separator = Gtk.SeparatorToolItem()
activity_toolbar.insert(separator, -1)
separator.show()
button = ToolButton('pippy-import-doc')
button.set_tooltip(_('Import Python file to new tab'))
button.connect('clicked', self._import_py_cb)
activity_toolbar.insert(button, -1)
button.show()
button = ToolButton('pippy-export-doc')
button.set_tooltip(_('Export as Pippy document'))
button.connect('clicked', self._export_document_cb)
activity_toolbar.insert(button, -1)
button.show()
button = ToolButton('pippy-export-library')
button.set_tooltip(_('Save this file to the Pippy library'))
button.connect('clicked', self._save_as_library)
activity_toolbar.insert(button, -1)
if not self._library_writable():
button.set_sensitive(False)
button.show()
button = ToolButton('pippy-export-example')
button.set_tooltip(_('Export as new Pippy example'))
button.connect('clicked', self._export_example_cb)
activity_toolbar.insert(button, -1)
button.show()
button = ToolButton('pippy-create-bundle')
button.set_tooltip(_('Create a Sugar activity bundle'))
button.connect('clicked', self._create_bundle_cb)
activity_toolbar.insert(button, -1)
button.show()
button = ToolButton('pippy-create-distutils')
# TRANS: A distutils package is used to distribute Python modules
button.set_tooltip(_('Export as a distutils package'))
button.connect('clicked', self._export_distutils_cb)
activity_toolbar.insert(button, -1)
button.show()
self._edit_toolbar = EditToolbar()
button = ToolbarButton()
button.set_page(self._edit_toolbar)
button.props.icon_name = 'toolbar-edit'
button.props.label = _('Edit')
self.get_toolbar_box().toolbar.insert(button, -1)
button.show()
self._edit_toolbar.show()
self._edit_toolbar.undo.connect('clicked', self.__undobutton_cb)
self._edit_toolbar.undo.set_sensitive(False)
self._edit_toolbar.redo.connect('clicked', self.__redobutton_cb)
self._edit_toolbar.redo.set_sensitive(False)
self._edit_toolbar.copy.connect('clicked', self.__copybutton_cb)
self._edit_toolbar.paste.connect('clicked', self.__pastebutton_cb)
view_btn = ToolbarButton()
view_toolbar = DevelopViewToolbar(self)
view_btn.props.page = view_toolbar
view_btn.props.icon_name = 'toolbar-view'
view_btn.props.label = _('View')
view_toolbar.connect('font-size-changed',
self._font_size_changed_cb)
self.get_toolbar_box().toolbar.insert(view_btn, -1)
self.view_toolbar = view_toolbar
view_toolbar.show()
actions_toolbar = self.get_toolbar_box().toolbar
self._toggle_output = ToggleToolButton('tray-show')
self._toggle_output.set_tooltip(_('Show output panel'))
self._toggle_output.connect('toggled', self._toggle_output_cb)
actions_toolbar.insert(self._toggle_output, -1)
self._toggle_output.show()
self._inverted_colors = ToggleToolButton(icon_name='dark-theme')
self._inverted_colors.set_tooltip(_('Inverted Colors'))
self._inverted_colors.set_accelerator('<Ctrl><Shift>I')
self._inverted_colors.connect(
'toggled', self.__inverted_colors_toggled_cb)
actions_toolbar.insert(self._inverted_colors, -1)
self._inverted_colors.show()
icons_path = os.path.join(get_bundle_path(), 'icons')
icon_bw = Gtk.Image()
icon_bw.set_from_file(os.path.join(icons_path, 'run_bw.svg'))
icon_bw.show()
icon_color = Gtk.Image()
icon_color.set_from_file(os.path.join(icons_path, 'run_color.svg'))
icon_color.show()
button = ToolButton(label=_('Run!'))
button.props.accelerator = _('<alt>r')
button.set_icon_widget(icon_bw)
button.set_tooltip(_('Run!'))
button.connect('clicked', self._flash_cb,
dict({'bw': icon_bw, 'color': icon_color}))
button.connect('clicked', self._go_button_cb)
actions_toolbar.insert(button, -1)
button.show()
icon_bw = Gtk.Image()
icon_bw.set_from_file(os.path.join(icons_path, 'stopit_bw.svg'))
icon_bw.show()
icon_color = Gtk.Image()
icon_color.set_from_file(os.path.join(icons_path, 'stopit_color.svg'))
icon_color.show()
button = ToolButton(label=_('Stop'))
button.props.accelerator = _('<alt>s')
button.set_icon_widget(icon_bw)
button.connect('clicked', self._flash_cb,
dict({'bw': icon_bw, 'color': icon_color}))
button.connect('clicked', self._stop_button_cb)
button.set_tooltip(_('Stop'))
actions_toolbar.insert(button, -1)
button.show()
icon_bw = Gtk.Image()
icon_bw.set_from_file(os.path.join(icons_path, 'eraser_bw.svg'))
icon_bw.show()
icon_color = Gtk.Image()
icon_color.set_from_file(os.path.join(icons_path, 'eraser_color.svg'))
icon_color.show()
button = ToolButton(label=_('Clear output panel'))
button.props.accelerator = _('<alt>c')
button.set_icon_widget(icon_bw)
button.connect('clicked', self._clear_button_cb)
button.connect('clicked', self._flash_cb,
dict({'bw': icon_bw, 'color': icon_color}))
button.set_tooltip(_('Clear output panel'))
actions_toolbar.insert(button, -1)
button.show()
# AI-assistant
# icon_assistant = Gtk.Image()
# icon_assistant.set_from_file(os.path.join(icons_path, 'pippy_assistant.svg'))
# icon_assistant.show()
# button = ToolButton(label=_('Talk with me'))
# button.set_icon_widget(icon_assistant)
# button.connect('clicked', self._clear_button_cb)
# button.set_tooltip(_('Talk with me'))
# actions_toolbar.insert(button, -1)
# button.show()
activity_toolbar.show()
separator = Gtk.SeparatorToolItem()
self.get_toolbar_box().toolbar.insert(separator, -1)
separator.show()
button = ToolButton('pippy-openoff')
button.set_tooltip(_('Open an example'))
button.connect('clicked', self._load_example_cb)
self.get_toolbar_box().toolbar.insert(button, -1)
button.show()
# AI-assistant
icon_assistant = Gtk.Image()
icon_assistant.set_from_file(os.path.join(icons_path, 'pippy_assistant.svg'))
icon_assistant.show()
button = ToolButton(label=_('Talk with me'))
button.set_icon_widget(icon_assistant)
button.connect('clicked', self._ai_chatbot)
button.set_tooltip(_('Talk with me'))
actions_toolbar.insert(button, -1)
button.show()
separator = Gtk.SeparatorToolItem()
separator.props.draw = False
separator.set_expand(True)
self.get_toolbar_box().toolbar.insert(separator, -1)
separator.show()
stop = StopButton(self)
self.get_toolbar_box().toolbar.insert(stop, -1)
stop.show()
vpane = Gtk.Paned.new(orientation=Gtk.Orientation.VERTICAL)
vpane.set_position(400) # setting initial position
self.paths = []
try:
if sound_check.finddir():
TAMTAM_AVAILABLE = True
else:
TAMTAM_AVAILABLE = False
except sound_check.SoundLibraryNotFoundError:
TAMTAM_AVAILABLE = False
data_path = os.path.join(get_bundle_path(), 'data')
# get default language from locale
locale_lang = locale.getdefaultlocale()[0]
if locale_lang is None:
lang = 'en'
else:
lang = locale_lang.split('_')[0]
_logger.debug(locale.getdefaultlocale())
_logger.debug(lang)
# construct the path for both
lang_path = os.path.join(data_path, lang)
en_lang_path = os.path.join(data_path, 'en')
# get all folders in lang examples
all_folders = []
if os.path.exists(lang_path):
for d in sorted(os.listdir(lang_path)):
all_folders.append(d)
# get all folders in English examples
for d in sorted(os.listdir(en_lang_path)):
# check if folder isn't already in list
if d not in all_folders:
all_folders.append(d)
for folder in all_folders:
# Skip sound folders if TAMTAM is not installed
if folder == 'sound' and not TAMTAM_AVAILABLE:
continue
direntry = {}
# check if dir exists in pref language, if exists, add it
if os.path.exists(os.path.join(lang_path, folder)):
direntry = {
'name': _(folder.capitalize()),
'path': os.path.join(lang_path, folder) + '/'}
# if not try to see if it's in default English path
elif os.path.exists(os.path.join(en_lang_path, folder)):
direntry = {
'name': _(folder.capitalize()),
'path': os.path.join(en_lang_path, folder) + '/'}
self.paths.append([direntry['name'], direntry['path']])
# Adding local examples
data_path = os.path.join(get_bundle_path(), 'data')
self.paths.append([_('My examples'), data_path])
self._source_tabs = SourceNotebook(self, self._collab, self._edit_toolbar)
self._source_tabs.connect('tab-added', self._add_source_cb)
self._source_tabs.connect('tab-renamed', self._rename_source_cb)
self._source_tabs.connect('tab-closed', self._close_source_cb)
if self._loaded_session:
for name, content, path in self._loaded_session:
self._source_tabs.add_tab(name, content, path)
else:
self.session_data.append(None)
self._source_tabs.add_tab() # New instance, ergo empty tab
vpane.add1(self._source_tabs)
self._source_tabs.show()
self._outbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
self._vte = Vte.Terminal()
self._vte.set_encoding('utf-8')
self._vte.set_size(30, 5)
self._vte.set_scrollback_lines(-1)
self._vte_set_colors('#000000', '#E7E7E7')
self._child_exited_handler = None
self._vte.connect('child_exited', self._child_exited_cb)
self._vte.connect('drag_data_received', self._vte_drop_cb)
self._outbox.pack_start(self._vte, True, True, 0)
outsb = Gtk.Scrollbar(orientation=Gtk.Orientation.VERTICAL)
outsb.set_adjustment(self._vte.get_vadjustment())
outsb.show()
self._outbox.pack_start(outsb, False, False, 0)
self._load_config()
vpane.add2(self._outbox)
self._outbox.show()
vpane.show()
return vpane
def _vte_set_colors(self, bg, fg):
# XXX support both Vte APIs
if _has_new_vte_api():
foreground = Gdk.RGBA()
foreground.parse(bg)
background = Gdk.RGBA()
background.parse(fg)
else:
foreground = Gdk.color_parse(bg)
background = Gdk.color_parse(fg)
self._vte.set_colors(foreground, background, [])
def after_init(self):
self._outbox.hide()
def _font_size_changed_cb(self, widget, size):
self._source_tabs.set_font_size(size)
self._vte.set_font(
Pango.FontDescription('Monospace {}'.format(size)))
def _store_config(self):
font_size = self._source_tabs.get_font_size()
_config_file_path = os.path.join(
activity.get_activity_root(), 'data',
'config.json')
with open(_config_file_path, "w") as f:
f.write(json.dumps(font_size))
def _load_config(self):
_config_file_path = os.path.join(
activity.get_activity_root(), 'data',
'config.json')
if not os.path.isfile(_config_file_path):
return
with open(_config_file_path, "r") as f:
font_size = json.loads(f.read())
self.view_toolbar.set_font_size(font_size)
self._vte.set_font(
Pango.FontDescription('Monospace {}'.format(font_size)))
def __active_cb(self, widget, event):
_logger.debug('__active_cb %r', self.props.active)
if self.props.active:
self.resume()
else:
self.pause()
def do_visibility_notify_event(self, event):
_logger.debug('do_visibility_notify_event %r', event.get_state())
if event.get_state() == Gdk.VisibilityState.FULLY_OBSCURED:
self.pause()
else:
self.resume()
def _ai_chatbot(self, button):
# Create a new window
icons_path = os.path.join(get_bundle_path(), 'icons')
if self.ai_window is not None:
print("Window already open, destroying it")
self.ai_window.destroy()
self.ai_window = None
else:
self.ai_window = Gtk.Window(title="AI Chatbot")
# Set default size to occupy a specific part of the screen
screen = Gdk.Screen.get_default()
screen_width = screen.get_width()
screen_height = screen.get_height()
window_width = int(screen_width * 0.4) # 40% of the screen width
window_height = int(screen_height * 0.855) # 85.5% of the screen height
self.ai_window.set_default_size(window_width, window_height)
self.ai_window.set_resizable(False)
self.ai_window.set_decorated(False)
self.ai_window.set_transient_for(self.get_toplevel())
self.ai_window.move((screen_width - window_width), (screen_height - window_height))
# Create a style context for the window
style_context = self.ai_window.get_style_context()
# Change the background color of the window to grey
style_context.add_class("yellow-background")
# Create a CSS provider
css_provider = Gtk.CssProvider()
# Load the CSS
css_provider.load_from_data(b"""
.yellow-background {
background-color: lightgrey;
}
.user-message {
background-color: lightblue;
border-radius: 5px;
padding: 10px;
margin: 10px;
}
.bot-message {
background-color: lightgreen;
border-radius: 5px;
padding: 10px;
margin: 10px;
}
""")
# Add the CSS provider to the screen
screen = Gdk.Screen.get_default()
style_context.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
# Create a scrolled window for the chat area
scrolled_window = Gtk.ScrolledWindow()
scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
# Create a vertical box to hold the messages
message_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
# Add the message box to the scrolled window
scrolled_window.add(message_box)
# Load previous messages if they exist
for msg, msg_type in self.chat_messages:
label = Gtk.Label(label=msg)
label.set_markup(f"<b>{msg_type}:</b> {msg}")
label.set_line_wrap(True)
label.set_max_width_chars(80)
label.get_style_context().add_class("user-message" if msg_type == "You" else "bot-message")
label.set_xalign(0) # Align left
label.set_selectable(True)
label.set_can_focus(False)
message_box.pack_start(label, False, False, 0)
message_box.show_all()
# Create a text entry to input messages
entry_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
text_entry = Gtk.Entry()
text_entry.set_placeholder_text("Ask your doubt")
# Create a button to send the message
icon_send = Gtk.Image()
icon_send.set_from_file(os.path.join(icons_path, 'send.svg'))
icon_send.show()
send_button = Gtk.Button()
send_button.set_image(icon_send)
send_button.set_tooltip_text(_("Send message"))
# Pack the text entry and send button into the entry box
entry_box.pack_start(text_entry, True, True, 0)
entry_box.pack_end(send_button, False, False, 0)
# Create a box to hold the scrolled window and entry box
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
box.pack_start(scrolled_window, True, True, 0)
box.pack_start(entry_box, False, False, 0)
# Add the box to the window
self.ai_window.add(box)
# Show the window and all its contents
self.ai_window.show_all()
def _handle_message(button, text_entry, message_box):
message = text_entry.get_text().strip()
if not message:
return
text_entry.set_text("")
self.chat_messages.append((message, "You"))
user_message = Gtk.Label(label="You: " + message)
user_message.set_markup(f"<b>You:</b> {message}")
user_message.set_line_wrap(True)
user_message.set_max_width_chars(80)
user_message.get_style_context().add_class("user-message")
user_message.set_xalign(0)
user_message.set_selectable(True)
user_message.set_can_focus(False)
message_box.pack_start(user_message, False, False, 0)
message_box.show_all()
self.send(message, message_box)
send_button.connect("clicked", lambda button: _handle_message(button, text_entry, message_box))
def send(self, message, message_box):
logging.debug('sending %s' % message)
Gdk.threads_add_timeout(GLib.PRIORITY_DEFAULT, 1000, lambda: self._simulate_ai_response(message_box))
def _simulate_ai_response(self, message_box):
ans = "This is a response."
self.chat_messages.append((ans, "Chatbot"))
bot_response = Gtk.Label(label=ans)
bot_response.set_markup(f"<b>Chatbot:</b> {ans}")
bot_response.set_line_wrap(True)
bot_response.set_max_width_chars(80)
bot_response.get_style_context().add_class("bot-message")
bot_response.set_xalign(0)
bot_response.set_selectable(True)
bot_response.set_can_focus(False)
message_box.pack_start(bot_response, False, False, 0)
message_box.show_all()
return False
def pause(self):
# FIXME: We had resume, but no pause?
pass
def resume(self):
if self._dialog is not None:
self._dialog.set_keep_above(True)
def _toggle_output_cb(self, button):
shown = button.get_active()
if shown:
self._outbox.show_all()
self._toggle_output.set_tooltip(_('Hide output panel'))
self._toggle_output.set_icon_name('tray-hide')
else:
self._outbox.hide()
self._toggle_output.set_tooltip(_('Show output panel'))
self._toggle_output.set_icon_name('tray-show')
def __inverted_colors_toggled_cb(self, button):
if button.props.active:
self._vte_set_colors('#E7E7E7', '#000000')
self._source_tabs.set_dark()
button.set_icon_name('light-theme')
button.set_tooltip(_('Normal Colors'))
else:
self._vte_set_colors('#000000', '#E7E7E7')
self._source_tabs.set_light()
button.set_icon_name('dark-theme')
button.set_tooltip(_('Inverted Colors'))
def _load_example_cb(self, widget):
widget.set_icon_name('pippy-openon')
self._dialog = FileDialog(self.paths, self, widget)
self._dialog.show()
self._dialog.run()
path = self._dialog.get_path()
if path:
if path.endswith('physics') and not self._ensure_box2d_support():
return
self._select_func_cb(path)
def _ensure_box2d_support(self):
try:
import Box2D
except ImportError:
dialog = Gtk.MessageDialog(
None, Gtk.DialogFlags.MODAL,
Gtk.MessageType.WARNING,
Gtk.ButtonsType.OK,
_('Box2D is not installed on your system'))
dialog.format_secondary_text(
_('Box2D is required to run this example.'))
from sugar3.graphics import style
dialog.modify_bg(Gtk.StateType.NORMAL, style.COLOR_TOOLBAR_GREY.get_gdk_color())
dialog.modify_fg(Gtk.StateType.NORMAL, Gdk.color_parse('white'))
dialog.run()
dialog.destroy()
return False
return True
def _add_source_cb(self, button, force=False, editor_id=None):
if self._collab._leader or force:
if editor_id is None:
editor_id = str(uuid.uuid1())
self._source_tabs.add_tab(editor_id=editor_id)
self.session_data.append(None)
self._source_tabs.get_nth_page(-1).show_all()
self._source_tabs.get_text_view().grab_focus()
if self._collab._leader:
self._collab.post(dict(
action='add-source',
editor_id=editor_id))
else:
# The leader must do it first so that they can set
# up the text buffer
self._collab.post(dict(action='add-source-request'))
# Check if dark mode enabled, apply it
self._source_tabs.update_edit_toolbar()
if self._inverted_colors.props.active:
self._source_tabs.set_dark()
def _rename_source_cb(self, notebook, page, name):
_logger.debug('_rename_source_cb %r %r' % (page, name))
self._collab.post(dict(action='rename-source', page=page, name=name))
def _close_source_cb(self, notebook, page):
self._source_tabs.update_edit_toolbar()
_logger.debug('_close_source_cb %r' % (page))
self._collab.post(dict(action='close-source', page=page))
def __message_cb(self, collab, buddy, msg):
action = msg.get('action')
if action == 'add-source-request' and self._collab._leader:
self._add_source_cb(None, force=True)
elif action == 'add-source':
self._add_source_cb(
None, force=True, editor_id=msg.get('editor_id'))
elif action == 'rename-source':
page = msg.get('page')
name = msg.get('name')
_logger.debug('__message_cb rename-source %r %r' % (page, name))
self._source_tabs.rename_tab(page, name)
elif action == 'close-source':
page = msg.get('page')
_logger.debug('__message_cb close-source %r' % (page))
self._source_tabs.close_tab(page)
def _vte_drop_cb(self, widget, context, x, y, selection, targetType, time):
if targetType == TARGET_TYPE_TEXT:
self._vte.feed_child(selection.data)
def get_data(self):
return self._source_tabs.get_all_data()
def set_data(self, data):
# Remove initial new/blank thing
self.session_data = []
self._loaded_session = []
try:
self._source_tabs.remove_page(0)
tab_object.pop(0)
self._source_tabs.last_tab = 0
except IndexError:
pass
list_ = list(zip(*data))
for name, code, path, modified, editor_id in list_:
self._source_tabs.add_tab(
label=name, editor_id=editor_id)
self.session_data.append(None) # maybe?
def _selection_cb(self, value):
self.save()
_logger.debug('clicked! %s' % value['path'])
_file = open(value['path'], 'r')
lines = _file.readlines()
self._add_source_cb(None)
text_buffer = self._source_tabs.get_text_buffer()
text_buffer.set_text(''.join(lines))
text_buffer.set_modified(False)
self._pippy_instance.metadata['title'] = value['name']
self._stop_button_cb(None)
self._reset_vte()
self._source_tabs.set_current_label(value['name'])
self._source_tabs.set_current_path(value['path'])
self._source_tabs.get_text_view().grab_focus()
def _select_func_cb(self, path):
values = {}
values['name'] = os.path.basename(path)
values['path'] = path
self._selection_cb(values)
def _timer_cb(self, button, icons):
button.set_icon_widget(icons['bw'])
button.show_all()
return False
def _flash_cb(self, button, icons):
button.set_icon_widget(icons['color'])
button.show_all()
GObject.timeout_add(400, self._timer_cb, button, icons)
def _clear_button_cb(self, button):
self.save()
self._stop_button_cb(None)
self._reset_vte()
self._source_tabs.get_text_view().grab_focus()
def _write_all_buffers(self, tmp_dir):
data = self._source_tabs.get_all_data()
zipdata = list(zip(data[0], data[1]))
for name, content in zipdata:
name = self._source_tabs.purify_name(name)
with open(os.path.join(tmp_dir, name), 'w') as f:
# Write utf-8 coding prefix if there's not one already
if re.match(r'coding[:=]\s*([-\w.]+)',
'\n'.join(content.splitlines()[:2])) is None:
f.write(PYTHON_PREFIX)
f.write(content)
def _reset_vte(self):
self._vte.grab_focus()
self._vte.feed(b'\x1B[H\x1B[J\x1B[0;39m')
def __undobutton_cb(self, button):
text_buffer = self._source_tabs.get_text_buffer()
if text_buffer.can_undo():
text_buffer.undo()
self._edit_toolbar.redo.set_sensitive(True)
if not text_buffer.can_undo():
button.set_sensitive(False)
def __redobutton_cb(self, button):
text_buffer = self._source_tabs.get_text_buffer()
if text_buffer.can_redo():
text_buffer.redo()
self._edit_toolbar.undo.set_sensitive(True)
if not text_buffer.can_redo():
button.set_sensitive(False)
def __copybutton_cb(self, button):
text_buffer = self._source_tabs.get_text_buffer()
if self._vte.get_has_selection():
self._vte.copy_clipboard()
elif text_buffer.get_has_selection():
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
text_buffer.copy_clipboard(clipboard)
def __pastebutton_cb(self, button):
text_buffer = self._source_tabs.get_text_buffer()
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
text_buffer.paste_clipboard(clipboard, None, True)
def _go_button_cb(self, button):
self._stop_button_cb(button) # Try stopping old code first.
self._reset_vte()
# FIXME: We're losing an odd race here
# Gtk.main_iteration(block=False)
if self._toggle_output.get_active() is False:
self._outbox.show_all()
self._toggle_output.set_active(True)
pippy_tmp_dir = '%s/tmp/' % self.get_activity_root()
self._write_all_buffers(pippy_tmp_dir)
current_file = os.path.join(
pippy_tmp_dir,
self._source_tabs.get_current_file_name())
# Write activity.py here too, to support pippy-based activities.
copy2('%s/activity.py' % get_bundle_path(),
'%s/tmp/activity.py' % self.get_activity_root())
# XXX Support both Vte APIs
if _has_new_vte_api():
vte_run = self._vte.spawn_sync
else:
vte_run = self._vte.fork_command_full
self._pid = vte_run(
Vte.PtyFlags.DEFAULT,
get_bundle_path(),
['/bin/sh', '-c', 'python3 %s; sleep 1' % current_file,
'PYTHONPATH=%s/library:%s' % (get_bundle_path(),
os.getenv('PYTHONPATH', ''))],
['PYTHONPATH=%s/library:%s' % (get_bundle_path(),
os.getenv('PYTHONPATH', ''))],
GLib.SpawnFlags.DO_NOT_REAP_CHILD,
None,
None, )
def _stop_button_cb(self, button):
try:
if self._pid is not None:
os.kill(self._pid[1], SIGTERM)
except:
pass # Process must already be dead.
def _library_writable(self):
return os.access(os.path.join(get_bundle_path(), 'library'), os.W_OK)
def _save_as_library(self, button):
library_dir = os.path.join(get_bundle_path(), 'library')
file_name = self._source_tabs.get_current_file_name()
text_buffer = self._source_tabs.get_text_buffer()
content = text_buffer.get_text(
*text_buffer.get_bounds(),
include_hidden_chars=True)
if not os.path.isdir(library_dir):
os.mkdir(library_dir)
with open(os.path.join(library_dir, file_name), 'w') as f:
f.write(content)
success = True
if success:
alert = NotifyAlert(5)
alert.props.title = _('Python File added to Library')
IMPORT_MESSAGE = _('The file you selected has been added'
' to the library. Use "import {importname}"'
' to import the library for using.')
alert.props.msg = IMPORT_MESSAGE.format(importname=file_name[:-3])
alert.connect('response', self._remove_alert_cb)
self.add_alert(alert)
def _export_document_cb(self, __):
self.copy()
alert = NotifyAlert()
alert.props.title = _('Saved')
alert.props.msg = _('The document has been saved to journal.')
alert.connect('response', lambda x, i: self.remove_alert(x))
self.add_alert(alert)
def _remove_alert_cb(self, alert, response_id):
self.remove_alert(alert)
def _import_py_cb(self, button):
chooser = ObjectChooser()
result = chooser.run()
if result is Gtk.ResponseType.ACCEPT:
dsitem = chooser.get_selected_object()
if dsitem.metadata['mime_type'] != 'text/x-python':