summaryrefslogtreecommitdiffstats
path: root/tuna/tuna_gui.py
blob: dbc8b3f31b938bf9060e64b6e7e7de84078e1520 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
#! /usr/bin/python
# -*- python -*-
# -*- coding: utf-8 -*-

import pygtk
pygtk.require("2.0")

import copy, ethtool, gtk, gobject, os, pango, procfs, re, schedutils, sys, tuna
import sysfs, math
import gtk.glade

try:
	from sets import Set as set
except:
	# OK, we're modern, having sets as first class citizens
	pass

# FIXME: should go to python-schedutils
( SCHED_OTHER, SCHED_FIFO, SCHED_RR, SCHED_BATCH ) = range(4)

DND_TARGET_STRING = 0
DND_TARGET_ROOTWIN = 1

DND_TARGETS = [ ('STRING', 0, DND_TARGET_STRING),
		('text/plain', 0, DND_TARGET_STRING),
		('application/x-rootwin-drop', 0, DND_TARGET_ROOTWIN) ]

tuna_glade_dirs = [ ".", "tuna", "/usr/share/tuna" ]
tuna_glade = None

def set_affinity_warning(tid, affinity):
	dialog = gtk.MessageDialog(None,
				   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
				   gtk.MESSAGE_WARNING,
				   gtk.BUTTONS_OK,
				   "Couldn't change the affinity of %d to %s!" % \
				   (tid, affinity))
	dialog.run()
	dialog.destroy()

def drop_handler_move_threads_to_cpu(new_affinity, data):
	pid_list = [ int(pid) for pid in data.split(",") ]

	return tuna.move_threads_to_cpu(new_affinity, pid_list,
					set_affinity_warning)

def drop_handler_move_irqs_to_cpu(cpus, data):
	irq_list = [ int(irq) for irq in data.split(",") ]
	new_affinity = [ reduce(lambda a, b: a | b,
			      map(lambda cpu: 1 << cpu, cpus)), ]

	for irq in irq_list:
		tuna.set_irq_affinity(irq, new_affinity)

	# FIXME: check if we really changed the affinity, but
	# its only an optimization to avoid a needless refresh
	# in the irqview, now we always refresh.
	return True

def set_store_columns(store, row, new_value):
	nr_columns = len(new_value)
	for col in range(nr_columns):
		col_weight = col + nr_columns
		cur_value = store.get_value(row, col)
		if cur_value == new_value[col]:
			new_weight = pango.WEIGHT_NORMAL
		else:
			new_weight = pango.WEIGHT_BOLD

		store.set(row, col, new_value[col], col_weight, new_weight)

class list_store_column:
	def __init__(self, name, type = gobject.TYPE_UINT):
		self.name = name
		self.type = type

def generate_list_store_columns_with_attr(columns):
	for column in columns:
		yield column.type
	for column in columns:
		yield gobject.TYPE_UINT

class cpu_socket_frame(gtk.Frame):

	( COL_FILTER, COL_CPU, COL_USAGE ) = range(3)

	def __init__(self, socket, cpus, creator):

		gtk.Frame.__init__(self, "Socket %s" % socket)

		self.socket = socket
		self.cpus = cpus
		self.nr_cpus = len(cpus)
		self.creator = creator

		self.list_store = gtk.ListStore(gobject.TYPE_BOOLEAN,
						gobject.TYPE_UINT,
						gobject.TYPE_UINT)

		self.treeview = gtk.TreeView(self.list_store)

		# Filter column
		renderer = gtk.CellRendererToggle()
		renderer.connect('toggled', self.filter_toggled, self.list_store)
		column = gtk.TreeViewColumn('Filter', renderer, active = self.COL_FILTER)
		self.treeview.append_column(column)

		# CPU# column
		column = gtk.TreeViewColumn('CPU', gtk.CellRendererText(),
					    text = self.COL_CPU)
		self.treeview.append_column(column)

		# CPU usage column
		try:
			column = gtk.TreeViewColumn('Usage', gtk.CellRendererProgress(),
						    text = self.COL_USAGE, value = self.COL_USAGE)
		except:
			# CellRendererProgress needs pygtk2 >= 2.6
			column = gtk.TreeViewColumn('Usage', gtk.CellRendererText(),
						    text = self.COL_USAGE)
		self.treeview.append_column(column)

		self.add(self.treeview)

		self.treeview.enable_model_drag_dest(DND_TARGETS,
						     gtk.gdk.ACTION_DEFAULT)
		self.treeview.connect("drag_data_received",
		 		       self.on_drag_data_received_data)
		self.treeview.connect("button_press_event",
		 		       self.on_cpu_socket_frame_button_press_event)

		self.drop_handlers = { "pid": (drop_handler_move_threads_to_cpu, self.creator.procview),
				       "irq": (drop_handler_move_irqs_to_cpu, self.creator.irqview), }

		self.drag_dest_set(gtk.DEST_DEFAULT_ALL, DND_TARGETS,
				   gtk.gdk.ACTION_DEFAULT | gtk.gdk.ACTION_MOVE)
		self.connect("drag_data_received",
			     self.on_frame_drag_data_received_data)

	def on_frame_drag_data_received_data(self, w, context, x, y,
					     selection, info, etime):
		# Move to all CPUs in this socket
		cpus = [ int(cpu.name[3:]) for cpu in self.cpus ]
		# pid list, a irq list, etc
		source, data = selection.data.split(":")

		if self.drop_handlers.has_key(source):
			if self.drop_handlers[source][0](cpus, data):
				self.drop_handlers[source][1].refresh()
		else:
			print "cpu_socket_frame: unhandled drag source '%s'" % source

	def on_drag_data_received_data(self, treeview, context, x, y,
				       selection, info, etime):
		drop_info = treeview.get_dest_row_at_pos(x, y)

		# pid list, a irq list, etc
		source, data = selection.data.split(":")

		if drop_info:
			model = treeview.get_model()
			path, position = drop_info
			iter = model.get_iter(path)
			cpus = [ model.get_value(iter, self.COL_CPU), ]
		else:
			# Move to all CPUs in this socket
			cpus = [ int(cpu.name[3:]) for cpu in self.cpus ]

		if self.drop_handlers.has_key(source):
			if self.drop_handlers[source][0](cpus, data):
				self.drop_handlers[source][1].refresh()
		else:
			print "cpu_socket_frame: unhandled drag source '%s'" % source

	def refresh(self):
		self.list_store.clear()
		for i in range(self.nr_cpus):
			cpu = self.cpus[i]
			cpunr = int(cpu.name[3:])
			usage = self.creator.cpustats[cpunr + 1].usage

			iter = self.list_store.append()
			self.list_store.set(iter,
					    self.COL_FILTER, cpunr not in self.creator.cpus_filtered,
					    self.COL_CPU, cpunr,
					    self.COL_USAGE, int(usage))
		self.treeview.show_all()

	def isolate_cpu(self, a):
		ret = self.treeview.get_path_at_pos(self.last_x, self.last_y)
		if not ret:
			return
		path, col, xpos, ypos = ret
		if not path:
			return
		row = self.list_store.get_iter(path)
		cpu = self.list_store.get_value(row, self.COL_CPU)

		self.creator.isolate_cpus([cpu,])

	def include_cpu(self, a):
		ret = self.treeview.get_path_at_pos(self.last_x, self.last_y)
		if not ret:
			return
		path, col, xpos, ypos = ret
		if not path:
			return
		row = self.list_store.get_iter(path)
		cpu = self.list_store.get_value(row, self.COL_CPU)

		self.creator.include_cpus([cpu,])

	def restore_cpu(self, a):

		self.creator.restore_cpu()

	def isolate_cpu_socket(self, a):

		# Isolate all CPUs in this socket
		cpus = [ int(cpu.name[3:]) for cpu in self.cpus ]
		self.creator.isolate_cpus(cpus)

	def include_cpu_socket(self, a):

		# Include all CPUs in this socket
		cpus = [ int(cpu.name[3:]) for cpu in self.cpus ]
		self.creator.include_cpus(cpus)

	def on_cpu_socket_frame_button_press_event(self, treeview, event):
		if event.type != gtk.gdk.BUTTON_PRESS or event.button != 3:
			return

		self.last_x = int(event.x)
		self.last_y = int(event.y)

		menu = gtk.Menu()

		include = gtk.MenuItem("I_nclude CPU")
		include_socket = gtk.MenuItem("I_nclude CPU Socket")
		isolate = gtk.MenuItem("_Isolate CPU")
		isolate_socket = gtk.MenuItem("_Isolate CPU Socket")
		restore = gtk.MenuItem("_Restore CPU")

		menu.add(include)
		menu.add(include_socket)
		menu.add(isolate)
		menu.add(isolate_socket)
		menu.add(restore)

		include.connect_object('activate', self.include_cpu, event)
		include_socket.connect_object('activate', self.include_cpu_socket, event)
		isolate.connect_object('activate', self.isolate_cpu, event)
		isolate_socket.connect_object('activate', self.isolate_cpu_socket, event)
		if not (self.creator.previous_pid_affinities or \
			self.creator.previous_irq_affinities):
			restore.set_sensitive(False)
		restore.connect_object('activate', self.restore_cpu, event)

		include.show()
		include_socket.show()
		isolate.show()
		isolate_socket.show()
		restore.show()

		menu.popup(None, None, None, event.button, event.time)

	def filter_toggled(self, cell, path, model):
		# get toggled iter
		iter = model.get_iter((int(path),))
		enabled = model.get_value(iter, self.COL_FILTER)
		cpu = model.get_value(iter, self.COL_CPU)

		enabled = not enabled
		self.creator.toggle_mask_cpu(cpu, enabled)

		# set new value
		model.set(iter, self.COL_FILTER, enabled)

class cpuview:

	def __init__(self, vpaned, hpaned, window, procview, irqview, cpus_filtered):
		self.cpus = sysfs.cpus()
		self.cpustats = procfs.cpusstats()
		self.socket_frames = {}

		self.procview = procview
		self.irqview = irqview

		vbox = window.get_child().get_child()
		socket_ids = self.cpus.sockets.keys()
		socket_ids.sort()

		nr_sockets = len(socket_ids)
		if nr_sockets > 1:
			columns = math.ceil(math.sqrt(nr_sockets))
			rows = math.ceil(nr_sockets / columns)
			box = gtk.HBox()
		else:
			box = vbox

		column = 1
		for socket_id in socket_ids:
			frame = cpu_socket_frame(socket_id,
						 self.cpus.sockets[socket_id],
						 self)
			box.pack_start(frame, False, False)
			self.socket_frames[socket_id] = frame
			if nr_sockets > 1:
				if column == columns:
					vbox.pack_start(box, True, True)
					box = gtk.HBox()
					column = 1
				else:
					column += 1

		window.show_all()

		self.cpus_filtered = cpus_filtered
		self.refresh()

		self.previous_pid_affinities = None
		self.previous_irq_affinities = None

		req = frame.size_request()
		# FIXME: what is the slack we have
		# to add to every row and column?
		width = req[0] + 16
		height = req[1] + 20
		if nr_sockets > 1:
			width *= columns
			height *= rows
		vpaned.set_position(int(height))
		hpaned.set_position(int(width))

		self.timer = gobject.timeout_add(3000, self.refresh)

	def isolate_cpus(self, cpus):
		self.previous_pid_affinities, \
		  self.previous_irq_affinities = tuna.isolate_cpus(cpus, self.cpus.nr_cpus)

		if self.previous_pid_affinities:
			self.procview.refresh()

		if self.previous_irq_affinities:
			self.irqview.refresh()

	def include_cpus(self, cpus):
		self.previous_pid_affinities, \
		  self.previous_irq_affinities = tuna.include_cpus(cpus, self.cpus.nr_cpus)

		if self.previous_pid_affinities:
			self.procview.refresh()

		if self.previous_irq_affinities:
			self.irqview.refresh()

	def restore_cpu(self):
		if not (self.previous_pid_affinities or \
			self.previous_irq_affinities):
			return
		affinities = self.previous_pid_affinities
		for pid in affinities.keys():
			try:
				schedutils.set_affinity(pid, affinities[pid])
			except:
				pass

		affinities = self.previous_irq_affinities
		for irq in affinities.keys():
			tuna.set_irq_affinity(int(irq),
					      procfs.hexbitmask(affinities[irq],
								self.cpus.nr_cpus))

		self.previous_pid_affinities = None
		self.previous_irq_affinities = None

	def toggle_mask_cpu(self, cpu, enabled):
		if enabled:
			if cpu in self.cpus_filtered:
				self.cpus_filtered.remove(cpu)
		else:
			if cpu not in self.cpus_filtered:
				self.cpus_filtered.append(cpu)

		self.procview.toggle_mask_cpu(cpu, enabled)
		self.irqview.toggle_mask_cpu(cpu, enabled)

	def refresh(self):
		self.cpustats.reload()
		for frame in self.socket_frames.keys():
			self.socket_frames[frame].refresh()
		return True

def on_affinity_text_changed(self):
	new_affinity_text = self.affinity.get_text().strip()
	if self.affinity_text != new_affinity_text:
		try:
			for cpu in new_affinity_text.strip(",").split(","):
				new_affinity_cpu_entry = int(cpu, 16)
		except:
			try:
				new_affinity = tuna.cpustring_to_list(new_affinity_text)
			except:
				if len(new_affinity_text) > 0 and new_affinity_text[-1] != "-":
					# print "not a hex number"
					self.affinity.set_text(self.affinity_text)
					return
		self.affinity_text = new_affinity_text

def invalid_affinity():
	dialog = gtk.MessageDialog(None,
				   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
				   gtk.MESSAGE_WARNING,
				   gtk.BUTTONS_OK,
				   "Invalid affinity, specify a list of CPUs!")
	dialog.run()
	dialog.destroy()
	return False

def thread_set_attributes(pid, threads, new_policy, new_prio, new_affinity, nr_cpus):
	changed = False
	curr_policy = schedutils.get_scheduler(pid)
	curr_prio = int(threads[pid]["stat"]["rt_priority"])
	if new_policy == SCHED_OTHER:
		new_prio = 0
	if curr_policy != new_policy or curr_prio != new_prio:
		try:
			schedutils.set_scheduler(pid, new_policy, new_prio)
		except:
			dialog = gtk.MessageDialog(None,
						   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
						   gtk.MESSAGE_WARNING,
						   gtk.BUTTONS_OK,
						   "Invalid parameters!")
			dialog.run()
			dialog.destroy()
			return False

		curr_policy = schedutils.get_scheduler(pid)
		if curr_policy != new_policy:
			print "couldn't change pid %d from %s(%d) to %s(%d)!" % \
			      ( pid, schedutils.schedstr(curr_policy),
				curr_prio,
				schedutils.schedstr(new_policy),
				new_prio)
		else:
			changed = True

	curr_affinity = schedutils.get_affinity(pid)
	try:
		new_affinity = [ int(a) for a in new_affinity.split(",") ]
	except:
		try:
			new_affinity = tuna.cpustring_to_list(new_affinity)
		except:
			new_affinity = procfs.bitmasklist(new_affinity, nr_cpus)

	new_affinity.sort()

	if curr_affinity != new_affinity:
		try:
			schedutils.set_affinity(pid, new_affinity)
		except:
			return invalid_affinity()

		curr_affinity = schedutils.get_affinity(pid)
		if curr_affinity != new_affinity:
			print "couldn't change pid %d from %s to %s!" % \
			      ( pid, curr_affinity, new_affinity )
		else:
			changed = True

	return changed

class irq_druid:

	def __init__(self, irqs, ps, irq):
		self.irqs = irqs
		self.ps = ps
		self.irq = irq
		self.window = gtk.glade.XML(tuna_glade, "set_irq_attributes")
		self.dialog = self.window.get_widget("set_irq_attributes")
		pixbuf = self.dialog.render_icon(gtk.STOCK_PREFERENCES,
						 gtk.ICON_SIZE_SMALL_TOOLBAR)
		self.dialog.set_icon(pixbuf)
		event_handlers = { "on_irq_affinity_text_changed" : self.on_irq_affinity_text_changed,
				   "on_sched_policy_combo_changed": self.on_sched_policy_combo_changed }
		self.window.signal_autoconnect(event_handlers)

		self.sched_pri = self.window.get_widget("irq_pri_spinbutton")
		self.sched_policy = self.window.get_widget("irq_policy_combobox")
		self.affinity = self.window.get_widget("irq_affinity_text")
		text = self.window.get_widget("irq_text")

		users = tuna.get_irq_users(irqs, irq)
		self.affinity_text = tuna.get_irq_affinity_text(irqs, irq)

		pids = ps.find_by_name("IRQ-%d" % irq)
		if pids:
			pid = pids[0]
			prio = int(ps[pid]["stat"]["rt_priority"])
			self.create_policy_model(self.sched_policy)
			self.sched_policy.set_active(schedutils.get_scheduler(pid))
			text.set_markup("IRQ <b>%u</b> (PID <b>%u</b>), pri <b>%u</b>, aff <b>%s</b>, <tt><b>%s</b></tt>" % \
					( irq, pid, prio, self.affinity_text,
					  ",".join(users)))
		else:
			self.sched_pri.set_sensitive(False)
			self.sched_policy.set_sensitive(False)
			text.set_markup("IRQ <b>%u</b>, aff <b>%s</b>, <tt><b>%s</b></tt>" % \
					( irq, self.affinity_text,
				 	  ",".join(users)))

		self.affinity.set_text(self.affinity_text)

	def create_policy_model(self, policy):
		( COL_TEXT, COL_SCHED ) = range(2)
		list_store = gtk.ListStore(gobject.TYPE_STRING,
					   gobject.TYPE_UINT)
		policy.set_model(list_store)
		renderer = gtk.CellRendererText()
		policy.pack_start(renderer, True)
		policy.add_attribute(renderer, "text", COL_TEXT)
		for pol in range(4):
			row = list_store.append()
			list_store.set(row, COL_TEXT, schedutils.schedstr(pol),
					    COL_SCHED, pol)

	def on_sched_policy_combo_changed(self, button):
		new_policy = self.sched_policy.get_active()
		if new_policy in ( SCHED_FIFO, SCHED_RR ):
			can_change_pri = True
		else:
			can_change_pri = False
		self.sched_pri.set_sensitive(can_change_pri)

	def on_irq_affinity_text_changed(self, button):
		on_affinity_text_changed(self)

	def run(self):
		changed = False
		if self.dialog.run() == gtk.RESPONSE_OK:
			new_policy = self.sched_policy.get_active()
			new_prio = self.sched_pri.get_value()
			new_affinity = self.affinity.get_text()
			pids = self.ps.find_by_name("IRQ-%d" % self.irq)
			if pids:
				if thread_set_attributes(pids[0], self.ps,
							 new_policy,
							 new_prio,
							 new_affinity,
							 self.irqs.nr_cpus):
					changed = True

			try:
				new_affinity = [ int(a) for a in new_affinity.split(",") ]
			except:
				try:
					new_affinity = tuna.cpustring_to_list(new_affinity)
				except:
					new_affinity = procfs.bitmasklist(new_affinity,
									  self.irqs.nr_cpus)

			new_affinity.sort()

			curr_affinity = self.irqs[self.irq]["affinity"]
			if curr_affinity != new_affinity:
				tuna.set_irq_affinity(self.irq,
						      procfs.hexbitmask(new_affinity,
									self.irqs.nr_cpus))
				changed = True

		self.dialog.destroy()
		return changed

class irqview:

	nr_columns = 7
	( COL_NUM, COL_PID, COL_POL, COL_PRI,
	  COL_AFF, COL_EVENTS, COL_USERS ) = range(nr_columns)
	columns = (list_store_column("IRQ"),
		   list_store_column("PID", gobject.TYPE_INT),
		   list_store_column("Policy", gobject.TYPE_STRING),
		   list_store_column("Priority", gobject.TYPE_INT),
		   list_store_column("Affinity", gobject.TYPE_STRING),
		   list_store_column("Events"),
		   list_store_column("Users", gobject.TYPE_STRING))

	def __init__(self, treeview, irqs, ps, cpus_filtered):

		self.is_root = os.getuid() == 0
		self.irqs = irqs
		self.ps = ps
		self.treeview = treeview
		self.has_threaded_irqs = tuna.has_threaded_irqs(irqs, ps)
		if not self.has_threaded_irqs:
			self.nr_columns = 4
			( self.COL_NUM,
			  self.COL_AFF,
			  self.COL_EVENTS,
			  self.COL_USERS ) = range(self.nr_columns)
			self.columns = (list_store_column("IRQ"),
					list_store_column("Affinity", gobject.TYPE_STRING),
					list_store_column("Events"),
					list_store_column("Users", gobject.TYPE_STRING))

		self.list_store = gtk.ListStore(*generate_list_store_columns_with_attr(self.columns))

		self.treeview.set_model(self.list_store)

		# Allow selecting multiple rows
		selection = treeview.get_selection()
		selection.set_mode(gtk.SELECTION_MULTIPLE)

		# Allow enable drag and drop of rows
		self.treeview.enable_model_drag_source(gtk.gdk.BUTTON1_MASK,
						       DND_TARGETS,
						       gtk.gdk.ACTION_DEFAULT | gtk.gdk.ACTION_MOVE)
		self.treeview.connect("drag_data_get", self.on_drag_data_get_data)
		self.renderer = gtk.CellRendererText()

		for col in range(self.nr_columns):
			column = gtk.TreeViewColumn(self.columns[col].name,
						    self.renderer, text = col)
			column.set_sort_column_id(col)
			column.add_attribute(self.renderer, "weight",
					     col + self.nr_columns)
			self.treeview.append_column(column)

		self.cpus_filtered = cpus_filtered
		self.refreshing = True

	def foreach_selected_cb(self, model, path, iter, irq_list):
		irq = model.get_value(iter, self.COL_NUM)
		irq_list.append(str(irq))

	def on_drag_data_get_data(self, treeview, context,
			          selection, target_id, etime):
		treeselection = treeview.get_selection()
		irq_list = []
		treeselection.selected_foreach(self.foreach_selected_cb, irq_list)
		selection.set(selection.target, 8, "irq:" + ",".join(irq_list))

	def set_irq_columns(self, iter, irq, irq_info, nics):
		new_value = [ None ] * self.nr_columns
		users = tuna.get_irq_users(self.irqs, irq, nics)
		if self.has_threaded_irqs:
			pids = self.ps.find_by_name("IRQ-%d" % irq)
			if pids:
				pid = pids[0]
				prio = int(self.ps[pid]["stat"]["rt_priority"])
				sched = schedutils.schedstr(schedutils.get_scheduler(pid))[6:]
			else:
				sched = ""
				pid = -1
				prio = -1
			new_value[self.COL_PID] = pid
			new_value[self.COL_POL] = sched
			new_value[self.COL_PRI] = prio

		new_value[self.COL_NUM] = irq
		new_value[self.COL_AFF] = tuna.get_irq_affinity_text(self.irqs, irq)
		new_value[self.COL_EVENTS] = reduce(lambda a, b: a + b, irq_info["cpu"])
		new_value[self.COL_USERS] = ",".join(users)

		set_store_columns(self.list_store, iter, new_value)

	def show(self):
		new_irqs = []
		for sirq in self.irqs.keys():
			try:
				new_irqs.append(int(sirq))
			except:
				continue

		nics = ethtool.get_active_devices()

		row = self.list_store.get_iter_first()
		while row:
			irq = self.list_store.get_value(row, self.COL_NUM)
			# IRQ was unregistered? I.e. driver unloaded?
			if not self.irqs.has_key(irq):
				if self.list_store.remove(row):
					# removed and row now its the next one
					continue
				# Was the last one
				break
			elif tuna.irq_filtered(irq, self.irqs,
					       self.cpus_filtered,
					       self.is_root):
				new_irqs.remove(irq)
				if self.list_store.remove(row):
					# removed and row now its the next one
					continue
				# Was the last one
				break
			else:
				new_irqs.remove(irq)
				irq_info = self.irqs[irq]
				self.set_irq_columns(row, irq, irq_info, nics)

			row = self.list_store.iter_next(row)

		new_irqs.sort()
		for irq in new_irqs:
			if tuna.irq_filtered(irq, self.irqs, self.cpus_filtered,
					     self.is_root):
				continue
			row = self.list_store.append()
			irq_info = self.irqs[irq]
			self.set_irq_columns(row, irq, irq_info, nics)

		self.treeview.show_all()

	def refresh(self):
		if not self.refreshing:
			return
		self.irqs.reload()
		self.show()

	def refresh_toggle(self, unused):
		self.refreshing = not self.refreshing

	def edit_attributes(self, a):
		ret = self.treeview.get_path_at_pos(self.last_x, self.last_y)
		if not ret:
			return
		path, col, xpos, ypos = ret
		if not path:
			return
		row = self.list_store.get_iter(path)
		irq = self.list_store.get_value(row, self.COL_NUM)
		if not self.irqs.has_key(irq):
			return

		dialog = irq_druid(self.irqs, self.ps, irq)
		if dialog.run():
			self.refresh(self.ps)

	def on_irqlist_button_press_event(self, treeview, event):
		if event.type != gtk.gdk.BUTTON_PRESS or event.button != 3:
			return

		self.last_x = int(event.x)
		self.last_y = int(event.y)

		menu = gtk.Menu()

		setattr = gtk.MenuItem("_Set IRQ attributes")
		if self.refreshing:
			refresh_prefix = "Sto_p refreshing the"
		else:
			refresh_prefix = "_Refresh"
		refresh = gtk.MenuItem(refresh_prefix + " IRQ list")

		menu.add(setattr)
		menu.add(refresh)

		setattr.connect_object('activate', self.edit_attributes, event)
		refresh.connect_object('activate', self.refresh_toggle, event)

		setattr.show()
		refresh.show()

		menu.popup(None, None, None, event.button, event.time)

	def toggle_mask_cpu(self, cpu, enabled):
		if not enabled:
			if cpu not in self.cpus_filtered:
				self.cpus_filtered.append(cpu)
				self.show()
		else:
			if cpu in self.cpus_filtered:
				self.cpus_filtered.remove(cpu)
				self.show()

class process_druid:

	( PROCESS_COL_PID, PROCESS_COL_NAME ) = range(2)

	def __init__(self, ps, pid, nr_cpus):
		self.ps = ps
		self.pid = pid
		self.nr_cpus = nr_cpus
		pid_info = self.ps[pid]
		self.window = gtk.glade.XML(tuna_glade, "set_process_attributes")
		self.dialog = self.window.get_widget("set_process_attributes")
		pixbuf = self.dialog.render_icon(gtk.STOCK_PREFERENCES,
						 gtk.ICON_SIZE_SMALL_TOOLBAR)
		self.dialog.set_icon(pixbuf)
		event_handlers = { "on_cmdline_regex_changed" : self.on_cmdline_regex_changed,
				   "on_affinity_text_changed" : self.on_affinity_text_changed,
				   "on_sched_policy_combo_changed" : self.on_sched_policy_combo_changed,
				   "on_command_regex_clicked" : self.on_command_regex_clicked,
				   "on_all_these_threads_clicked" : self.on_all_these_threads_clicked,
				   "on_just_this_thread_clicked" : self.on_just_this_thread_clicked }
		self.window.signal_autoconnect(event_handlers)

		self.sched_pri = self.window.get_widget("sched_pri_spin")
		self.sched_policy = self.window.get_widget("sched_policy_combo")
		self.regex_edit = self.window.get_widget("cmdline_regex")
		self.affinity = self.window.get_widget("affinity_text")
		self.just_this_thread = self.window.get_widget("just_this_thread")
		self.all_these_threads = self.window.get_widget("all_these_threads")
		processes = self.window.get_widget("matching_process_list")

		self.sched_pri.set_value(int(pid_info["stat"]["rt_priority"]))
		cmdline_regex = procfs.process_cmdline(pid_info)
		self.affinity_text = tuna.list_to_cpustring(schedutils.get_affinity(pid))
		self.affinity.set_text(self.affinity_text)
		self.create_matching_process_model(processes)
		self.create_policy_model(self.sched_policy)
		self.sched_policy.set_active(schedutils.get_scheduler(pid))
		self.regex_edit.set_text(cmdline_regex)
		self.just_this_thread.set_active(True)
		self.regex_edit.set_sensitive(False)
		if not ps[pid].has_key("threads"):
			self.all_these_threads.hide()
		self.on_just_this_thread_clicked(None)

	def refresh_match_pids(self, cmdline_regex):
		self.process_list_store.clear()
		for match_pid in self.ps.find_by_cmdline_regex(cmdline_regex):
			info = self.process_list_store.append()
			pid_info = self.ps[match_pid]
			cmdline = procfs.process_cmdline(pid_info)
			self.process_list_store.set(info, self.PROCESS_COL_PID, match_pid,
						    self.PROCESS_COL_NAME,
						    cmdline)

	def create_matching_process_model(self, processes):
		labels = [ "PID", "Name" ]

		self.process_list_store = gtk.ListStore(gobject.TYPE_UINT,
							gobject.TYPE_STRING)
		processes.set_model(self.process_list_store)
		renderer = gtk.CellRendererText()

		for col in range(len(labels)):
			column = gtk.TreeViewColumn(labels[col], renderer, text = col)
			column.set_sort_column_id(col)
			processes.append_column(column)

	def create_policy_model(self, policy):
		( COL_TEXT, COL_SCHED ) = range(2)
		list_store = gtk.ListStore(gobject.TYPE_STRING,
					   gobject.TYPE_UINT)
		policy.set_model(list_store)
		renderer = gtk.CellRendererText()
		policy.pack_start(renderer, True)
		policy.add_attribute(renderer, "text", COL_TEXT)
		for pol in range(4):
			row = list_store.append()
			list_store.set(row, COL_TEXT, schedutils.schedstr(pol),
					    COL_SCHED, pol)

	def on_cmdline_regex_changed(self, entry):
		process_regex_text = entry.get_text()
		try:
			cmdline_regex = re.compile(process_regex_text)
		except:
			self.process_list_store.clear()
			return
		self.refresh_match_pids(cmdline_regex)

	def on_just_this_thread_clicked(self, button):
		self.regex_edit.set_sensitive(False)
		self.process_list_store.clear()
		info = self.process_list_store.append()
		cmdline = procfs.process_cmdline(self.ps[self.pid])
		self.process_list_store.set(info,
					    self.PROCESS_COL_PID, self.pid,
					    self.PROCESS_COL_NAME, cmdline)

	def on_command_regex_clicked(self, button):
		self.regex_edit.set_sensitive(True)
		self.on_cmdline_regex_changed(self.regex_edit)

	def on_all_these_threads_clicked(self, button):
		self.regex_edit.set_sensitive(False)
		self.process_list_store.clear()
		info = self.process_list_store.append()
		cmdline = procfs.process_cmdline(self.ps[self.pid])
		self.process_list_store.set(info,
					    self.PROCESS_COL_PID, self.pid,
					    self.PROCESS_COL_NAME, cmdline)
		for tid in self.ps[self.pid]["threads"].keys():
			child = self.process_list_store.append()
			self.process_list_store.set(child,
						    self.PROCESS_COL_PID, tid,
						    self.PROCESS_COL_NAME, cmdline)


	def on_sched_policy_combo_changed(self, button):
		new_policy = self.sched_policy.get_active()
		if new_policy in ( SCHED_FIFO, SCHED_RR ):
			can_change_pri = True
		else:
			can_change_pri = False
		self.sched_pri.set_sensitive(can_change_pri)

	def on_affinity_text_changed(self, button):
		on_affinity_text_changed(self)

	def set_attributes_for_regex(self, regex, new_policy, new_prio, new_affinity):
		changed = False
		cmdline_regex = re.compile(regex)
		for match_pid in self.ps.find_by_cmdline_regex(cmdline_regex):
			if thread_set_attributes(match_pid, self.ps, new_policy,
						 new_prio, new_affinity,
						 self.nr_cpus):
				changed = True

		return changed

	def set_attributes_for_threads(self, pid, new_policy, new_prio, new_affinity):
		changed = False
		threads = self.ps[pid]["threads"]
		for tid in threads.keys():
			if thread_set_attributes(tid, threads, new_policy, new_prio,
						 new_affinity, self.nr_cpus):
				changed = True

		return changed

	def run(self):
		changed = False
		if self.dialog.run() == gtk.RESPONSE_OK:
			new_policy = int(self.sched_policy.get_active())
			new_prio = int(self.sched_pri.get_value())
			new_affinity = self.affinity.get_text()
			if self.just_this_thread.get_active():
				changed = thread_set_attributes(self.pid,
								self.ps,
								new_policy,
								new_prio,
								new_affinity,
								self.nr_cpus)
			elif self.all_these_threads.get_active():
				if thread_set_attributes(self.pid, self.ps,
							 new_policy, new_prio,
							 new_affinity,
							 self.nr_cpus):
					changed = True
				if self.set_attributes_for_threads(self.pid,
								   new_policy,
								   new_prio,
								   new_affinity):
					changed = True
			else:
				changed = self.set_attributes_for_regex(self.regex_edit.get_text(),
									new_policy,
									new_prio,
									new_affinity)

		self.dialog.destroy()
		return changed

class procview:

	nr_columns = 7
	( COL_PID, COL_POL, COL_PRI, COL_AFF, COL_VOLCTXT, COL_NONVOLCTXT, COL_CMDLINE ) = range(nr_columns)
	columns = (list_store_column("PID"),
		   list_store_column("Policy", gobject.TYPE_STRING),
		   list_store_column("Priority"),
		   list_store_column("Affinity", gobject.TYPE_STRING),
		   list_store_column("VolCtxtSwitch", gobject.TYPE_INT),
		   list_store_column("NonVolCtxtSwitch", gobject.TYPE_INT),
		   list_store_column("Command Line", gobject.TYPE_STRING))

	def __init__(self, treeview, ps,
		     show_kthreads = True, show_uthreads = True,
		     cpus_filtered = None):
		self.ps = ps
		self.treeview = treeview
		self.nr_cpus = procfs.cpuinfo().nr_cpus

		if not ps[1]["status"].has_key("voluntary_ctxt_switches"):
			self.nr_columns = 5
			( self.COL_PID, self.COL_POL, self.COL_PRI,
			  self.COL_AFF, self.COL_CMDLINE ) = range(self.nr_columns)
			self.columns = (list_store_column("PID"),
					list_store_column("Policy", gobject.TYPE_STRING),
					list_store_column("Priority"),
					list_store_column("Affinity", gobject.TYPE_STRING),
					list_store_column("Command Line", gobject.TYPE_STRING))

		self.tree_store = gtk.TreeStore(*generate_list_store_columns_with_attr(self.columns))
		self.treeview.set_model(self.tree_store)

		# Allow selecting multiple rows
		selection = treeview.get_selection()
		selection.set_mode(gtk.SELECTION_MULTIPLE)

		# Allow enable drag and drop of rows
		self.treeview.enable_model_drag_source(gtk.gdk.BUTTON1_MASK,
						       DND_TARGETS,
						       gtk.gdk.ACTION_DEFAULT | gtk.gdk.ACTION_MOVE)
		self.treeview.connect("drag_data_get", self.on_drag_data_get_data)
		try:
			self.treeview.connect("query-tooltip", self.on_query_tooltip)
		except:
			# old versions of pygtk2+ doesn't have this signal
			pass

		self.renderer = gtk.CellRendererText()
		for col in range(self.nr_columns):
			column = gtk.TreeViewColumn(self.columns[col].name,
						    self.renderer, text = col)
			column.add_attribute(self.renderer, "weight",
					     col + self.nr_columns)
			column.set_sort_column_id(col)
			try:
				self.treeview.set_tooltip_column(col)
			except:
				# old versions of pygtk2+ doesn't have this signal
				pass
			self.treeview.append_column(column)

		self.show_kthreads = show_kthreads
		self.show_uthreads = show_uthreads
		self.cpus_filtered = cpus_filtered
		self.refreshing = True

	def on_query_tooltip(self, treeview, x, y, keyboard_mode, tooltip):
		x, y = treeview.convert_widget_to_bin_window_coords(x, y)
		ret = treeview.get_path_at_pos(x, y)
		tooltip.set_text(None)
		if not ret:
			return True
		path, col, xpos, ypos = ret
		if not path:
			return True
		col_id = col.get_sort_column_id()
		if col_id != self.COL_CMDLINE:
			return True
		row = self.tree_store.get_iter(path)
		if not row:
			return True
		pid = int(self.tree_store.get_value(row, self.COL_PID))
		if not tuna.iskthread(pid):
			return True
		cmdline = self.tree_store.get_value(row, self.COL_CMDLINE).split(' ')[0]
		try:
			index = cmdline.index("/")
			key = cmdline[:index + 1]
			suffix_help = "\n<i>One per CPU</i>"
		except:
			key = cmdline
			suffix_help = ""
		help = tuna.kthread_help(key)
		tooltip.set_markup("<b>Kernel Thread %d (%s):</b>\n%s%s" % (pid, cmdline, help, suffix_help))
		return True

	def foreach_selected_cb(self, model, path, iter, pid_list):
		pid = model.get_value(iter, self.COL_PID)
		pid_list.append(str(pid))

	def on_drag_data_get_data(self, treeview, context,
			          selection, target_id, etime):
		treeselection = treeview.get_selection()
		pid_list = []
		treeselection.selected_foreach(self.foreach_selected_cb, pid_list)
		selection.set(selection.target, 8, "pid:" + ",".join(pid_list))

	def set_thread_columns(self, iter, tid, thread_info):
		new_value = [ None ] * self.nr_columns

		new_value[self.COL_PRI] = int(thread_info["stat"]["rt_priority"])

		try:
			new_value[self.COL_POL] = schedutils.schedstr(schedutils.get_scheduler(tid))[6:]
		except SystemError:
			return True

		new_value[self.COL_PID] = tid
		thread_affinity_list = schedutils.get_affinity(tid)
		new_value[self.COL_AFF] = tuna.list_to_cpustring(thread_affinity_list)
		try:
			new_value[self.COL_VOLCTXT] = int(thread_info["status"]["voluntary_ctxt_switches"])
			new_value[self.COL_NONVOLCTXT] = int(thread_info["status"]["nonvoluntary_ctxt_switches"])
		except:
			pass

		new_value[self.COL_CMDLINE] = procfs.process_cmdline(thread_info)

		set_store_columns(self.tree_store, iter, new_value)

		return False

	def show(self, force_refresh = False):
		# Start with the first row, if there is one, on the
		# process list. If the first time update_rows will just
		# have everthing in new_tids and append_new_tids will
		# create the rows.
		if not self.refreshing and not force_refresh:
			return
		row = self.tree_store.get_iter_first()
		self.update_rows(self.ps, row, None)
		self.treeview.show_all()

	def update_rows(self, threads, row, parent_row):
		new_tids = threads.keys()
		while row:
			tid = self.tree_store.get_value(row, self.COL_PID)
			if not threads.has_key(tid):
				if self.tree_store.remove(row):
					# removed and now row is the next one
					continue
				# removed and its the last one
				break
			else:
				try:
					new_tids.remove(tid)
				except:
					# FIXME: understand in what situation this
					# can happen, seems harmless from visual
					# inspection.
					pass
				if tuna.thread_filtered(tid, self.cpus_filtered,
						        self.show_kthreads,
							self.show_uthreads):
					if self.tree_store.remove(row):
						# removed and now row is the next one
						continue
					# removed and its the last one
					break
				else:
					self.set_thread_columns(row, tid, threads[tid])

					if threads[tid].has_key("threads"):
						children = threads[tid]["threads"]
					else:
						children = {}

					child_row = self.tree_store.iter_children(row)
					self.update_rows(children, child_row, row)

			row = self.tree_store.iter_next(row)

		new_tids.sort()
		self.append_new_tids(parent_row, threads, new_tids)

	def append_new_tids(self, parent_row, threads, tid_list):
		for tid in tid_list:
			if tuna.thread_filtered(tid, self.cpus_filtered,
						self.show_kthreads,
						self.show_uthreads):
				continue

			row = self.tree_store.append(parent_row)

			if self.set_thread_columns(row, tid, threads[tid]):
				# Thread doesn't exists anymore
				self.tree_store.remove(row)
				continue

			if threads[tid].has_key("threads"):
				children = threads[tid]["threads"]
				children_list = children.keys()
				children_list.sort()
				for child in children_list:
					child_row = self.tree_store.append(row)
					if self.set_thread_columns(child_row,
								   child,
								   children[child]):
						# Thread doesn't exists anymore
						self.tree_store.remove(child_row)

	def refresh(self):
		self.ps.reload()
		self.ps.reload_threads()
		self.ps.load_cmdline()

		self.show(True)

	def edit_attributes(self, a):
		ret = self.treeview.get_path_at_pos(self.last_x, self.last_y)
		if not ret:
			return
		path, col, xpos, ypos = ret
		if not path:
			return
		row = self.tree_store.get_iter(path)
		pid = self.tree_store.get_value(row, self.COL_PID)
		if not self.ps.has_key(pid):
			return

		dialog = process_druid(self.ps, pid, self.nr_cpus)
		if dialog.run():
			self.refresh()

	def kthreads_view_toggled(self, a):
		self.show_kthreads = not self.show_kthreads
		self.show(True)

	def uthreads_view_toggled(self, a):
		self.show_uthreads = not self.show_uthreads
		self.show(True)

	def help_dialog(self, a):
		ret = self.treeview.get_path_at_pos(self.last_x, self.last_y)
		if not ret:
			return
		path, col, xpos, ypos = ret
		if not path:
			return
		row = self.tree_store.get_iter(path)
		pid = self.tree_store.get_value(row, self.COL_PID)
		if not self.ps.has_key(pid):
			return

		cmdline = self.tree_store.get_value(row, self.COL_CMDLINE)
		help, title = tuna.kthread_help_plain_text(pid, cmdline)

		dialog = gtk.MessageDialog(None,
					   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
					   gtk.MESSAGE_INFO,
					   gtk.BUTTONS_OK, help)
		dialog.set_title(title)
		ret = dialog.run()
		dialog.destroy()

	def refresh_toggle(self, a):
		self.refreshing = not self.refreshing

	def save_kthreads_tunings(self, a):
		dialog = gtk.FileChooserDialog("Save As",
					       None,
					       gtk.FILE_CHOOSER_ACTION_SAVE,
					       (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
						gtk.STOCK_OK, gtk.RESPONSE_OK))
		dialog.set_default_response(gtk.RESPONSE_OK)

		try:
			dialog.set_do_overwrite_confirmation(True)
		except:
			pass

		filter = gtk.FileFilter()
		filter.set_name("rtctl config files")
		filter.add_pattern("*.rtctl")
		filter.add_pattern("*.tuna")
		filter.add_pattern("*rtgroup*")
		dialog.add_filter(filter)

		filter = gtk.FileFilter()
		filter.set_name("All files")
		filter.add_pattern("*")
		dialog.add_filter(filter)

		response = dialog.run()

		filename = dialog.get_filename()
		dialog.destroy()

		if response != gtk.RESPONSE_OK:
			return

		self.refresh()
		kthreads = tuna.get_kthread_sched_tunings(self.ps)
		tuna.generate_rtgroups(filename, kthreads, self.nr_cpus)

		if filename != "/etc/rtgroups":
			dialog = gtk.MessageDialog(None,
						   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
						   gtk.MESSAGE_INFO,
						   gtk.BUTTONS_YES_NO,
						   "Kernel thread tunings saved!\n\n"
						   "Now you can use it with rtctl:\n\n"
						   "rtctl --file %s reset\n\n"
						   "If you want the changes to be in "
						   "effect everytime you boot the system "
						   "please move %s to /etc/rtgroups\n\n"
						   "Do you want do do that now?" % (filename, filename))
			response = dialog.run()
			dialog.destroy()
			if response == gtk.RESPONSE_YES:
				filename = "/etc/rtgroups"
				tuna.generate_rtgroups(filename, kthreads, self.nr_cpus)

		dialog = gtk.MessageDialog(None,
					   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
					   gtk.MESSAGE_INFO,
					   gtk.BUTTONS_OK,
					   "Kernel thread tunings saved to %s!" % filename)
		dialog.run()
		dialog.destroy()

	def on_processlist_button_press_event(self, treeview, event):
		if event.type != gtk.gdk.BUTTON_PRESS or event.button != 3:
			return

		self.last_x = int(event.x)
		self.last_y = int(event.y)

		menu = gtk.Menu()

		setattr = gtk.MenuItem("_Set process attributes")
		if self.refreshing:
			refresh_prefix = "Sto_p refreshing the"
		else:
			refresh_prefix = "_Refresh the "
		refresh = gtk.MenuItem(refresh_prefix + " process list")
		if self.show_kthreads:
			kthreads_prefix = "_Hide"
		else:
			kthreads_prefix = "_Show"
		kthreads = gtk.MenuItem(kthreads_prefix + " kernel threads")
		if self.show_uthreads:
			uthreads_prefix = "_Hide"
		else:
			uthreads_prefix = "_Show"
		uthreads = gtk.MenuItem(uthreads_prefix + " user threads")

		help = gtk.MenuItem("_What is this?")

		save_kthreads_tunings = gtk.MenuItem("_Save kthreads tunings")

		menu.add(save_kthreads_tunings)
		menu.add(setattr)
		menu.add(refresh)
		menu.add(kthreads)
		menu.add(uthreads)
		menu.add(help)

		save_kthreads_tunings.connect_object('activate',
						     self.save_kthreads_tunings, event)
		setattr.connect_object('activate', self.edit_attributes, event)
		refresh.connect_object('activate', self.refresh_toggle, event)
		kthreads.connect_object('activate', self.kthreads_view_toggled, event)
		uthreads.connect_object('activate', self.uthreads_view_toggled, event)
		help.connect_object('activate', self.help_dialog, event)

		save_kthreads_tunings.show()
		setattr.show()
		refresh.show()
		kthreads.show()
		uthreads.show()
		help.show()

		menu.popup(None, None, None, event.button, event.time)

	def toggle_mask_cpu(self, cpu, enabled):
		if not enabled:
			if cpu not in self.cpus_filtered:
				self.cpus_filtered.append(cpu)
				self.show(True)
		else:
			if cpu in self.cpus_filtered:
				self.cpus_filtered.remove(cpu)
				self.show(True)

class gui:

	def __init__(self, show_kthreads = True, show_uthreads = True, cpus_filtered = []):
		global tuna_glade

		if self.check_root():
			sys.exit(1)
		for dir in tuna_glade_dirs:
			tuna_glade = "%s/tuna_gui.glade" % dir
			if os.access(tuna_glade, os.F_OK):
				break
		self.wtree = gtk.glade.XML(tuna_glade, "mainbig_window")
		self.ps = procfs.pidstats()
		self.irqs = procfs.interrupts()
		self.window = self.wtree.get_widget("mainbig_window")

		self.procview = procview(self.wtree.get_widget("processlist"),
					 self.ps, show_kthreads, show_uthreads, cpus_filtered)
		self.irqview = irqview(self.wtree.get_widget("irqlist"),
				       self.irqs, self.ps, cpus_filtered)
		self.cpuview = cpuview(self.wtree.get_widget("vpaned1"),
				       self.wtree.get_widget("hpaned2"),
				       self.wtree.get_widget("cpuview"),
				       self.procview, self.irqview, cpus_filtered)

		event_handlers = { "on_mainbig_window_delete_event"    : self.on_mainbig_window_delete_event,
				   "on_processlist_button_press_event" : self.procview.on_processlist_button_press_event,
				   "on_irqlist_button_press_event"     : self.irqview.on_irqlist_button_press_event }
		self.wtree.signal_autoconnect(event_handlers)

		self.ps.reload_threads()
		self.ps.load_cmdline()
		self.show()
		self.timer = gobject.timeout_add(2500, self.refresh)
		try:
			self.icon = gtk.status_icon_new_from_stock(gtk.STOCK_PREFERENCES)
			self.icon.connect("activate", self.on_status_icon_activate)
			self.icon.connect("popup-menu", self.on_status_icon_popup_menu)
		except AttributeError:
			# Old pygtk2
			pass
		pixbuf = self.window.render_icon(gtk.STOCK_PREFERENCES,
						 gtk.ICON_SIZE_SMALL_TOOLBAR)
		self.window.set_icon(pixbuf)

	def on_status_icon_activate(self, status_icon):
		if self.window.is_active():
			self.window.hide()
		else:
			self.window.present()

	def on_status_icon_popup_menu(self, icon, event_button, event_time):
		menu = gtk.Menu()

		quit = gtk.MenuItem("_Quit")
		menu.add(quit)
		quit.connect_object('activate', self.on_mainbig_window_delete_event, icon)
		quit.show()

		menu.popup(None, None, None, event_button, event_time)

	def on_mainbig_window_delete_event(self, obj, event = None):
		gtk.main_quit()

	def show(self):
		self.cpuview.refresh()
		self.irqview.show()
		self.procview.show()

	def refresh(self):
		self.ps.reload()
		self.ps.reload_threads()
		self.irqview.refresh()
		self.ps.load_cmdline()
		self.procview.show()
		return True

	def check_root(self):
		if os.getuid() == 0:
			return False

		dialog = gtk.MessageDialog(None,
					   gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
					   gtk.MESSAGE_WARNING,
					   gtk.BUTTONS_YES_NO,
					   "Root priviledge required\n\n" + \
					   "Some functions will not work without root " + \
					   "privilege.\nDo you want to continue?")
		ret = dialog.run()
		dialog.destroy()
		if ret == gtk.RESPONSE_NO:
			return True
		return False

	def run(self):
		gtk.main()