This repository has been archived by the owner on Dec 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtcs.py
executable file
·586 lines (520 loc) · 18.7 KB
/
tcs.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
#!/usr/bin/python
"""
TjebCadeStarter, a simplistic frontend for arcade machines.
Or, if you will, a very simple full-screen button menu.
"""
# Copyright (C) 2013 Jelte Jansen
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
import ConfigParser
import gtk
import os
import pango
import pygtk
import shlex
import subprocess
import sys
pygtk.require('2.0')
#
# Callbacks for gtk events
#
def cb_destroy(widget, data=None):
"""
Destroy the window
"""
gtk.main_quit()
def cb_button_gets_focus(widget, event):
"""
Change colors when button receives focus
"""
widget.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#EEEEEE'))
label = widget.get_children()[0].get_children()[0]
label.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#000000'))
def cb_button_loses_focus(widget, event):
"""
Change colors when button loses focus
"""
widget.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#707070'))
label = widget.get_children()[0].get_children()[0]
label.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#FFFFFF'))
def cb_close(widget, event, tcs):
if gtk.gdk.keyval_name(event.keyval) == 'Escape':
tcs.current_menu.back()
#
# End of callbacks for GTK events
#
#
# Helper functions
#
def create_button(menuitem):
"""
Create a button from the given menuitem
"""
label = gtk.Label(menuitem.get_name())
label.set_justify(gtk.JUSTIFY_CENTER)
label.modify_font(pango.FontDescription("sans bold 20"))
label.show()
button_hbox = gtk.HBox(True, 0)
button_hbox.pack_start(label, True, True, 0)
button_hbox.show()
button = gtk.Button()
button.add(button_hbox)
button.connect("clicked", menuitem.run)
button.connect("focus-in-event", cb_button_gets_focus)
button.connect("focus-out-event", cb_button_loses_focus)
button.show()
return button
class DirContext:
"""
Class to temporarily switch working directories
"""
def __init__(self, new_directory):
self.orig_directory = os.getcwd()
self.new_directory = new_directory
def __enter__(self):
os.chdir(self.new_directory)
def __exit__(self, *args):
os.chdir(self.orig_directory)
#
# End of helper functions
#
class Logger:
"""
Simple logger class that can be used as a context
"""
def __init__(self, filename=None):
self.filename = None
self.set_filename(filename)
self.logfile = None
def __enter__(self):
self.open_logfile()
return self
def __exit__(self, *args):
self.logfile.close()
def set_filename(self, filename = None):
"""
Sets the filename of the logfile to open with open_logfile()
Defaults to /tmp/tcs.log
"""
if filename is not None:
self.filename = filename
else:
self.filename = "/tmp/tcs.log"
def open_logfile(self):
"""
Opens a logfile with the given name. Replaces the
existing one if it succeeds. Otherwise logs an error
"""
try:
new_logfile = open(self.filename, "w")
self.close_logfile()
self.logfile = new_logfile
except IOError as ioe:
self.log.log("Error opening log file: " + str(ioe))
def close_logfile(self):
"""
Closes the logfile if one is open
"""
if self.logfile is not None:
self.logfile.close()
self.logfile = None
def log(self, msg):
"""
Logs the given message to the logfile, if any. Prints
to stdout otherwise
"""
if self.logfile is None:
print(msg)
else:
self.logfile.write(msg)
self.logfile.write("\n")
self.logfile.flush()
class MenuItem:
"""
A single menu item.
One item corresponds to one button on-screen.
It can call:
- a program (derived from config file)
- a submenu (indirectly derived from config entries that have the
submenu value set)
- a special function (either back or quit)
"""
ACTION_RUN = 1
ACTION_SUBMENU = 2
ACTION_BACK = 3
ACTION_QUIT = 4
ACTION_RELOAD = 5
ACTION_NAMES = [ "", "RUN", "SUBMENU", "BACK", "QUIT", "RELOAD" ]
def __init__(self, name, action, menu, directory=None, arguments=None):
"""
name (string): the name that is shown on screen.
action (int): an ACTION_TYPE which tells the button how to behave
menu (Menu): the menu this button belongs to
directory (string): UNUSED ATM, directory to execute the commands in
arguments (list): either a list of commands, or a 1-element list of the submenu (Menu)
"""
self.name = name
self.action = action
self.menu = menu
if directory is None:
self.directory = os.getcwd()
else:
self.directory = directory
if arguments is None:
self.args = []
else:
self.args = arguments
def run(self, _):
"""
Run the action defined by this menu item.
"""
self.menu.tcs.log.log("MenuItem activated: " +
self.get_name() +
" Action type: " +
self.ACTION_NAMES[self.action])
if self.action == MenuItem.ACTION_QUIT:
sys.exit(0)
elif self.action == MenuItem.ACTION_BACK:
self.menu.back()
elif self.action == MenuItem.ACTION_SUBMENU:
self.menu.submenu(self.args[0])
elif self.action == MenuItem.ACTION_RELOAD:
self.menu.tcs.reload_config_file()
elif self.action == MenuItem.ACTION_RUN:
with DirContext(self.directory):
for arg in self.args:
try:
self.menu.tcs.log.log("Run command: " + arg)
subprocess.call(shlex.split(arg))
except OSError as ose:
print("Error calling: " + arg)
print(ose)
def get_name(self):
"""
Returns the name of this menu item
"""
return self.name
def __str__(self):
"""
String representation, of the form name: action_type (int)
"""
return "[MenuItem] " + self.name + ": " + str(self.action)
class Menu:
"""
Menu is a collection of menuitems and a way to navigate through
them.
"""
def __init__(self, main_tcs, name, parent=None):
self.tcs = main_tcs
self.name = name
self.items = []
self.parent = parent
def back(self):
"""
Make TCS go to the parent of this menu
"""
if self.parent != None:
self.tcs.show_menu(self.parent)
self.tcs.set_button_focus(self.name.rpartition(".")[2])
def submenu(self, submenu):
"""
Go to the given submenu (a Menu)
"""
self.tcs.show_menu(submenu)
def get_name(self):
"""
Returns the name of the menu
"""
return self.name
def add_item(self, menuitem):
"""
Add a MenuItem to this menu
"""
self.items.append(menuitem)
def get_items(self):
"""
Returns a list of all the MenuItems in this menu
"""
return self.items
def get_item_count(self):
"""
Returns the number of MenuItems this menu has
"""
return len(self.items)
class TCS:
"""
Main TjebCadeStarter class. Shows the 'window' and the menus
"""
def __init__(self, config_filename, log):
self.log = log
self.log.log("Starting TjebCadeStarter")
self.config_filename = config_filename
self.menus = None
self.pixbuf = None
self.pixmap = None
self.buttonbox = None
self.window = None
self.current_menu = None
self.config = None
self.read_config_file()
def reload_config_file(self):
"""
Reloads the configuration file, and reverts to the main menu.
"""
self.read_config_file()
self.show_menu(self.current_menu)
def read_config_file(self):
"""
Read the config file from disk
"""
self.log.log("Reading config file: " + self.config_filename)
self.config = ConfigParser.ConfigParser()
self.config.readfp(open(self.config_filename))
self.parse_config_file()
self.current_menu = self.get_menu("")
def show_menu(self, menu):
"""
Show the given Menu
"""
self.log.log("Show menu: " + menu.get_name())
self.current_menu = menu
self.show_buttons()
self.set_button_focus()
def get_menu(self, menuname):
"""
Returns the menu with the given name.
If the menu doesn't exist yet, it is created with a back
button, and with a new menuitem in its parent
Menu definitions are of the form
'parent_menu.sub_menu.subsub_menu'
"""
if menuname in self.menus:
cur_menu = self.menus[menuname]
else:
self.log.log("Creating menu " + menuname)
# If this is a new menu, add it to the list
# First look up the parent and add a submenu item
menu_parts = menuname.rpartition(".")
parent_menu = self.get_menu(menu_parts[0])
cur_menu = Menu(self, menuname, parent_menu)
parent_menu.add_item(MenuItem(menu_parts[2],
MenuItem.ACTION_SUBMENU,
parent_menu,
arguments=[cur_menu]))
# Add a back button
cur_menu.add_item(MenuItem("Back", MenuItem.ACTION_BACK, cur_menu))
# Add it to the total list of menus
self.menus[menuname] = cur_menu
return cur_menu
def parse_config_file(self):
"""
Parse the main config file, and create Menus and MenuItems
from it
"""
self.menus = {}
# Add the top-level menu
self.menus[""] = Menu(self, "")
# Parse all entries
for section in self.config.sections():
name = section
commands = []
directory = None
submenu = ""
item_type = MenuItem.ACTION_RUN
if name == "TCS":
# Skip the main config section
continue
name_parts = name.rpartition(".")
submenu = name_parts[0]
for item in self.config.items(section):
if item[0] == 'command':
if item[1] == 'quit':
item_type = MenuItem.ACTION_QUIT
elif item[1] == 'reload':
item_type = MenuItem.ACTION_RELOAD
else:
commands.append(item[1])
elif item[0] == 'directory':
directory = item[1]
elif item[0] == 'submenu':
submenu = item[1]
cur_menu = self.get_menu(submenu)
menuitem = MenuItem(name_parts[2], item_type,
cur_menu, directory, commands)
cur_menu.add_item(menuitem)
def show_buttons(self):
"""
Show the buttons window element
"""
self.add_config_buttons()
self.buttonbox.show()
for child in self.buttonbox.children():
child.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#707070'))
child.modify_bg(gtk.STATE_ACTIVE, gtk.gdk.color_parse('#EEEEEE'))
child.modify_bg(gtk.STATE_PRELIGHT, gtk.gdk.color_parse('#EEEEEE'))
child.modify_bg(gtk.STATE_SELECTED, gtk.gdk.color_parse('#FF0000'))
label = child.get_children()[0].get_children()[0]
label.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#FFFFFF'))
child.modify_fg(gtk.STATE_ACTIVE, gtk.gdk.color_parse('#000000'))
child.modify_fg(gtk.STATE_PRELIGHT, gtk.gdk.color_parse('#000000'))
child.modify_fg(gtk.STATE_SELECTED, gtk.gdk.color_parse('#FFFFFF'))
def set_button_focus(self, button_name=None):
"""
If a button name is given, and it can be found, give it focus.
If no name is given, the first button is given focus.
"""
for child in self.buttonbox.children():
if button_name is None:
child.grab_focus()
return
else:
label = child.get_children()[0].get_children()[0]
if label.get_text() == button_name:
child.grab_focus()
return
def show_window(self):
"""
Create and show the main window
"""
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
#self.window.connect("delete_event", self.delete_event)
self.window.connect("configure_event", self.cb_configure_event)
self.window.connect("destroy", cb_destroy)
self.window.connect("key-press-event", cb_close, self)
self.window.set_border_width(10)
# This is where the actual buttons will go, the rest
# is layout and spacing
self.buttonbox = gtk.VBox(homogeneous=False, spacing=0)
# Layout:
# main_vbox
main_vbox = gtk.VBox(homogeneous=False, spacing=1)
top_hbox = gtk.HBox(homogeneous=False, spacing=1)
mid_hbox = gtk.HBox(homogeneous=False, spacing=1)
midleft_vbox = gtk.VBox(homogeneous=False, spacing=1)
midright_vbox = gtk.VBox(homogeneous=False, spacing=1)
bot_hbox = gtk.HBox(homogeneous=False, spacing=1)
main_vbox.add(top_hbox)
main_vbox.add(mid_hbox)
main_vbox.add(bot_hbox)
mid_hbox.add(midleft_vbox)
mid_hbox.add(self.buttonbox)
mid_hbox.add(midright_vbox)
self.window.add(main_vbox)
top_hbox.show()
mid_hbox.show()
midleft_vbox.show()
midright_vbox.show()
bot_hbox.show()
main_vbox.show()
self.window.resize(gtk.gdk.screen_width(), gtk.gdk.screen_height())
self.window.fullscreen()
self.set_background_image(self.config.get("TCS",
"background_image"))
self.window.show()
self.window.present()
gtk.gdk.display_get_default().warp_pointer(gtk.gdk.screen_get_default(),
gtk.gdk.screen_width()-2,
gtk.gdk.screen_height()-2)
def add_config_buttons(self):
"""
Add the buttons to the buttonbox
"""
for old_button in self.buttonbox.get_children():
self.buttonbox.remove(old_button)
for menuitem in self.current_menu.get_items():
self.buttonbox.add(create_button(menuitem))
def set_background_image(self, filename):
"""
Set the background image for the main window
"""
self.log.log("Loading background image " + filename)
self.pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
self.pixmap, _ = self.pixbuf.render_pixmap_and_mask()
self.window.set_app_paintable(gtk.TRUE)
self.window.realize()
self.window.window.set_back_pixmap(self.pixmap, False)
def resize_background_image(self):
"""
Resize the background image to the window size
"""
dst_width, dst_height = self.window.window.get_size()
new_pixbuf = self.pixbuf.scale_simple(dst_width,
dst_height,
gtk.gdk.INTERP_BILINEAR)
pixmap, _ = new_pixbuf.render_pixmap_and_mask()
self.window.window.set_back_pixmap(pixmap, False)
def cb_configure_event(self, widget, event):
"""
Configure event callback
"""
self.resize_background_image()
def add_command(config, section, settings):
"""
Config initializer on --init; add a command
"""
config.add_section(section)
for name, value in settings:
config.set(section, name, value)
def initialize_config_file(file_name):
"""
Config initializer on --init, initialize an example config file
"""
if os.path.exists(file_name):
print("Error: %s already exists, please remove it "
"or use a different file to initialize" % (file_name))
else:
# Initialize empty config file
confp = ConfigParser.ConfigParser()
add_command(confp, "TCS", [("background_image",
os.getcwd() +
'/images/default_background.jpg')])
add_command(confp, "Gnome Terminal",
[("command", "gnome-terminal")])
add_command(confp, "Example of three commands in a directory",
[("directory", "/home/foo/bar"),
("pre_command", "command 1"),
("command", "command 2"),
("post_command", "command 3"),
])
add_command(confp, "Quit",
[("command", "quit")])
with open(file_name, "w") as out:
confp.write(out)
print(file_name + " written")
def main():
"""
Main function, run a TCS instance.
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--init", action="store_true",
help="Initialize a configuration file")
parser.add_argument("-c", "--config", dest="config_file",
default="tcs.conf",
help="use the given configuration file")
args = parser.parse_args()
if args.init:
initialize_config_file(args.config_file)
else:
if os.path.exists(args.config_file):
with Logger() as log:
tcs = TCS(args.config_file, log)
tcs.show_window()
tcs.show_menu(tcs.current_menu)
gtk.main()
else:
print("Config file " + args.config_file +
" not found, please use --init to generate one")
if __name__ == "__main__":
main()