This file is indexed.

/usr/lib/python2.7/dist-packages/gnomebtdownload/client.py is in gnome-btdownload 0.0.32-4.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
"""
Copyright (c) 2003-2007, Paul Varga and other contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the project nor the names of its contributors may be
      used to endorse or promote products derived from this software without
      specific prior written permission.
"""

# gnome-btdownload stuff
import formattime, prefix, progressicon

# BitTorrent related modules.
import BitTorrent.download, BitTorrent.bencode

# Various system and utility modules.
import os, os.path, threading, sha, sys, time, re

# GTK+ and GNOME related modules.
import gobject, gtk, gtk.glade, gnome, gnome.ui, gconf
try:
	# The new module name
	import gnomevfs
except:
	import gnome.vfs
	gnomevfs = gnome.vfs

# pynotify
import pynotify

# Gettext
import gettext
_ = gettext.gettext

# The name of this program.
app_name    = 'gnome-btdownload'

# The version of this program.
app_version = '0.0.32'

# The 'GnomeProgram' for this process.
gnome_program = gnome.program_init(app_name, app_version)

# A hack that is set to a value that is the largest possible BitTorrent meta
# file. This is passed to get_url to pull the entire (hopefully) meta file into
# memory. I do this to prevent huge files from being loaded into memory.
max_torrent_size = 0x400000 # 4 MB

# From RFC 2396, the regular expression for well-formed URIs
rfc_2396_uri_regexp = r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?"

# If assigned, called with:
#	type: string
#		Describes the classification of the file to infer where it's
#		stored.
#		
#		Currently valid options:
#			* 'data'
#	filename: string
#		The name of the file for which to look.
#	sub: string or None
#		A potential sub-directory to check (and prefer) for the file.
locate_file = None

# Disabled until gnome_program.locate_file is exported by gnome-python...
#def locate_file(type filename, sub):
#	FIXME gnome_program.locate_file(gnome.FILE_DOMAIN_APP_DATADIR, filename, True)

# Fallback wrapper
if not locate_file:
	def fallback_locate_attempt(p, path, sub, filename):
		if sub:
			p_path_sub_file = p + '/' + path + '/' + sub + '/' + filename
			if os.path.exists(p_path_sub_file):
				return p_path_sub_file
		
		p_path_file = p + '/' + path + '/' + filename
		if os.path.exists(p_path_file):
			return p_path_file
		
		return None
	
	def fallback_locate_file(type, filename, sub=None):
		if type == 'data':
			result = fallback_locate_attempt(prefix.datadir, app_name, sub, filename)
			if result:
				return result
		
		print >> sys.stderr, _("Couldn't locate file, will probably explode...")
		return None
	
	if not locate_file:
		locate_file = fallback_locate_file

# Makes sure a URI is fully qualified and return the result. Return None if it
# isn't a URI.
def fix_up_uri(path):
	try:
		# 2 == GNOME_VFS_MAKE_URI_DIR_CURRENT, but isn't exported to python.
		# This does not appear to support relative URIs, but does
		# support relative paths, at least.
		return gnomevfs.URI(gnomevfs.make_uri_from_input_with_dirs(path, 2))
	except:
		return None

# Wrapper
def get_config_dir():
	home_dir = os.path.expanduser('~')
	
	if gnomevfs.exists(os.path.join(home_dir, '.gnome2')):
		return os.path.join(home_dir, '.gnome2', app_name)
	else:
		return os.path.join(home_dir, '.'+app_name)
def make_config_dir():
	home_dir   = os.path.expanduser('~')
	config_dir = None
	
	if gnomevfs.exists(os.path.join(home_dir, '.gnome2')):
		config_dir = os.path.join(home_dir, '.gnome2', app_name)
	else:
		config_dir = os.path.join(home_dir, '.'+app_name)
	
	if not gnomevfs.exists(config_dir):
		gnomevfs.make_directory(config_dir, 00750)
	
	cache_dir = os.path.join(config_dir, 'cache')
	
	if not gnomevfs.exists(cache_dir):
		gnomevfs.make_directory(cache_dir, 00777)

# Load at most read_bytes from a URI and return the result.
def get_url(uri, read_bytes):
	content = ''
	total_size = 0
	
	try:
		handle = gnomevfs.open(uri, gnomevfs.OPEN_READ)
	except Exception, e:
		print >> sys.stderr, 'gnomevfs.open failed with: url('+str(uri)+') e: '+str(e)
		return None
	try:
		tmp = handle.read(read_bytes)
		tmp_size = len(tmp)
		
		while(tmp_size < read_bytes - total_size):
			content += tmp
			total_size += tmp_size
			
			tmp = handle.read(read_bytes - total_size)
			tmp_size = len(tmp)
	except gnomevfs.EOFError:
		pass
	
	return content

# Wraps gobject.idle_add with a False return value so that the idle call will
# only be made once.
def idle_add_once(function, *args):
	def function_false(function, *args):
		function(*args)
		return False
	gobject.idle_add(function_false, function, *args)

# A GNOME HIG compliant error dialog wrapper.
class GtkHigErrorDialog(gtk.MessageDialog):
	def __init__(self, text, subtext=None, modal=False, parent=None):
		flags = gtk.DIALOG_DESTROY_WITH_PARENT
		
		if modal:
			flags |= gtk.DIALOG_MODEL
		
		gtk.MessageDialog.__init__(self, parent, flags, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE)
		
		self.set_markup(str(text))
		if subtext:
			self.format_secondary_markup(subtext)
	
	def run(self):
		gtk.MessageDialog.run(self)
		self.destroy()

# A GNOME HIG complient "continue session?" dialog wrapper.
class GtkHigContinueSessionDialog:
	glade_xml = None
	dialog    = None
	
	def run(self):
		ret = self.dialog.run()
		
		self.dialog.destroy()
		
		if ret == gtk.RESPONSE_ACCEPT:
			return True
		elif ret == gtk.RESPONSE_CANCEL:
			return False
		else:
			return None
	
	def __init__(self, previous, modal=False):
		self.glade_xml = gtk.glade.XML(locate_file('data', 'contdiag.glade', 'glade'))
		
		self.dialog = self.glade_xml.get_widget('dialog_hig_continue')
		
		self.glade_xml.get_widget('label_previous').set_markup(previous)
		
		self.dialog.set_modal(modal)

# A base wrapper for open and save dialogs.
class GtkFileActionDialog:
	dialog = None
	
	def run(self):
		ret = None
		
		if self.dialog.run() == gtk.RESPONSE_ACCEPT:
			ret = self.dialog.get_filename()
		
		self.dialog.destroy()
		
		return ret
	
	def __init__(self, title, action, buttons, filters=None, default_name=None, default_path=None, modal=False, multiple=False, localonly=False):
		self.dialog = gtk.FileChooserDialog(title, None, action, buttons)
		
		self.dialog.set_local_only(localonly)
		self.dialog.set_select_multiple(multiple)
		
		if default_path:
			self.dialog.set_current_folder(default_path)
		
		if default_name and (action == gtk.FILE_CHOOSER_ACTION_SAVE or action == gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER):
			self.dialog.set_current_name(default_name)
		
		if filters:
			default_filter = None
			
			for default, name, type, etc in filters:
				filter = gtk.FileFilter()
				
				filter.set_name(name)
				
				if type == 'mime':
					filter.add_mime_type(etc)
				elif type == 'pattern':
					filter.add_pattern(etc)
				elif type == 'custom':
					filter.add_custom(etc)
				
				self.dialog.add_filter(filter)
				
				if default:
					default_filter = filter
			
			all_filter = gtk.FileFilter()
			all_filter.set_name(_("All files"))
			all_filter.add_pattern('*')
			
			if not default_filter:
				default_filter = all_filter
			
			self.dialog.add_filter(all_filter)
			self.dialog.set_filter(default_filter)
		
		self.dialog.set_modal(modal)
		self.dialog.show()

# A wrapper for the open file dialog.
class GtkFileOpenDialog(GtkFileActionDialog):
	def __init__(self, title, folder=False, filters=None, default=None, modal=False, multiple=False, localonly=False):
		action = gtk.FILE_CHOOSER_ACTION_OPEN
		
		if folder:
			action = gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER
		
		GtkFileActionDialog.__init__(self, title, action, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT), filters, default, None, modal, multiple, localonly)

# A wrapper for the save file dialog.
class GtkFileSaveDialog(GtkFileActionDialog):
	def __init__(self, title, folder=False, filters=None, default_name=None, default_path=None, modal=False, multiple=False, localonly=False):
		action = gtk.FILE_CHOOSER_ACTION_SAVE
		
		if folder:
			action = gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER
		
		GtkFileActionDialog.__init__(self, title, action, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT), filters, default_name, default_path, modal, multiple, localonly)

# Manages a BitTorrent session's state into something consistent.
class BtState:
	# Handles the arguments passed to a BtState at initialization based
	# upon command line arguments.
	class Args:
		def __init__(self, args, bt_swa=(
			'--bind',
			'--check_hashes',
			'--display_interval',
			'--download_slice_size',
			'--http_timeout',
			'-i',
			'--ip',
			'--keepalive_interval',
			'--max_allow_in',
			'--max_initiate',
			'--max_message_length',
			'--max_rate_period',
			'--max_rate_recalculate_interval',
			'--max_slice_length',
			'--min_peers'
			'--rarest_first_priority_cutoff',
			'--report_hash_failures',
			'--request_backlog',
			'--rerequest_interval',
			'--snub_time',
			'--spew',
			'--timeout',
			'--timeout_check_interval',
			'--upload_rate_fudge',
		)):
			self.swa_args        = []
			self.path_origin     = None
			self.path_output     = None
			self.min_port        = None
			self.max_port        = None
			self.max_uploads     = None
			self.max_upload_rate = None
			self.torrent_file    = None
			self.torrent_info    = None
			
			# The number of arguments following the current one to ignore.
			ignore = 0
			
			for i in range(0,len(args)):
				# If we're ignoring this argument, skip it.
				if ignore > 0:
					ignore -= 1
					continue
				
				if args[i] == '--saveas':
					# Use the value to know where to save the session.
					
					# Ignore the next argument, since we're
					# going to use it now.
					ignore = 1
					
					if i+1 < len(args):
						self.set_path_output(args[i+1])
				elif args[i] == '--responsefile' or args[i] == '--url':
					# Use the value to know where the meta
					# file is located.
					
					# Ignore the next argument, since we're
					# going to use it now.
					ignore = 1
					
					# Convert "--responsefile [path]" into
					# "--url [uri]" and get a suggested
					# path_output if possible or needed.
					if i+1 < len(args):
						self.set_path_origin(fix_up_uri(args[i+1]))
				elif args[i] == '--max_uploads':
					# Use the value for the maximum number
					# of peers to upload to.
					
					# Ignore the next argument, since we're
					# going to use it now.
					ignore = 1
					
					if i+1 < len(args):
						self.max_uploads = int(args[i+1])
				elif args[i] == '--max_upload_rate':
					# Use the value for the maximum rate in
					# kbps to upload to peers
					
					# Ignore the next argument, since we're
					# going to use it now.
					ignore = 1
					
					if i+1 < len(args):
						self.max_upload_rate = float(args[i+1])
				elif args[i] == '--minport':
					# Use the value for the minimum port in
					# the port range to use.
					
					# Ignore the next argument, since we're
					# going to use it now.
					ignore = 1
					
					if i+1 < len(args):
						self.min_port = int(args[i+1])
				elif args[i] == '--maxport':
					# Use the value for the maximum port in
					# the port range to use.
					
					# Ignore the next argument, since we're
					# going to use it now.
					ignore = 1
					
					if i+1 < len(args):
						self.max_port = int(args[i+1])
				elif args[i] in bt_swa:
					# This is some BitTorrent command line
					# switch, pass it on.
					
					# Ignore the next argument, since we're
					# going to use it now.
					ignore = 1
					
					if i+1 < len(args):
						self.swa_args.append(args[i])
						self.swa_args.append(args[i+1])
				elif re.match(r"(--)(.+)", args[i]):
					# This is some random command line
					# switch, ignore it.
					
					# Ignore the next argument, as well.
					ignore = 1
				else:
					# Assume any stray argument is the
					# path_origin as if passed to
					# --reponsefile or --url if it's a
					# valid URI.
					
					if not self.path_origin and i < len(args):
						fixed = fix_up_uri(args[i])
						
						if fixed:
							self.set_path_origin(fixed)
		
		# Returns the meta file's contents
		def get_torrent_file(self):
			if self.path_origin:
				if not self.torrent_file:
					try:
						self.torrent_file = get_url(self.path_origin, max_torrent_size)
					except:
						pass
			
			return self.torrent_file
		
		# Returns the meta file's information.
		def get_torrent_info(self):
			torrent_file = self.get_torrent_file()
			
			if torrent_file:
				if not self.torrent_info:
					try:
						self.torrent_info = BitTorrent.bencode.bdecode(torrent_file)
					except:
						pass
			
			return self.torrent_info
		
		# Suggest an output path from the input path and/or the meta
		# file.
		def find_suggested_path_output(self):
			suggested_path_output = None
			torrent_info          = self.get_torrent_info()
			
			if torrent_info:
				suggested_path_output = torrent_info['info']['name']
			elif self.path_origin:
				suggested_path_output = self.path_origin.short_name
				
				if suggested_path_output[-len('.torrent'):] == '.torrent':
					suggested_path_output = suggested_path_output[:-len('.torrent')]
			
			return suggested_path_output
		
		# Tells if the torrent tracks multiple files by reading the
		# meta file.
		def test_has_multiple_files(self):
			has_multiple_files = False
			torrent_info       = self.get_torrent_info()
			
			if torrent_info:
				has_multiple_files = torrent_info['info'].has_key('files')
			
			return has_multiple_files
		
		# Set the path_origin and update anything that might depend
		# upon it. Expects a GnomeVFSURI.
		def set_path_origin(self, path_origin):
			# Invalidate information retreived from any old
			# path_origin, just in-case
			self.torrent_file = None
			self.torrent_info = None
			
			self.path_origin = path_origin
		
		# Set the path_output.
		def set_path_output(self, path_output):
			self.path_output = path_output
		
		# Set the min_port and max_port.
		def set_ports(self, min_port, max_port):
			self.min_port = min_port
			self.max_port = max_port
		
		# Retreive the entire argument string
		def get_args(self):
			args = []
			
			if self.path_origin:
				args.append('--url')
				args.append(str(self.path_origin))
			
			if self.path_output:
				args.append('--saveas')
				args.append(self.path_output)
			
			if self.min_port and self.max_port:
				args.append('--minport')
				args.append(str(self.min_port))
				args.append('--maxport')
				args.append(str(self.max_port))
			
			return args + self.swa_args
	
	def __init__(self, args):
		# BitTorrent module related information
		self.path_origin     = args.path_origin # The URI of the meta file
		self.size_total      = 0                # Total bytes of the download
		self.args            = args.get_args()  # The command line arguments to pass to the BitTorrent module's download
		# Local information
		self.path_output     = ''               # The path to which the session is being downloaded.
		# Transfer information
		self.done            = False            # True if the download portion of the session is complete
		self.event           = None             # Event used to flag the BitTorrent module to kill the session
		self.thread          = None             # Thread running the BitTorrent module's download
		self.activity        = None             # What the session is doing at the moment
		self.time_begin      = 0.0              # When the current session began
		self.time_remaining  = 0.0              # Estimated time remaining for the download to complete
		self.dl_rate         = 0.0              # The current rate of download in bytes/sec
		self.dl_amount       = 0                # Bytes downloaded from the current session
		self.dl_pre_amount   = 0                # Bytes downloaded from previous sessions
		self.ul_rate         = 0.0              # The current rate of upload in bytes/sec
		self.ul_amount       = None             # Bytes uploaded from the current session (None for unknown)
		self.ul_pre_amount   = 0                # Bytes uploaded from previous sessions
		self.max_uploads     = 0                # Maximum number of peers to upload to
		self.max_upload_rate = 0.0              # Maximum total bytes/sec to upload at once
		# Implementation information
		self.params          = {}               # Parameters passed from the BitTorrent module
		self.params_pounce   = True             # If current settings still need to be reflected in the session
	
	# Return the corrected-for-multiple-sessions downloaded amount in bytes.
	def get_dl_amount(self):
		if self.activity == 'checking existing file':
			return self.dl_amount
		else:
			return self.dl_amount + self.dl_pre_amount
	
	# Return the corrected-for-multiple-sessions uploaded amount in bytes.
	def get_ul_amount(self):
		if self.ul_amount:
			return self.ul_amount + self.ul_pre_amount
		elif self.ul_pre_amount > 0:
			return self.ul_pre_amount
		else:
			return None
	
	# Pseudo-callback to update state when 'file' BitTorrent callback is called.
	def file(self, default, size, saveas, dir):
		self.done       = False
		self.size_total = size
		
		if saveas:
			self.path_output = os.path.abspath(saveas)
		else:
			self.path_output = os.path.abspath(default)
		
		return self.path_output
	
	# Pseudo-callback to update state when 'status' BitTorrent callback is called.
	def status(self, dict):
		if not self.done:
			if dict.has_key('downRate'):
				self.dl_rate = float(dict['downRate'])
			
			dl_amount = None
			if dict.has_key('downTotal'):
				dl_amount = long(dict['downTotal'] * (1 << 20))
			elif dict.has_key('fractionDone'):
				dl_amount = long(float(dict['fractionDone']) * self.size_total)
			if dl_amount:
				if dl_amount == 0:
					self.dl_pre_amount = self.dl_amount
				self.dl_amount = dl_amount
			
			if dict.has_key('timeEst'):
				self.time_remaining = float(dict['timeEst'])
		
		if dict.has_key('upRate'):
			self.ul_rate = float(dict['upRate'])
		
		if dict.has_key('upTotal'):
			self.ul_amount = long(dict['upTotal'] * (1 << 20))

		if dict.has_key('activity'):		
			self.activity = dict['activity']

			# Incorporate the previous phase(s) in our download amount.
			self.dl_pre_amount += self.dl_amount
			self.dl_amount = 0
	
	# Pseudo-callback to update state when 'finished' BitTorrent callback is called.
	def finished(self):
		self.done = True
		self.dl_amount = self.size_total - self.dl_pre_amount
	
	# Pseudo-callback to update state when 'path' BitTorrent callback is called.
	def path(self, path):
		self.path_output = path
	
	# Pseudo-callback to update state when 'param' BitTorrent callback is called.
	def param(self, params):
		if params:
			self.params = params
			
			if self.params_pounce:
				self.cap_uploads(self.max_uploads)
				self.cap_upload_rate(self.max_upload_rate)
				
				self.params_pounce = False
		else:
			self.params = {}
	
	# Function to run in another thread.
	def download_thread(self, file, status, finished, error, cols, path, param):
		try:
			# BitTorrent 3.3-style
			BitTorrent.download.download(self.args, file, status, finished, error, self.event, cols, path, param)
		except Exception, e:
			# BitTorrent 3.2-style
			BitTorrent.download.download(self.args, file, status, finished, error, self.event, cols, path)
	
	# Start a session with the specified callbacks (which should each call
	# BtState updaters).
	def download(self, file, status, finished, error, cols, path, param, resuming=False):
		self.done          = False
		self.time_begin    = time.time()
		self.event         = threading.Event()
		self.thread        = threading.Thread(None, self.download_thread, 'bt_dl_thread', (file, status, finished, error, cols, path, param))
		self.dl_rate       = 0.0
		self.dl_amount     = 0
		self.dl_pre_amount = 0
		self.ul_rate       = 0.0
		self.params        = None
		self.params_pounce = True

		if resuming:
			if self.ul_amount:
				self.ul_pre_amount += self.ul_amount
		else:
			self.ul_pre_amount = 0
		self.ul_amount = None
		
		self.thread.start()
	
	# Try to end the BitTorrent session and wait for it to die before
	# returning.
	def join(self):
		if self.event:
			self.event.set()
			self.event = None
		if self.thread:
			self.thread.join()
			self.thread = None
	
	# Cap the number of peers to which you will upload.
	def cap_uploads(self, uploads):
		self.max_uploads = int(uploads)
		
		if self.params and self.params.has_key('max_uploads'):
			self.params['max_uploads'](self.max_uploads)
			return self.max_uploads
		else:
			return None
	
	# Cap the total bytes/sec of which you will upload.
	def cap_upload_rate(self, upload_rate):
		self.max_upload_rate = upload_rate
		
		if self.params and self.params.has_key('max_upload_rate'):
			self.params['max_upload_rate'](int(self.max_upload_rate * (1 << 10)))
			return int(self.max_upload_rate * (1 << 10))
		else:
			return None

# Persistance functions to resume a previously downloaded torrent
def check_for_previous_save_location(bt_state_args):
	config_dir = get_config_dir()
	cache_dir = os.path.join(config_dir, 'cache')
	
	if gnomevfs.exists(cache_dir):
		torrent_file = bt_state_args.get_torrent_file()
		
		if torrent_file:
			digest     = sha.new(torrent_file).hexdigest()
			digest_url = os.path.join(cache_dir, digest)
			
			if gnomevfs.exists(digest_url):
				previous_save_location = get_url(digest_url, max_torrent_size)
				
				if gnomevfs.exists(fix_up_uri(previous_save_location)):
					return previous_save_location
		else:
			print >> sys.stderr, 'check_for_previous_save_location failed to get torrent_file'
	else:
		make_config_dir()

def cache_save_location(bt_state_args):
	config_dir = get_config_dir()
	cache_dir = os.path.join(config_dir, 'cache')
	
	if not gnomevfs.exists(cache_dir):
		make_config_dir()
	
	# Just to make sure
	config_dir = get_config_dir()
	cache_dir = os.path.join(config_dir, 'cache')
	
	torrent_file = bt_state_args.get_torrent_file()
	
	if torrent_file:
		digest     = sha.new(torrent_file).hexdigest()
		digest_url = os.path.join(cache_dir, digest)
		
		digest_file = file(digest_url, 'w')
		digest_file.write(bt_state_args.path_output)
		digest_file.close()
	else:
		print >> sys.stderr, 'cache_save_location failed to get torrent_file'

class GtkClient:
	def __init__(self, args):
		# Miscellaneous events that have happened in this process's
		# BitTorrent sessions.
		self.bt_events = []
		
		# Time that the last error dialog was displayed
		self.last_error = 0
		
		# Localization Setup
		gtk.glade.bindtextdomain(app_name, prefix.localedir)
		gtk.glade.textdomain(app_name)
		
		gettext.bindtextdomain(app_name, prefix.localedir)
		gettext.bind_textdomain_codeset(app_name, 'UTF-8')
		gettext.textdomain(app_name)
		
		# Gtk+ Setup
		gtk.gdk.threads_init()
		
		# GConf Setup
		self.gconf_client = gconf.client_get_default()
		
		self.gconf_client.add_dir('/apps/'+app_name, gconf.CLIENT_PRELOAD_RECURSIVE)
		#self.gconf_client.notify_add('/apps/'+app_name+'/settings', self.on_gconf_settings_notify)
		
		# pynotify Setup
		self.notify_enabled = pynotify.init(app_name)
		
		# Bt Setup
		bt_state_args = BtState.Args(args[1:])
		
		if not bt_state_args.path_origin or not gnomevfs.exists(bt_state_args.path_origin):
			filters = ((True, _("BitTorrent meta files"), 'mime', 'application/x-bittorrent'), )
			result = GtkFileOpenDialog(_("Open location for BitTorrent meta file"), filters=filters, modal=True).run()
			
			if result:
				bt_state_args.set_path_origin(fix_up_uri(result))
			else:
				# They hit Cancel
				sys.exit(1)
		
		if not bt_state_args.path_output:
			previous_save_location = check_for_previous_save_location(bt_state_args)
			
			if previous_save_location:
				ret = GtkHigContinueSessionDialog(previous_save_location, modal=True).run()
				
				if ret == None:
					# They closed the window without an answer
					sys.exit(2)
				elif ret:
					bt_state_args.set_path_output(previous_save_location)
		
		if not bt_state_args.path_output:
			previous_path = None
			default = None
			
			# Look up the previous save path.
			try:
				previous_path = self.gconf_client.get_string('/apps/'+app_name+'/previous_path')
				
				if not os.path.isdir(previous_path):
					previous_path = None
			except:
				pass
			
			# Run Gtk+ file selector; localonly=True due to
			# BitTorrent.
			result = GtkFileSaveDialog(_("Save location for BitTorrent session"), default_name=bt_state_args.find_suggested_path_output(), default_path=previous_path, modal=True, localonly=True, folder=bt_state_args.test_has_multiple_files()).run()
			
			if result:
				bt_state_args.set_path_output(result)
				
				# Save the new path
				try:
					self.gconf_client.set_string('/apps/'+app_name+'/previous_path', os.path.dirname(result))
				except:
					pass
				
				cache_save_location(bt_state_args)
			else:
				# They hit Cancel
				sys.exit(3)
		
		if not bt_state_args.min_port or not bt_state_args.max_port:
			min_port = self.gconf_client.get_int('/apps/'+app_name+'/settings/min_port')
			max_port = self.gconf_client.get_int('/apps/'+app_name+'/settings/max_port')
			
			if min_port and max_port:
				bt_state_args.set_ports(min_port, max_port)
		
		self.bt_state = BtState(bt_state_args)
		
		# StatusIcon Setup
		self.status_icon          = gtk.StatusIcon()
		self.status_icon_fraction = None
		
		self.status_icon.connect('activate', self.on_status_icon_activate)
		self.status_icon.connect('popup-menu', self.on_status_icon_popup_menu)
		self.status_icon.connect('size-changed', self.on_status_icon_size_changed)
		
		# Run Gtk+ main window
		self.glade_xml = gtk.glade.XML(locate_file('data', 'dlsession.glade', 'glade'))
	
		self.setup_treeview_events()
		
		self.glade_xml.signal_autoconnect({
			'on_window_main_focus_in_event':
				self.on_window_main_focus_event,
			'on_window_main_focus_out_event':
				self.on_window_main_focus_event,
			'on_window_main_destroy':
				self.on_window_main_destroy,
			'on_button_open_clicked':
				lambda widget: self.open(),
			'on_button_resume_clicked':
				lambda widget: self.resume(),
			'on_button_stop_clicked':
				lambda widget: self.stop(),
			'on_button_close_clicked':
				lambda widget: self.close(),
			'on_checkbutton_cap_uploads_toggled':
				self.on_checkbutton_cap_uploads_toggled,
			'on_spinbutton_cap_uploads_value_changed':
				self.on_spinbutton_cap_uploads_value_changed,
			'on_checkbutton_cap_upload_rate_toggled':
				self.on_checkbutton_cap_upload_rate_toggled,
			'on_spinbutton_cap_upload_rate_value_changed':
				self.on_spinbutton_cap_upload_rate_value_changed,
			'on_button_events_clear_clicked':
				self.on_button_events_clear_clicked,
			'on_checkbutton_events_display_status_icon_toggled':
				self.on_checkbutton_events_display_status_icon_toggled,
			'on_checkbutton_events_display_error_dialogs_toggled':
				self.on_checkbutton_events_display_error_dialogs_toggled
		})
		
		self.glade_xml.get_widget('label_download_address_output').set_text(gnomevfs.format_uri_for_display(str(self.bt_state.path_origin)))
		self.glade_xml.get_widget('window_main').set_title(os.path.basename(self.bt_state.path_output))
		
		# Set GUI preferences
		display_status_icon = self.gconf_client.get_bool('/apps/'+app_name+'/settings/display_status_icon')
		if display_status_icon != None:
			self.glade_xml.get_widget('checkbutton_events_display_status_icon').set_active(display_status_icon)
		
		display_error_dialogs = self.gconf_client.get_bool('/apps/'+app_name+'/settings/display_error_dialogs')
		if display_error_dialogs != None:
			self.glade_xml.get_widget('checkbutton_events_display_error_dialogs').set_active(display_error_dialogs)
		
		if bt_state_args.max_uploads:
			self.glade_xml.get_widget('spinbutton_cap_uploads').set_value(bt_state_args.max_uploads)
			self.glade_xml.get_widget('checkbutton_cap_uploads').set_active(True)
		else:
			cap_upload_peers = self.gconf_client.get_int('/apps/'+app_name+'/settings/cap_upload_peers')
			if cap_upload_peers != None:
				self.glade_xml.get_widget('spinbutton_cap_uploads').set_value(cap_upload_peers)
			
			cap_upload = self.gconf_client.get_bool('/apps/'+app_name+'/settings/cap_upload')
			if cap_upload != None:
				self.glade_xml.get_widget('checkbutton_cap_uploads').set_active(cap_upload)
		
		cap_upload_rate_kbps = self.gconf_client.get_float('/apps/'+app_name+'/settings/cap_upload_rate_kbps')
		if cap_upload_rate_kbps != None:
			self.glade_xml.get_widget('spinbutton_cap_upload_rate').set_value(cap_upload_rate_kbps)
		
		if bt_state_args.max_upload_rate != None:
			if bt_state_args.max_upload_rate > 0:
				self.glade_xml.get_widget('spinbutton_cap_upload_rate').set_value(bt_state_args.max_upload_rate)
				self.glade_xml.get_widget('checkbutton_cap_upload_rate').set_active(True)
			else:
				self.glade_xml.get_widget('checkbutton_cap_upload_rate').set_active(False)
		else:
			cap_upload_rate = self.gconf_client.get_bool('/apps/'+app_name+'/settings/cap_upload_rate')
			if cap_upload_rate != None:
				self.glade_xml.get_widget('checkbutton_cap_upload_rate').set_active(cap_upload_rate)
		
		# Save arguments for session recovery
		self.session_recovery_cwd  = os.getcwd()
		self.session_recovery_args = args[:1] + bt_state_args.get_args()
		
		# Setup session
		master_client = gnome.ui.master_client()
		
		master_client.connect('save-yourself', self.on_gc_save_yourself, None)
		master_client.connect('die', self.on_gc_die, None)
		
		master_client.set_restart_style(gnome.ui.RESTART_IF_RUNNING)
		
		# Setup status icon
		self.update_status_icon()
		
		# Run Bt
		self.run_bt()
		
		# Run Gtk+
		gtk.main()
	
	# Actions
	def open(self):
		uri = fix_up_uri(self.bt_state.path_output)
		try:
			gnome.url_show(str(uri))
		except:
			# If we can't open the file, show it in the file
			# browser. In Python we cannot access libeel's
			# open-with dialog, so this is the next best thing.
			gnome.url_show(str(uri.parent))
	def resume(self):
		button_resume = self.glade_xml.get_widget('button_resume')
		button_stop   = self.glade_xml.get_widget('button_stop')
		button_close  = self.glade_xml.get_widget('button_close')
		
		button_resume.set_sensitive(False)
		button_stop.show()
		button_close.hide()
		
		self.run_bt(resuming=True)
	def stop(self):
		self.join()
		
		button_resume = self.glade_xml.get_widget('button_resume')
		button_stop   = self.glade_xml.get_widget('button_stop')
		button_close  = self.glade_xml.get_widget('button_close')
		
		button_resume.set_sensitive(True)
		button_stop.hide()
		button_close.show()
	def close(self):
		self.join()
		
		window_main = self.glade_xml.get_widget('window_main')
		window_main.destroy()
	def show_window_main(self, show):
		window_main = self.glade_xml.get_widget('window_main')
		
		if show:
			window_main.present()
		else:
			window_main.hide()
	
	# Appends an event to the log.
	def log_event(self, type, text):
		# Even though this is only run in the GUI thread, this seems to
		# be necessary to prevent the dialog from deadlocking on a
		# mutex.
		gtk.gdk.threads_enter()
		
		t = formattime.succinct(time.time() - self.bt_state.time_begin)
		
		notebook_main = self.glade_xml.get_widget('notebook_main')
		vbox_events   = self.glade_xml.get_widget('vbox_events')
		events_tab    = notebook_main.page_num(vbox_events)
		
		if type == 'Error':
			primary, secondary = str(text), None
			
			# Try to specially adapt the error message.
			try:
				mo = re.search(r"([A-Za-z ',]+) - [<]?([^>]+)[>]?", primary)
				primary, secondary = mo.group(1), mo.group(2)
			except:
				pass
			
			# Should we silently log errors or no?
			if self.glade_xml.get_widget('checkbutton_events_display_error_dialogs').get_active():
				done = False
				
				# Check if the status icon is showing and notify is
				# enabled. If so, try to use that for errors.
				if self.status_icon.get_visible() and self.notify_enabled:
					markup = primary
					if secondary is not None:
						markup = '<b>%s</b>\n\n%s' % (primary, secondary)
					
					n = pynotify.Notification(markup)
					n.attach_to_status_icon(self.status_icon)
					n.set_urgency(pynotify.URGENCY_NORMAL)
					
					if n.show():
						done = True
				if not done:
					# Check if the user is looking at the events tab. If so, do not
					# pop up an error dialog.
					if events_tab != None and notebook_main.get_current_page() != events_tab:
						# Select the events tab now (this will also prevent
						# more error dialogs from popping up).
						#
						# Say it with me: "worst solution EVER". :P
						notebook_main.set_current_page(events_tab)
						
						GtkHigErrorDialog(primary, secondary, parent=self.glade_xml.get_widget('window_main')).run()
		
		if self.bt_events:
			treeview_events = self.glade_xml.get_widget('treeview_events')
			
			# Scroll to the newly added event
			iter = self.bt_events.append((t, type, text))
			path = treeview_events.get_model().get_path(iter)
			treeview_events.scroll_to_cell(path)
		else:
			print >> sys.stderr, i18n('%s, %s: %s' % (t, type, str(text)))
		
		gtk.gdk.threads_leave()
	
	# BitTorrent callbacks
	def on_bt_file(self, default, size, saveas, dir):
		path = self.bt_state.file(default, size, saveas, dir)
		
		label_download_file_output = self.glade_xml.get_widget('label_download_file_output')
		idle_add_once(label_download_file_output.set_text, path)
		
		return path
	
	def on_bt_status(self, dict = {}, fractionDone = None, timeEst = None, downRate = None, upRate = None, activity = None):
		# To support BitTorrent 3.2, pack anything supplied seperately
		# from dict into dict.
		if fractionDone:
			dict['fractionDone'] = fractionDone
		if timeEst:
			dict['timeEst'] = timeEst
		if downRate:
			dict['downRate'] = downRate
		if upRate:
			dict['upRate'] = upRate
		if activity:
			dict['activity'] = activity
		
		self.bt_state.status(dict)
		
		label_download_elapsed_output = self.glade_xml.get_widget('label_download_time_elapsed_output')
		idle_add_once(label_download_elapsed_output.set_text, formattime.lengthy_precise(time.time() - self.bt_state.time_begin))
		
		if dict.has_key('fractionDone'):
			progressbar_download_status = self.glade_xml.get_widget('progressbar_download_status')
			window_main = self.glade_xml.get_widget('window_main')
			
			fraction = float(dict['fractionDone'])
			perc_string = str(int(fraction * 100.0)) + '%'
			title = _("%s of %s") % (perc_string, os.path.basename(self.bt_state.path_output))
			
			idle_add_once(progressbar_download_status.set_fraction, dict['fractionDone'])
			idle_add_once(progressbar_download_status.set_text, perc_string)
			idle_add_once(window_main.set_title, title)
			idle_add_once(self.update_status_icon, title, fraction)
		
		if dict.has_key('downTotal') or dict.has_key('fractionDone'):
			label_download_status_output = self.glade_xml.get_widget('label_download_status_output')
			
			idle_add_once(label_download_status_output.set_text, _("%.1f of %.1f MB at %.2f KB/s") %
				(float(self.bt_state.get_dl_amount()) / (1 << 20),
				 float(self.bt_state.size_total)      / (1 << 20),
				 float(self.bt_state.dl_rate)         / (1 << 10)))
			
		if dict.has_key('timeEst'):
			label_download_time_remaining_output = self.glade_xml.get_widget('label_download_time_remaining_output')
			
			idle_add_once(label_download_time_remaining_output.set_text, formattime.lengthy(dict['timeEst']))
		
		if dict.has_key('upRate') or dict.has_key('upTotal'):
			label_upload_status_output = self.glade_xml.get_widget('label_upload_status_output')
			
			if self.bt_state.get_ul_amount():
				idle_add_once(label_upload_status_output.set_text, _("%.1f MB at %.2f KB/s") %
					(float(self.bt_state.get_ul_amount()) / (1 << 20),
					 float(self.bt_state.ul_rate)         / (1 << 10)))
			else:
				idle_add_once(label_upload_status_output.set_text, _("%.2f KB/s") %
					(float(self.bt_state.ul_rate) / (1 << 10)))
		
		if dict.has_key('activity'):
			self.log_event('Activity', dict['activity'])
	
	def on_bt_finished(self):
		self.bt_state.finished()
		self.on_bt_status({'fractionDone': float(1.0), 'timeEst': 0, 'activity': 'finished'})
		
		label_download_status_output         = self.glade_xml.get_widget('label_download_status_output')
		progressbar_download_status          = self.glade_xml.get_widget('progressbar_download_status')
		label_download_time_remaining_output = self.glade_xml.get_widget('label_download_time_remaining_output')
		button_close                         = self.glade_xml.get_widget('button_close')
		button_open                          = self.glade_xml.get_widget('button_open')
		button_resume                        = self.glade_xml.get_widget('button_resume')
		button_stop                          = self.glade_xml.get_widget('button_stop')
		window_main                          = self.glade_xml.get_widget('window_main')
		
		idle_add_once(label_download_status_output.set_text, _("%.1f of %.1f MB at %.2f KB/s") %
				(float(self.bt_state.get_dl_amount()) / (1 << 20),
				 float(self.bt_state.size_total)      / (1 << 20),
				 0.0))
		idle_add_once(progressbar_download_status.set_fraction, 1.0)
		idle_add_once(progressbar_download_status.set_text, '100%')
		idle_add_once(label_download_time_remaining_output.set_text, _("None"))
		
		# Update buttons
		idle_add_once(button_resume.hide)
		idle_add_once(button_stop.hide)
		idle_add_once(button_close.show)
		idle_add_once(button_open.show)
		
		# Notify of completion
		idle_add_once(self.notify_of_completion)
	
	def on_bt_error(self, msg):
		idle_add_once(self.log_event, 'Error', msg)
	
	def on_bt_path(self, path):
		self.bt_state.path(path)
		
		label_download_file_output = self.glade_xml.get_widget('label_download_file_output')
		idle_add_once(label_download_file_output.set_text, self.bt_state.path_output)
	
	def on_bt_param(self, params):
		self.bt_state.param(params)
		
		checkbutton_cap_uploads = self.glade_xml.get_widget('checkbutton_cap_uploads')
		spinbutton_cap_uploads  = self.glade_xml.get_widget('spinbutton_cap_uploads')
		checkbutton_cap_upload_rate = self.glade_xml.get_widget('checkbutton_cap_upload_rate')
		spinbutton_cap_upload_rate  = self.glade_xml.get_widget('spinbutton_cap_upload_rate')
		
		if params.has_key('max_uploads'):
			idle_add_once(checkbutton_cap_uploads.set_sensitive, True)
			idle_add_once(spinbutton_cap_uploads.set_sensitive, True)
		else:
			idle_add_once(checkbutton_cap_uploads.set_sensitive, False)
			idle_add_once(spinbutton_cap_uploads.set_sensitive, False)
		
		if params.has_key('max_upload_rate'):
			idle_add_once(checkbutton_cap_upload_rate.set_sensitive, True)
			idle_add_once(spinbutton_cap_upload_rate.set_sensitive, True)
		else:
			idle_add_once(checkbutton_cap_upload_rate.set_sensitive, False)
			idle_add_once(spinbutton_cap_upload_rate.set_sensitive, False)
	
	# GnomeClient callbacks
	def on_gc_save_yourself(self, client, phase, save_style, is_shutdown, interact_style, is_fast, data=None):
		master_client = gnome.ui.master_client()
		
		args = self.session_recovery_args[:]
		
		checkbutton_cap_uploads = self.glade_xml.get_widget('checkbutton_cap_uploads')
		spinbutton_cap_uploads  = self.glade_xml.get_widget('spinbutton_cap_uploads')
		checkbutton_cap_upload_rate = self.glade_xml.get_widget('checkbutton_cap_upload_rate')
		spinbutton_cap_upload_rate  = self.glade_xml.get_widget('spinbutton_cap_upload_rate')
		
		if checkbutton_cap_uploads.get_active():
			args.append('--max_uploads')
			args.append(str(spinbutton_cap_uploads.get_value()))
		
		if checkbutton_cap_upload_rate.get_active():
			args.append('--max_upload_rate')
			args.append(str(spinbutton_cap_upload_rate.get_value()))
		
		master_client.set_current_directory(self.session_recovery_cwd)
		master_client.set_clone_command(len(args), args)
		master_client.set_restart_command(len(args), args)
		
		return True
	
	def on_gc_die(self, client, data=None):
		self.join()
		gtk.main_quit()
	
	# GTK+ callbacks
	def on_window_main_focus_event(self, widget, event):
		# Try to unset the urgency event
		try:
			widget.set_urgency_hint(False)
		except:
			pass
		return False
	def on_window_main_destroy(self, widget, data=None):
		self.join()
		gtk.main_quit()
	
	def on_checkbutton_cap_uploads_toggled(self, widget, data=None):
		spinbutton_cap_uploads = self.glade_xml.get_widget('spinbutton_cap_uploads')
		
		try:
			if widget.get_active():
				self.bt_state.cap_uploads(int(spinbutton_cap_uploads.get_value()))
				self.gconf_client.set_bool('/apps/'+app_name+'/settings/cap_upload', True)
			else:
				self.bt_state.cap_uploads(0)
				self.gconf_client.set_bool('/apps/'+app_name+'/settings/cap_upload', False)
		except:
			pass
	
	def on_spinbutton_cap_uploads_value_changed(self, widget, data=None):
		checkbutton_cap_uploads = self.glade_xml.get_widget('checkbutton_cap_uploads')
		
		try:
			self.gconf_client.set_int('/apps/'+app_name+'/settings/cap_upload_peers', int(widget.get_value()))
		except:
			pass
		
		if checkbutton_cap_uploads.get_active():
			self.bt_state.cap_uploads(int(widget.get_value()))
	
	def on_checkbutton_cap_upload_rate_toggled(self, widget, data=None):
		spinbutton_cap_upload_rate = self.glade_xml.get_widget('spinbutton_cap_upload_rate')
		
		try:
			if widget.get_active():
				self.bt_state.cap_upload_rate(spinbutton_cap_upload_rate.get_value())
				self.gconf_client.set_bool('/apps/'+app_name+'/settings/cap_upload_rate', True)
			else:
				self.bt_state.cap_upload_rate(0)
				self.gconf_client.set_bool('/apps/'+app_name+'/settings/cap_upload_rate', False)
		except:
			pass
	
	def on_spinbutton_cap_upload_rate_value_changed(self, widget, data=None):
		checkbutton_cap_upload_rate = self.glade_xml.get_widget('checkbutton_cap_upload_rate')
		
		try:
			self.gconf_client.set_float('/apps/'+app_name+'/settings/cap_upload_rate_kbps', float(widget.get_value()))
		except:
			pass
		
		if checkbutton_cap_upload_rate.get_active():
			self.bt_state.cap_upload_rate(widget.get_value())
	
	def on_button_events_clear_clicked(self, widget, data=None):
		if self.bt_events:
			self.bt_events.clear()
	
	def on_checkbutton_events_display_status_icon_toggled(self, widget, data=None):
		try:
			self.gconf_client.set_bool('/apps/'+app_name+'/settings/display_status_icon', widget.get_active())
		except:
			pass
		self.update_status_icon()
	def on_checkbutton_events_display_error_dialogs_toggled(self, widget, data=None):
		try:
			self.gconf_client.set_bool('/apps/'+app_name+'/settings/display_error_dialogs', widget.get_active())
		except:
			pass
	
	def on_status_icon_activate(self, status_icon, data=None):
		window_main = self.glade_xml.get_widget('window_main')
		
		self.show_window_main(not window_main.get_property('visible'))
	def on_status_icon_popup_menu(self, status_icon, button, activate_time, data=None):
		screen, area, orientation = status_icon.get_geometry()
		if status_icon.is_embedded() and area is not None:
			def new_entry(stock, markup):
				menuitem = gtk.ImageMenuItem(stock)
				menuitem.get_child().set_markup_with_mnemonic(markup)
				menuitem.show()
				return menuitem
			
			button_resume = self.glade_xml.get_widget('button_resume')
			button_stop   = self.glade_xml.get_widget('button_stop')
			button_close  = self.glade_xml.get_widget('button_close')
			window_main   = self.glade_xml.get_widget('window_main')
			checkbutton_events_display_error_dialogs = self.glade_xml.get_widget('checkbutton_events_display_error_dialogs')
			
			menu = gtk.Menu()
			
			if button_resume.get_property('visible') and button_resume.get_property('sensitive'):
				resume = new_entry(gtk.STOCK_REFRESH, _('_Resume'))
				resume.connect('activate', lambda widget: self.resume())
				menu.add(resume)
			
			if button_stop.get_property('visible'):
				stop = new_entry(gtk.STOCK_STOP, _('_Stop'))
				stop.connect('activate', lambda widget: self.stop())
				menu.add(stop)
			
			if button_close.get_property('visible'):
				close = new_entry(gtk.STOCK_CLOSE, _('_Close'))
				close.connect('activate', lambda widget: self.close())
				menu.add(close)
			
			menuitem = gtk.SeparatorMenuItem()
			menuitem.show()
			menu.add(menuitem)
			
			menuitem = gtk.CheckMenuItem(_('Display BitTorrent Session'))
			menuitem.set_active(window_main.get_property('visible'))
			menuitem.connect('toggled', lambda menuitem: self.show_window_main(menuitem.get_active()))
			menuitem.show()
			menu.add(menuitem)
			
			menuitem = gtk.CheckMenuItem(_('Display Error Dialogs'))
			menuitem.set_active(checkbutton_events_display_error_dialogs.get_active())
			menuitem.connect('toggled', lambda menuitem: checkbutton_events_display_error_dialogs.set_active(menuitem.get_active()))
			menuitem.show()
			menu.add(menuitem)
			
			menu.popup(None, None, gtk.status_icon_position_menu, button, activate_time, status_icon)
	def on_status_icon_size_changed(self, status_icon, size, data=None):
		self.update_status_icon()
	
	def notify_of_completion(self):
		done = False
		
		# If the status icon is displayed and notification works, notify the user of completion
		if self.status_icon.get_visible() and self.notify_enabled:
			n = pynotify.Notification('Download Complete')
			n.attach_to_status_icon(self.status_icon)
			n.set_urgency(pynotify.URGENCY_LOW)
			
			if n.show():
				done = True
		
		# Otherwise, try to set the urgency hint if the user isn't paying adequite attention
		if not done:
			try:
				if not window_main.has_toplevel_focus():
					idle_add_once(window_main.set_urgency_hint, True)
			except:
				pass
	
	def update_status_icon(self, title=None, fraction=None):
		checkbutton_events_display_status_icon = self.glade_xml.get_widget('checkbutton_events_display_status_icon')
		
		if checkbutton_events_display_status_icon.get_active():
			granularity = 0.2
			
			if self.status_icon_fraction is None or fraction is None or self.status_icon_fraction != int(fraction / granularity)*granularity:
				if fraction is None:
					if self.status_icon_fraction is None:
						self.status_icon_fraction = 0.0
				else:
					self.status_icon_fraction = int(fraction / granularity)*granularity
				
				progress_icon = progressicon.render_progress_icon(
					locate_file('data', 'download.svg', 'pixmaps'),
					self.status_icon.get_size(), self.status_icon.get_size(),
					self.status_icon_fraction)
				
				self.status_icon.set_from_pixbuf(progress_icon)
			
			if title is not None:
				self.status_icon.set_tooltip(title)
			
			self.status_icon.set_visible(True)
		else:
			self.status_icon.set_visible(False)
	
	# GTK+ setup stuff to supliment Glade.
	def setup_treeview_events(self):
		treeview_events = self.glade_xml.get_widget('treeview_events')
		
		list_store = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
		
		treeview_events.set_model(list_store)
		
		treeview_events.append_column(gtk.TreeViewColumn('Time', gtk.CellRendererText(), text=0))
		treeview_events.append_column(gtk.TreeViewColumn('Type', gtk.CellRendererText(), text=1))
		treeview_events.append_column(gtk.TreeViewColumn('Text', gtk.CellRendererText(), text=2))
		
		self.bt_events = list_store
	
	# Helpful wrapper to start BitTorrent session.
	def run_bt(self, resuming=False):
		self.bt_state.download(self.on_bt_file, self.on_bt_status, self.on_bt_finished, self.on_bt_error, 100, self.on_bt_path, self.on_bt_param, resuming=resuming)
	
	# Helpful wrapper to end BitTorrent session.
	def join(self):
		if self.bt_state:
			self.bt_state.join()

# Start the client
def run(args):
	gtk.window_set_default_icon_from_file(locate_file('data', 'download.svg', 'pixmaps'))
	client = GtkClient(args)