-
Notifications
You must be signed in to change notification settings - Fork 0
/
uigtk.py
1469 lines (1148 loc) · 62.9 KB
/
uigtk.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Itaka 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 3 of the License, or
# any later version.
#
# Itaka 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 Itaka; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# Copyright 2003-2009 Marc E.
# http://itaka.jardinpresente.com.ar
#
# $Id$
""" Itaka GTK+ GUI """
import copy
import datetime
import os
import sys
import signal
import traceback
try:
from twisted.internet import gtk2reactor
try:
gtk2reactor.install()
except Exception, e:
print_e(_('Could not initiate GTK modules: %s' % (e)))
sys.exit(1)
from twisted.internet import reactor
except ImportError:
print_e(_('Could not import Twisted Network Framework'))
traceback.print_exc()
sys.exit(1)
try:
import server as iserver
import error
except ImportError:
print_e(_('Failed to import Itaka modules'))
traceback.print_exc()
sys.exit(1)
try:
import pygtk
pygtk.require("2.0")
except ImportError:
print_w(_('Pygtk module is missing'))
pass
try:
import gtk, gobject, pango
except ImportError:
print_e(_('GTK+ bindings are missing'))
sys.exit(1)
if gtk.gtk_version[1] < 10:
print_e(_('Itaka requires GTK+ 2.10, you have %s installed' % (".".join(str(x) for x in gtk.gtk_version))))
sys.exit(1)
class GuiLog:
"""
GTK+ GUI logging handler
"""
def __init__(self, gui_instance, console, configuration):
"""
Constructor
@type gui_instance: instance
@param gui_instance: Instance of L{Gui}
@type console: instance
@param console: Instance of L{Console}
@type configuration: dict
@param configuration: Configuration values dictionary from L{ConfigParser}
"""
self.gui = gui_instance
self.console = console
self.configuration = configuration
def twisted_observer(self, args):
"""
A log observer for our Twisted server
Interestingly it carries a time timestamp.
datetime.datetime.fromtimestamp(args['time']).strftime("%b %d %H:%M:%S")
@type args: dict
@param args: dict {'key': [str(message)]}
"""
# Handle twisted errors
# 'isError': 1, 'failure': <twisted.python.failure.Failure <type 'exceptions.AttributeError'>>
if args.has_key('isError') and args['isError'] == 1:
self.msg = str(args['failure'])
else:
self.msg = args['message'][0]
self._write_server_log(self.msg, False)
def message(self, message, icon=None):
"""
Write normal message on Gui log widgets
@type message: str
@param message: Message to be inserted
@type icon: tuple
@param icon: The first argument is a string of either 'stock' or 'pixbuf', and the second is a string of gtk.STOCK_ICON or a gtk.gdk.pixbuf object (without the 'gtk.' prefix)
"""
if self.configuration['log']['logtimeformat']:
message = "%s %s" % (datetime.datetime.now().strftime(self.configuration['log']['logtimeformat']), message)
self.console.message(message)
self._write_gui_log(message, None, icon, False)
def verbose_message(self, message, detailed_message, icon=None):
"""
Write detailed message on Gui log widgets
@type message: str
@param message: Message to be inserted in the events log
@type detailed_message: str
@param detailed_message: Message to be inserted in the detailed log
@type icon: tuple
@param icon: The first argument is a string of either 'stock' or 'pixbuf', and the second is a string of gtk.STOCK_ICON or a gtk.gdk.pixbuf object (without the 'gtk.' prefix)
"""
if self.configuration['log']['logtimeformat']:
message = "%s %s" % (datetime.datetime.now().strftime(self.configuration['log']['logtimeformat']), message)
detailed_message = "%s %s" % (datetime.datetime.now().strftime(self.configuration['log']['logtimeformat']), detailed_message)
self.console.message(detailed_message)
self._write_gui_log(message, detailed_message, icon, False, False)
def failure(self, caller, message, failure_type='ERROR'):
"""
Write failure message on Gui log widgets
@type caller: tuple
@param caller: Specifies the class and method were the warning ocurred
@type message: tuple
@param message: A tuple containing first the simple message to the events log, and then the detailed message for the detailed log
@type failure_type: str
@param failure_type: What kind of failure it is, either 'ERROR' (default), 'WARNING' or 'DEBUG'
"""
self.simple_message = message[0]
self.detailed_message = message[1]
if self.configuration['log']['logtimeformat']:
self.simple_message = "%s %s" % (datetime.datetime.now().strftime(self.configuration['log']['logtimeformat']), self.simple_message)
self.detailed_message = "%s %s" % (datetime.datetime.now().strftime(self.configuration['log']['logtimeformat']), self.detailed_message)
self.console.failure(caller, self.detailed_message, failure_type)
# Errors require some more actions
if failure_type == 'ERROR':
# Show the window and its widgets, set the status icon blinking timeout
if not self.gui.window.get_property("visible"):
self.gui.window.present()
self.gui.status_icon_timeout_blink()
self.gui.window.move(self.gui.window_position[0], self.gui.window_position[1])
if not self.gui.expander.get_property("sensitive"):
self.gui.expander.set_sensitive(True)
if not self.gui.expander.get_property("expanded"):
self.gui.expander.set_expanded(True)
# Stop the server
if self.gui.server.listening():
self.gui.stop_server(None, True)
self._write_gui_log(self.simple_message, self.detailed_message, self._get_failure_icon(failure_type), True, True)
def _get_failure_icon(self, failure_type):
"""
Return a default stock icon for a failure type
@type failure_type: str
@param failure_type: What kind of failure it is, either 'ERROR' (default), 'WARNING' or 'DEBUG'
@rtype: tuple
@return: An GTK+ stock icon definition. ['stock', 'STOCK_ICON']
"""
# Default icon is always STOCK_DIALOG_ERROR
icon = ['stock', 'STOCK_DIALOG_ERROR']
if failure_type == "WARNING":
icon = ['stock', 'STOCK_DIALOG_WARNING']
elif failure_type == "DEBUG":
icon = ['stock', 'STOCK_DIALOG_INFO']
return icon
def _write_gui_log(self, message, detailed_message=None, icon=None, unpause_logger=True, failure=False):
"""
Private method to write to both Gui logs
@type message: str
@param message: Message to be inserted
@type detailed_message: str
@param detailed_message: Optional detailed message if the event log and detailed log messages differ
@type icon: tuple
@param icon: The first argument is a string of either 'stock' or 'pixbuf', and the second is a string of gtk.STOCK_ICON or a gtk.gdk.pixbuf object (without the 'gtk.' prefix)
@type unpause_logger: bool
@param unpause_logger: Whether to unpause the GUI Logger
@type failure: bool
@param failure: Whether the message is a failure or not
"""
if detailed_message is None:
detailed_message = message
# Only write messages when the logging is unpaused. Unless we are told otherwise
if self.gui.log_paused():
if unpause_logger:
self.gui.unpause_log(True)
self._write_events_log(message, icon, failure)
self._write_detailed_log(detailed_message)
else:
self._write_events_log(message, icon, failure)
self._write_detailed_log(detailed_message)
def _write_events_log(self, message, icon=None, failure=False):
"""
Private method to write to the events log Gui widget
@type message: str
@param message: Message to be inserted
@type icon: tuple
@param icon: The first argument is a string of either 'stock' or 'pixbuf', and the second is a string of gtk.STOCK_ICON or a gtk.gdk.pixbuf object (without the 'gtk.' prefix) if its stock, or a pixbuf
@type failure: bool
@param failure: Whether the message is a failure or not
"""
if icon is not None:
if icon[0] == "stock":
self.inserted_iter = self.gui.log_events_store.append([self.gui.log_events_tree_view.render_icon(stock_id=getattr(gtk, icon[1]), size=gtk.ICON_SIZE_MENU, detail=None), message])
# Select the iter if it's a failure
if failure:
self.selection = self.gui.log_events_tree_view.get_selection()
self.selection.select_iter(self.inserted_iter)
else:
self.inserted_iter = self.gui.log_events_store.append([icon[1], message])
else:
self.inserted_iter = self.gui.log_events_store.append([icon, message])
# Scroll
self.gui.log_events_tree_view.scroll_to_cell(self.gui.log_events_tree_view.get_model().get_path(self.inserted_iter))
def _write_detailed_log(self, message, bold=True):
"""
Private method to write to the detailed log Gui widget
@type message: str
@param message: Message to be inserted
@type bold: bool
@param bold: Whether the text will be inserted as bold
"""
message = message + '\r'
if bold:
self.gui.log_details_buffer.insert_with_tags_by_name(self.gui.log_details_buffer.get_end_iter(), message, 'bold-text')
else:
self.gui.log_details_buffer.insert_at_cursor(message, len(message))
# Automatically scroll. Use wrap until fix
self.gui.log_details_text_view.scroll_mark_onscreen(self.gui.log_details_buffer.get_insert())
def _write_server_log(self, message, bold=True):
"""
Private method to write to the server log Gui widget
@type message: str
@param message: Message to be inserted
@type bold: bool
@param bold: Whether the text will be inserted as bold
"""
message = message + '\r'
if bold:
self.gui.log_server_buffer.insert_with_tags_by_name(self.gui.log_server_buffer.get_end_iter(), message, 'bold-text')
else:
self.gui.log_server_buffer.insert_at_cursor(message, len(message))
# Automatically scroll. Use wrap until fix
self.gui.log_server_text_view.scroll_mark_onscreen(self.gui.log_server_buffer.get_insert())
class Gui:
"""
GTK+ GUI
"""
def __init__(self, console_instance, configuration):
"""
Constructor
@type console_instance: instance
@param console_instance: An instance of the L{Console} class
@type configuration: tuple
@param configuration: A tuple of configuration globals and an instance of L{ConfigParser}
"""
# Load our configuration and console instances and values
self.console = console_instance
self.itaka_globals = configuration[0]
# The configuration instance has the user's preferences already loaded
self.config_instance = configuration[1]
self.configuration = self.itaka_globals.configuration_values
# Instances of our Gui Logging class and Screenshot Server
self.server = iserver.ScreenshotServer(self)
self.log = GuiLog(self, self.console, self.configuration)
self.log_is_paused = False
# Start defining widgets
self.icon_pixbuf = gtk.gdk.pixbuf_new_from_file(os.path.join(self.itaka_globals.image_dir, 'itaka.png'))
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect('destroy', self._destroy)
self.window.connect('size-allocate', self._window_size_changed)
self.window.set_title('Itaka')
self.window.set_icon(self.icon_pixbuf)
self.window.set_border_width(6)
self.window.set_default_size(425, 1)
self.window.set_position(gtk.WIN_POS_CENTER)
self.window_position = self.window.get_position()
# Create our tray icon
self.status_icon = gtk.StatusIcon()
self.status_menu = gtk.Menu()
if self.configuration['server']['authentication']:
self.status_icon.set_from_pixbuf(gtk.gdk.pixbuf_new_from_file(os.path.join(self.itaka_globals.image_dir, 'itaka-secure.png')))
else:
self.status_icon.set_from_pixbuf(self.icon_pixbuf)
self.status_icon.set_tooltip('Itaka')
self.status_icon.set_visible(True)
self.status_icon.connect('activate', self.status_icon_activate)
self.status_icon.connect('popup-menu', self.status_icon_menu, self.status_menu)
self.start_image = gtk.Image()
self.start_image.set_from_stock(gtk.STOCK_EXECUTE, gtk.ICON_SIZE_MENU)
self.stop_image = gtk.Image()
self.stop_image.set_from_stock(gtk.STOCK_STOP, gtk.ICON_SIZE_MENU)
self.menu_item_start = gtk.ImageMenuItem(_('St_art'))
self.menu_item_start.set_image(self.start_image)
self.menu_item_start.connect('activate', self.start_server, True)
self.menu_item_stop = gtk.ImageMenuItem(_('St_op'))
self.menu_item_stop.set_image(self.stop_image)
self.menu_item_stop.connect('activate', self.stop_server, True)
self.menu_item_stop.set_sensitive(False)
if self.itaka_globals.notify_available:
self.menu_item_notifications = gtk.CheckMenuItem(_('Show _Notifications'))
if self.configuration['server']['notify']:
self.menu_item_notifications.set_active(True)
self.menu_item_notifications.connect('toggled', self.status_icon_notify)
self.menu_item_separator = gtk.SeparatorMenuItem()
self.menu_item_separator1 = gtk.SeparatorMenuItem()
self.menu_item_quit = gtk.ImageMenuItem(gtk.STOCK_QUIT)
self.menu_item_quit.connect('activate', self._destroy)
self.status_menu.append(self.menu_item_start)
self.status_menu.append(self.menu_item_stop)
if self.itaka_globals.notify_available:
self.status_menu.append(self.menu_item_separator)
self.status_menu.append(self.menu_item_notifications)
self.status_menu.append(self.menu_item_separator1)
self.status_menu.append(self.menu_item_quit)
self.vbox = gtk.VBox(False, 6)
self.box = gtk.HBox(False, 0)
self.itaka_logo = gtk.Image()
if self.configuration['server']['authentication']:
self.itaka_logo.set_from_file(os.path.join(self.itaka_globals.image_dir, 'itaka-secure.png'))
else:
self.itaka_logo.set_from_file(os.path.join(self.itaka_globals.image_dir, 'itaka.png'))
self.itaka_logo.show()
self.box.pack_start(self.itaka_logo, False, False, 35)
self.button_start_stop = gtk.ToggleButton(_('Start'))
self.start_stop_image = gtk.Image()
self.start_stop_image.set_from_stock(gtk.STOCK_EXECUTE, gtk.ICON_SIZE_BUTTON)
self.button_start_stop.set_image(self.start_stop_image)
self.button_start_stop.connect('toggled', self.button_start_server)
self.button_preferences = gtk.Button(_('Preferences'), gtk.STOCK_PREFERENCES)
self.button_preferences.connect('clicked', self._expand_preferences)
# Set up some variables for our timeouts/animations
self.preferences_hidden = False
self.preferences_expanded = False
self.timeout_contract = None
self.timeout_expand = None
self.timeout_blink = None
self.box.pack_start(self.button_start_stop, True, True, 5)
self.box.pack_start(self.button_preferences, True, True, 8)
self.vbox.pack_start(self.box, False, False, 0)
self.hbox_status = gtk.HBox(False, 0)
self.label_served = gtk.Label()
self.label_last_ip = gtk.Label()
self.label_time = gtk.Label()
self.hbox_status.pack_start(self.label_last_ip, True, False, 0)
self.hbox_status.pack_start(self.label_time, True, False, 0)
self.hbox_status.pack_start(self.label_served, True, False, 0)
# Logger widget (displayed when expanded)
self.vbox_log = gtk.VBox(False, 0)
self.notebook_log = gtk.Notebook()
self.notebook_log.set_tab_pos(gtk.POS_BOTTOM)
self.label_log_events = gtk.Label(_('Events'))
self.label_log_details = gtk.Label(_('Details'))
self.label_log_server = gtk.Label(_('Server'))
self.scroll_log_events = gtk.ScrolledWindow()
self.scroll_log_events.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.scroll_log_events.set_shadow_type(gtk.SHADOW_NONE)
self.log_events_store = gtk.ListStore(gtk.gdk.Pixbuf, str)
self.log_events_tree_view = gtk.TreeView(self.log_events_store)
self.log_events_tree_view.set_property('headers-visible', False)
self.log_events_tree_view.set_property('rules-hint', True)
self.column_log_events_icon = gtk.TreeViewColumn()
self.column_log_events = gtk.TreeViewColumn()
self.log_events_tree_view.append_column(self.column_log_events_icon)
self.log_events_tree_view.append_column(self.column_log_events)
self.cell_pixbuf_log_events = gtk.CellRendererPixbuf()
self.column_log_events_icon.pack_start(self.cell_pixbuf_log_events)
self.column_log_events_icon.add_attribute(self.cell_pixbuf_log_events, 'pixbuf', 0)
self.cell_text_log_events = gtk.CellRendererText()
self.column_log_events.pack_start(self.cell_text_log_events, True)
self.column_log_events.add_attribute(self.cell_text_log_events, 'text', 1)
self.scroll_log_events.add(self.log_events_tree_view)
self.scroll_log_details = gtk.ScrolledWindow()
self.scroll_log_details.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.scroll_log_details.set_shadow_type(gtk.SHADOW_NONE)
self.log_details_text_view = gtk.TextView()
self.log_details_text_view.set_wrap_mode(gtk.WRAP_WORD)
self.log_details_text_view.set_editable(False)
self.log_details_text_view.set_size_request(-1, 160)
self.log_details_buffer = self.log_details_text_view.get_buffer()
self.log_details_buffer.create_tag ('bold-text', weight = pango.WEIGHT_BOLD)
self.scroll_log_details.add(self.log_details_text_view)
self.scroll_log_server = gtk.ScrolledWindow()
self.scroll_log_server.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.scroll_log_server.set_shadow_type(gtk.SHADOW_NONE)
self.log_server_text_view = gtk.TextView()
self.log_server_text_view.set_wrap_mode(gtk.WRAP_WORD)
self.log_server_text_view.set_editable(False)
self.log_server_text_view.set_size_request(-1, 160)
self.log_server_buffer = self.log_server_text_view.get_buffer()
self.log_server_buffer.create_tag ('bold-text', weight = pango.WEIGHT_BOLD)
self.scroll_log_server.add(self.log_server_text_view)
self.notebook_log.append_page(self.scroll_log_events, self.label_log_events)
self.notebook_log.append_page(self.scroll_log_details, self.label_log_details)
self.notebook_log.append_page(self.scroll_log_server, self.label_log_server)
self.hbox_log = gtk.HBox(False, 0)
self.button_log_clear = gtk.Button(_('Clear'))
self.button_log_clear_image = gtk.Image()
self.button_log_clear_image.set_from_stock(gtk.STOCK_CLEAR, gtk.ICON_SIZE_BUTTON)
self.button_log_clear.set_image(self.button_log_clear_image)
self.button_log_clear.connect('clicked', self._clear_logger)
self.button_log_pause = gtk.ToggleButton(_('Pause'))
self.button_log_pause_image = gtk.Image()
self.button_log_pause_image.set_from_stock(gtk.STOCK_MEDIA_PAUSE, gtk.ICON_SIZE_BUTTON)
self.button_log_pause.set_image(self.button_log_pause_image)
self.button_log_pause.connect('toggled', self.button_pause_log)
self.button_log_save = gtk.Button(_('Save'), gtk.STOCK_SAVE)
#self.button_log_save.connect('toggled', self._save_log)
self.hbox_log.pack_start(self.button_log_clear, False, False, 4)
self.hbox_log.pack_start(self.button_log_pause, False, False, 4)
self.hbox_log.pack_end(self.button_log_save, False, False, 4)
self.vbox_log.pack_start(self.notebook_log, False, False, 4)
self.vbox_log.pack_start(self.hbox_log, False, False, 4)
self.label_log_box = gtk.Label(_('<b>Server log</b>'))
self.label_log_box.set_use_markup(True)
self.expander_size_finalized = False
self.expander = gtk.Expander(None)
self.expander.set_label_widget(self.label_log_box)
self.expander.connect('notify::expanded', self._expand_logger)
self.vbox.pack_start(self.hbox_status, False, False, 4)
self.vbox.pack_start(self.expander, False, False, 0)
self.expander.set_sensitive(False)
# This is are the preference widgets that are going to be added and shown later
self.vbox_preferences = gtk.VBox(False, 7)
self.vbox_preferences_items = gtk.VBox(False, 5)
self.vbox_preferences_items.set_border_width(2)
# Create our Hboxes
for n in xrange(1, 12+1):
setattr(self, 'hbox_preferences_%d' % (n), gtk.HBox(False, 0))
self.frame_preference_settings = gtk.Frame()
self.label_preferences_settings = gtk.Label(_('<b>Preferences</b>'))
self.label_preferences_settings.set_use_markup(True)
self.frame_preference_settings.set_label_widget(self.label_preferences_settings)
self.frame_preference_settings.set_label_align(0.5, 0.5)
self.label_preferences_port = gtk.Label(_('Port'))
self.label_preferences_port.set_justify(gtk.JUSTIFY_LEFT)
self.label_preferences_port.set_alignment(0, 0.60)
self.label_preferences_auth = gtk.Label(_('Authentication'))
self.label_preferences_auth.set_justify(gtk.JUSTIFY_LEFT)
self.label_preferences_auth.set_alignment(0, 0.60)
self.label_preferences_user = gtk.Label(_('Username'))
self.label_preferences_user.set_justify(gtk.JUSTIFY_LEFT)
self.label_preferences_user.set_alignment(0, 0.60)
self.label_preferences_pass = gtk.Label(_('Password'))
self.label_preferences_pass.set_justify(gtk.JUSTIFY_LEFT)
self.label_preferences_pass.set_alignment(0, 0.60)
self.label_preferences_format = gtk.Label(_('Format'))
self.label_preferences_format.set_justify(gtk.JUSTIFY_LEFT)
self.label_preferences_format.set_alignment(0, 0.50)
self.label_preferences_quality = gtk.Label(_('Quality'))
self.label_preferences_quality.set_justify(gtk.JUSTIFY_LEFT)
self.label_preferences_quality.set_alignment(0, 0.50)
self.label_preferences_scale = gtk.Label(_('Scale'))
self.label_preferences_scale.set_justify(gtk.JUSTIFY_LEFT)
self.label_preferences_scale.set_alignment(0, 0.50)
if not self.itaka_globals.system == 'nt':
self.label_preferences_screenshot = gtk.Label(_('Window'))
self.label_preferences_screenshot.set_justify(gtk.JUSTIFY_LEFT)
self.label_preferences_screenshot.set_alignment(0, 0.50)
if self.itaka_globals.notify_available:
self.label_preferences_notifications = gtk.Label(_('Desktop notifications'))
self.label_preferences_notifications.set_justify(gtk.JUSTIFY_LEFT)
self.label_preferences_notifications.set_alignment(0, 0.50)
self.label_preferences_notifications_sound = gtk.Label(_('Audio notifications'))
self.label_preferences_notifications_sound.set_justify(gtk.JUSTIFY_LEFT)
self.label_preferences_notifications_sound.set_alignment(0, 0.50)
self.label_preferences_timestamp = gtk.Label(_('Show timestamp in log'))
self.label_preferences_timestamp.set_justify(gtk.JUSTIFY_LEFT)
self.label_preferences_timestamp.set_alignment(0, 0.50)
self.adjustment_preferences_port = gtk.Adjustment(float(self.configuration['server']['port']), 1024, 65535, 1, 0, 0)
self.spin_preferences_port = gtk.SpinButton(self.adjustment_preferences_port)
self.spin_preferences_port.set_numeric(True)
self.entry_preferences_user = gtk.Entry()
self.entry_preferences_user.set_width_chars(11)
self.entry_preferences_user.set_text(self.configuration['server']['username'])
self.entry_preferences_pass = gtk.Entry()
self.entry_preferences_pass.set_width_chars(11)
char = u'\u25cf'
if self.itaka_globals.system == 'nt':
char = '*'
self.entry_preferences_pass.set_invisible_char(char)
self.entry_preferences_pass.set_visibility(False)
self.entry_preferences_pass.set_text(self.configuration['server']['password'])
self.check_preferences_auth = gtk.CheckButton()
self.check_preferences_auth.connect('toggled', self._preferences_authentication_toggled)
if self.configuration['server']['authentication']:
self.check_preferences_auth.set_active(1)
else:
self.check_preferences_auth.set_active(0)
if not self.configuration['server']['authentication']:
self.entry_preferences_user.set_sensitive(False)
self.entry_preferences_pass.set_sensitive(False)
self.adjustment_preferences_quality = gtk.Adjustment(float(self.configuration['screenshot']['quality']), 0, 100, 1, 0, 0)
self.spin_preferences_quality = gtk.SpinButton(self.adjustment_preferences_quality)
self.spin_preferences_quality.set_numeric(True)
self.adjustment_preferences_scale = gtk.Adjustment(float(self.configuration['screenshot']['scalepercent']), 1, 100, 1, 0, 0)
self.spin_preferences_scale = gtk.SpinButton(self.adjustment_preferences_scale)
self.spin_preferences_scale.set_numeric(True)
self.combo_preferences_format = gtk.combo_box_new_text()
self.combo_preferences_format.connect('changed', self._preferences_combo_changed)
self.combo_preferences_format.append_text('JPG')
self.combo_preferences_format.append_text('PNG')
if self.configuration['screenshot']['format'] == 'jpeg':
self.combo_preferences_format.set_active(0)
else:
self.combo_preferences_format.set_active(1)
self.hbox_preferences_6.set_sensitive(False)
if self.itaka_globals.notify_available:
self.check_preferences_notifications = gtk.CheckButton()
if self.configuration['server']['notify']:
self.check_preferences_notifications.set_active(1)
else:
self.check_preferences_notifications.set_active(0)
self.check_preferences_timestamp = gtk.CheckButton()
## if self.configuration['log']['timestamp']:
## self.check_preferences_notifications.set_active(1)
## else:
## self.check_preferences_notifications.set_active(0)
self.check_preferences_notifications_sound = gtk.CheckButton()
## if self.configuration['log']['timestamp']:
## self.check_preferences_notifications.set_active(1)
## else:
## self.check_preferences_notifications.set_active(0)
if not self.itaka_globals.system == 'nt':
self.combo_preferences_screenshot = gtk.combo_box_new_text()
self.combo_preferences_screenshot.append_text(_('Fullscreen'))
self.combo_preferences_screenshot.append_text(_('Active window'))
if self.configuration['screenshot']['currentwindow']:
self.combo_preferences_screenshot.set_active(1)
else:
self.combo_preferences_screenshot.set_active(0)
self.button_preferences_close = gtk.Button('Close', gtk.STOCK_SAVE)
self.button_preferences_close.connect('clicked', self._contract_preferences)
self.button_preferences_about = gtk.Button('About', gtk.STOCK_ABOUT)
self.button_preferences_about.connect('clicked', self.about)
self.hbox_preferences_1.pack_start(self.label_preferences_port, False, False, 12)
self.hbox_preferences_1.pack_end(self.spin_preferences_port, False, False, 7)
self.hbox_preferences_2.pack_start(self.label_preferences_auth, False, False, 12)
self.hbox_preferences_3.pack_start(self.label_preferences_user, False, False, 12)
self.hbox_preferences_4.pack_end(self.entry_preferences_pass, False, False, 7)
self.hbox_preferences_4.pack_start(self.label_preferences_pass, False, False, 12)
self.hbox_preferences_3.pack_end(self.entry_preferences_user, False, False, 7)
self.hbox_preferences_2.pack_end(self.check_preferences_auth, False, False, 7)
self.hbox_preferences_5.pack_start(self.label_preferences_format, False, False, 12)
self.hbox_preferences_5.pack_end(self.combo_preferences_format, False, False, 7)
self.hbox_preferences_6.pack_start(self.label_preferences_quality, False, False, 12)
self.hbox_preferences_6.pack_end(self.spin_preferences_quality, False, False, 7)
if not self.itaka_globals.system == 'nt':
self.hbox_preferences_7.pack_start(self.label_preferences_screenshot, False, False, 12)
self.hbox_preferences_7.pack_end(self.combo_preferences_screenshot, False, False, 7)
self.hbox_preferences_8.pack_start(self.label_preferences_scale, False, False, 12)
self.hbox_preferences_8.pack_end(self.spin_preferences_scale, False, False, 7)
if self.itaka_globals.notify_available:
self.hbox_preferences_9.pack_start(self.label_preferences_notifications, False, False, 12)
self.hbox_preferences_9.pack_end(self.check_preferences_notifications, False, False, 7)
self.hbox_preferences_10.pack_start(self.label_preferences_notifications_sound, False, False, 12)
self.hbox_preferences_10.pack_end(self.check_preferences_notifications_sound, False, False, 7)
self.hbox_preferences_11.pack_start(self.label_preferences_timestamp, False, False, 12)
self.hbox_preferences_11.pack_end(self.check_preferences_timestamp, False, False, 7)
self.hbox_preferences_12.pack_start(self.button_preferences_about, False, False, 7)
self.hbox_preferences_12.pack_end(self.button_preferences_close, False, False, 7)
self.vbox_preferences_items.pack_start(self.hbox_preferences_1, False, False, 0)
self.vbox_preferences_items.pack_start(self.hbox_preferences_2, False, False, 0)
self.vbox_preferences_items.pack_start(self.hbox_preferences_3, False, False, 0)
self.vbox_preferences_items.pack_start(self.hbox_preferences_4, False, False, 0)
self.vbox_preferences_items.pack_start(self.hbox_preferences_5, False, False, 0)
self.vbox_preferences_items.pack_start(self.hbox_preferences_6, False, False, 0)
if not self.itaka_globals.system == 'nt':
self.vbox_preferences_items.pack_start(self.hbox_preferences_7, False, False, 0)
self.vbox_preferences_items.pack_start(self.hbox_preferences_8, False, False, 0)
if self.itaka_globals.notify_available:
self.vbox_preferences_items.pack_start(self.hbox_preferences_9, False, False, 0)
self.vbox_preferences_items.pack_start(self.hbox_preferences_10, False, False, 0)
self.vbox_preferences_items.pack_start(self.hbox_preferences_11, False, False, 0)
self.frame_preference_settings.add(self.vbox_preferences_items)
self.vbox_preferences.pack_start(self.frame_preference_settings, False, False, 0)
self.vbox_preferences.pack_start(self.hbox_preferences_12, False, False, 4)
self.window.add(self.vbox)
self.window.show_all()
# Once we have all our widgets shown, get the 'initial' real size, for expanding/contracting
self.window.initial_size = self.window.get_size()
def _save_preferences(self):
"""
Saves and hides the preferences dialog
"""
# So we can mess with the values in the running one and not mess up our comparison
self.current_configuration = copy.deepcopy(self.configuration)
# Switch to the proper values
self.format_value = str(self.combo_preferences_format.get_active_text())
if self.format_value == 'PNG':
self.format_value = 'png'
self.configuration['screenshot']['format'] = 'png'
else:
self.format_value = 'jpeg'
self.configuration['screenshot']['format'] = 'jpeg'
# Delete stale old screenshot
if (self.current_configuration['screenshot']['format'] != self.configuration['screenshot']['format']):
if os.path.exists(os.path.join(self.current_configuration['screenshot']['path'], 'itakashot.%s' % (self.current_configuration['screenshot']['format']))):
os.remove(os.path.join(self.current_configuration['screenshot']['path'], 'itakashot.%s' % (self.current_configuration['screenshot']['format'])))
if self.itaka_globals.console_verbosity['debug']: print_m(_("Deleting stale screenshot file '%s'" % ((os.path.join(self.current_configuration['screenshot']['path'], 'itakashot.%s' % (self.current_configuration['screenshot']['format']))))))
if self.itaka_globals.notify_available:
self.notify_value = self.check_preferences_notifications.get_active()
if self.notify_value:
self.notify_value = True
self.menu_item_notifications.set_active(True)
self.configuration['server']['notify'] = True
else:
self.notify_value = False
self.menu_item_notifications.set_active(False)
self.configuration['server']['notify'] = False
else:
self.notify_value = False
self.configuration['server']['notify'] = False
if not self.itaka_globals.system == 'nt':
if self.combo_preferences_screenshot.get_active_text() == _('Active window'):
self.configuration['screenshot']['currentwindow'] = True
self.screenshot_value = True
else:
self.configuration['screenshot']['currentwindow'] = False
self.screenshot_value = False
else:
self.screenshot_value = False
self.configuration['screenshot']['currentwindow'] = False
self.scale_value = [self.spin_preferences_scale.get_value_as_int()]
if self.scale_value[0] == 100:
self.configuration['screenshot']['scale'] = False
self.scale_value.append(False)
else:
self.configuration['screenshot']['scale'] = True
self.scale_value.append(True)
if self.configuration['screenshot']['scalepercent'] != self.scale_value[0]:
self.configuration['screenshot']['scalepercent'] = self.scale_value[0]
# Build a configuration dictionary to send to the configuration engine's
# save method. Redundant values must be included for the comparison
self.configuration_dict = {
'html':
{'html': '<img src="screenshot" alt="If you are seeing this message it means there was an error in Itaka or you are using a text-only browser.">',
'authfailure': '<p><strong>Sorry, but you cannot access this resource without authorization.</strong></p>'},
'screenshot':
{'path': self.configuration['screenshot']['path'],
'format': self.format_value,
'quality': self.spin_preferences_quality.get_value_as_int(),
'currentwindow': self.screenshot_value,
'scale': self.scale_value[1],
'scalepercent': self.scale_value[0]},
'log':
{'logtimeformat': '[%d/%b/%Y %H:%M:%S]',
'logfile': '~/.itaka/access.log'},
'server':
{'username': self.entry_preferences_user.get_text(),
'authentication': self.check_preferences_auth.get_active(),
'notify': self.notify_value,
'password': self.entry_preferences_pass.get_text(),
'port': self.spin_preferences_port.get_value_as_int()}
}
# Set them for local use now
if self.configuration['screenshot']['quality'] != self.spin_preferences_quality.get_value_as_int():
self.configuration['screenshot']['quality'] = self.spin_preferences_quality.get_value_as_int()
if self.configuration['server']['port'] != self.spin_preferences_port.get_value_as_int():
self.configuration['server']['port'] = self.spin_preferences_port.get_value_as_int()
self.restart_server()
if self.configuration['server']['authentication'] is not self.check_preferences_auth.get_active():
self.configuration['server']['authentication'] = self.check_preferences_auth.get_active()
if self.configuration['server']['username'] != self.entry_preferences_user.get_text():
self.configuration['server']['username'] = self.entry_preferences_user.get_text()
if self.configuration['server']['password'] != self.entry_preferences_pass.get_text():
self.configuration['server']['password'] = self.entry_preferences_pass.get_text()
# Check if the configuration changed
if (self.configuration_dict != self.current_configuration):
# Update the needed keys
try:
# self.config_instance.save(self.configuration_dict)
for section in self.configuration_dict:
[self.config_instance.update(section, key, value) for key, value in self.configuration_dict[section].iteritems() if key not in self.current_configuration[section] or self.current_configuration[section][key] != value]
except:
self.log.failure(('Gui', '_save_preferences'), _('Could not save preferences'), 'ERROR')
def _expand_preferences(self, *args):
"""
Expands the window for preferences
"""
# We have a race condition here. If GTK cant resize fast enough, then it gets very sluggish
# See configure-event signal of gtk.Widget
# start timer, resize, catch configure-notify, set up idle handler, when idle resize to what the size should be at this point of time, repeat
if not self.preferences_expanded:
# Close log in small screen displays
if ((gtk.gdk.screen_height() < self.itaka_globals.min_screen_height) and self.expander.get_property("expanded")):
self.expander.set_expanded(False)
if self.timeout_expand is not None:
"""NOTE: GTK+ GtkWidget.size_request() method can give you the amount of size a widget will take
however, it has to be show()ned before. For our little hack, we show the vbox_preferences widgets
but not itself, which should yield a close enough calculation."""
self.frame_preference_settings.show_all()
self.hbox_preferences_10.show_all()
"""If the logger is expanded, use that as the initial size.
_expander_size is set by our GtkWindow resize callback
but we also set a expander_size_finalized variable here
so that _window_size_changed doesnt set the new expanded_size over
again as our window is expanding here."""
self.expander_size_finalized = False
if self.expander.get_expanded():
self.window.normal_size = self.expander_size
self.expander_size_finalized = True
else:
self.window.normal_size = self.window.initial_size
self.increment = 33
if self.window.current_size[1] < self.window.normal_size[1]+self.vbox_preferences.size_request()[1]:
# Avoid overexpanding our calculation
if self.window.current_size[1]+self.increment > self.window.normal_size[1]+self.vbox_preferences.size_request()[1]:
self.increment = (self.window.normal_size[1]+self.vbox_preferences.size_request()[1] - self.window.current_size[1])
self.window.resize(self.window.current_size[0], self.window.current_size[1]+self.increment)
return True
else:
# Its done expanding, add our widgets or display it if it has been done already
self.button_preferences.set_sensitive(False)
self.preferences_expanded = True
# Reload our configuration and show the preferences
self.configuration = self.config_instance.load()
if self.preferences_hidden:
self.vbox_preferences.show_all()
else:
self.vbox.pack_start(self.vbox_preferences, False, False, 0)
self.vbox_preferences.show_all()
self.timeout_expand = None
return False
else:
self.timeout_expand = gobject.timeout_add(30, self._expand_preferences)
def _contract_preferences(self, save):
"""
Contracts the window of preferences
@type args: unknown
@param args: gtk.Widget or "False" if you don't want to save preferences, just hide the pane
"""
if self.timeout_contract is not None:
# If you dont use the normal_size proxy to our window sizes,
# it generates a nice effect of doing the animation when closing the expander also.
# While sexy, it's inconsistent, and most definately a resource hungry bug
if self.expander.get_expanded():
self.window.normal_size = self.expander_size
self.expander_size_finalized = True
else:
self.window.normal_size = self.window.initial_size
if self.vbox_preferences.get_property("visible"):
self.vbox_preferences.hide_all()
if self.window.current_size[1] > self.window.normal_size[1]:
self.window.resize(self.window.current_size[0], self.window.current_size[1]-self.increment)
return True
else:
# Done, set some variables and stop our timer
self.preferences_expanded = False
self.preferences_hidden = True
self.expander.size_finalized = False
self.button_preferences.set_sensitive(True)
# Save our settings (but not if we are on small displays and we just want to hide the pane)
if save is not False:
self._save_preferences()
self.timeout_contract = None
return False
else:
self.timeout_contract = gobject.timeout_add(30, self._contract_preferences, save)
def _window_size_changed(self, widget=None, data=None):
"""
Report the window size on change
@type widget: instance
@param widget: gtk.Widget
@type data: unknown
@param data: Unknown
"""
self.window.current_size = self.window.get_size()
# If the logger is expanded, give them a new size unless our preferences expander is working
if self.expander.get_expanded() and not self.expander_size_finalized:
self.expander_size = self.window.current_size
# If the preferences were expanded before the logger
if self.preferences_expanded:
# Cant assign tuple items
self.expander_size = [self.expander_size[0], self.expander_size[1] - self.vbox_preferences.size_request()[1]]
def status_icon_menu(self, widget, button, time, menu):
"""
Display the menu on the status icon
@type widget: instance
@param widget: gtk.Widget
@type button: int
@param button: The button pressed.
@type time: unknown
@param time: Unknown
@type menu: instance
@param menu: A gtk.Menu instance