Esempio n. 1
0
        public void AddTorrent(string pathToTorrentFile)
        {
            Messenger.Default.Send(new AddTorrentShowDialog((dialogResult) =>
            {
                if (dialogResult == true)
                {
                    ViewModelLocator locator = new ViewModelLocator();
                    var addTorrentViewModel  = locator.AddTorrent;

                    TorrentManager manager = new TorrentManager(addTorrentViewModel.Torrent, addTorrentViewModel.PathToFolder, tSettings);
                    if (!engine.Contains(manager.InfoHash))
                    {
                        saveLoadManager.Add(manager);

                        engine.Register(manager);

                        manager.Start();

                        TorrentManagerWrapper wrapper = new TorrentManagerWrapper(manager);

                        Torrents.Add(wrapper);
                    }
                }
            }, pathToTorrentFile));
        }
Esempio n. 2
0
        private void RemoveTorrentCommandExecute()
        {
            Messenger.Default.Send(new DeleteTorrentShowDialog((dialogResult) =>
            {
                if (dialogResult == true)
                {
                    SelectedItem.Stop();
                    engine.Unregister(SelectedItem.Manager);
                    saveLoadManager.Remove(SelectedItem.Manager);

                    ViewModelLocator locator = new ViewModelLocator();
                    var deleteTorrentVM      = locator.DeleteTorrent;

                    if (deleteTorrentVM.Delete == DeleteTorrent.DeleteWithDownloadedFiles)
                    {
                        foreach (var item in SelectedItem.Files)
                        {
                            File.Delete(SelectedItem.SavePath + "\\" + item.Path);
                        }

                        try
                        {
                            Directory.Delete(SelectedItem.SavePath, false);
                        }
                        catch (IOException)
                        {
                        }
                    }


                    SelectedItem.Manager.Dispose();
                    Torrents.Remove(SelectedItem);
                }
            }));
        }
Esempio n. 3
0
 // Code to execute when the application is launching (eg, from Start)
 // This code will not execute when the application is reactivated
 private void Application_Launching(object sender, LaunchingEventArgs e)
 {
     if (LatestShows == null)
     {
         LatestShows = new Listings();
     }
     if (Torrents == null)
     {
         Torrents = new Torrents();
     }
     if (Shows == null)
     {
         Shows = new Shows();
     }
     if (db == null)
     {
         db = new DC();
     }
     if (!db.DatabaseExists())
     {
         db.CreateDatabase();
     }
     //pre load shows
     //if (!App.Shows.IsDataLoaded) {
     //    App.Shows.LoadData(false);
     //}
 }
        public async Task<byte[]> SaveStateAsync ()
        {
            await MainLoop;
            var state = new BEncodedDictionary {
                {nameof (Settings), Serializer.Serialize (Settings) },
            };

            state[nameof (Torrents)] = new BEncodedList (Torrents.Select (t => {
                var dict = new BEncodedDictionary {
                    { nameof (t.MagnetLink),  (BEncodedString) t.MagnetLink.ToV1String () },
                    { nameof(t.SavePath), (BEncodedString) t.SavePath },
                    { nameof(t.Settings), Serializer.Serialize (t.Settings) },
                    { "Streaming", (BEncodedString) (t.StreamProvider != null).ToString ()},
                };

                if (t.HasMetadata) {
                    dict[nameof (t.Files)] = new BEncodedList (t.Files.Select (file =>
                       new BEncodedDictionary {
                            { nameof(file.FullPath), (BEncodedString) file.FullPath },
                            { nameof(file.Path), (BEncodedString) file.Path },
                            { nameof(file.Priority), (BEncodedString) file.Priority.ToString () },
                       }
                    ));
                    dict[nameof (t.MetadataPath)] = (BEncodedString) t.MetadataPath;
                } else {
                }

                return dict;
            }));

            foreach (var v in Torrents)
                await v.MaybeWriteFastResumeAsync ();

            return state.Encode ();
        }
Esempio n. 5
0
        async void HandleLocalPeerFound(object sender, LocalPeerFoundEventArgs args)
        {
            try {
                await MainLoop;

                TorrentManager manager = Torrents.FirstOrDefault(t => t.InfoHash == args.InfoHash);
                // There's no TorrentManager in the engine
                if (manager == null)
                {
                    return;
                }

                // The torrent is marked as private, so we can't add random people
                if (manager.HasMetadata && manager.Torrent.IsPrivate)
                {
                    manager.RaisePeersFound(new LocalPeersAdded(manager, 0, 0));
                }
                else
                {
                    // Add new peer to matched Torrent
                    var peer       = new Peer("", args.Uri);
                    int peersAdded = manager.AddPeer(peer, fromTrackers: false, prioritise: true) ? 1 : 0;
                    manager.RaisePeersFound(new LocalPeersAdded(manager, peersAdded, 1));
                }
            } catch {
                // We don't care if the peer couldn't be added (for whatever reason)
            }
        }
Esempio n. 6
0
        public void RemoveTorrentAndFiles(PeriodicTorrent torrent)
        {
            torrent.Torrent.TorrentStateChanged += (s, e) =>
            {
                if (e.NewState == TorrentState.Stopped || e.NewState == TorrentState.Error)
                {
                    Client.Unregister(torrent.Torrent);
                    // Delete cache
                    if (File.Exists(torrent.CacheFilePath))
                    {
                        File.Delete(torrent.CacheFilePath);
                    }
                    if (File.Exists(Path.Combine(SettingsManager.TorrentCachePath,
                                                 Path.GetFileNameWithoutExtension(torrent.CacheFilePath) + ".info")))
                    {
                        File.Delete(Path.Combine(SettingsManager.TorrentCachePath,
                                                 Path.GetFileNameWithoutExtension(torrent.CacheFilePath) + ".info"));
                    }
                    // Delete files
                    try
                    {
                        Directory.Delete(torrent.Torrent.Path, true);
                    }
                    catch { }

                    torrent.Torrent.Dispose();
                    Application.Current.Dispatcher.BeginInvoke(new Action(() => Torrents.Remove(torrent)));
                }
            };
            Task.Factory.StartNew(() => torrent.Stop());
        }
Esempio n. 7
0
        public void OnTorrentRemoved(object sender, TorrentActionEventArgs args)
        {
            Torrent torrent = bitTorrentManager.GetTorrent(args.Handle);

            // Marshall the collection call back to the window thread, torrent will be captured
            Action dispatchAction = () => Torrents.Remove(torrent);

            this.currentDispatcher.BeginInvoke(dispatchAction);
        }
        private async Task InitializeTorrentsAsync()
        {
            var torrentsContainer = _rootElement.WaitForWebElementByContentName("torrents-container");
            var torrents          = torrentsContainer.FindElementsByContentName("torrent");

            Torrents = torrents
                       .Select(torrent => new TorrentComponent(torrent, _webDriver))
                       .ToList();

            await Torrents.InitializeAsync();
        }
Esempio n. 9
0
        public void UpdateAll()
        {
            TreeIter iter;

            if (Torrents.GetIterFirst(out iter))
            {
                do
                {
                    Update(iter);
                } while (Torrents.IterNext(ref iter));
            }
        }
Esempio n. 10
0
        private void BtnGoTorent_Clicked(object sender, RoutedEventArgs e)
        {
            Button cmd = (Button)sender;

            if (cmd.DataContext is Torrents)
            {
                Torrents URLTor = (Torrents)cmd.DataContext;

                string dirWithTorrent = @"C: \Users\User\Downloads";

                System.Diagnostics.Process.Start(URLTor.URLDownloads);

                //Process.Start(System.IO.Path.Combine(dirWithTorrent, deleteme.URLDownloads));
                //MessageBox.Show(deleteme.URLDownloads.ToString());
            }
        }
Esempio n. 11
0
        void Update(TreeIter row)
        {
            Download d = (Download)Torrents.GetValue(row, 0);

            Torrents.SetValues(row,
                               d,
                               d.Torrent.Name,
                               GetStatusString(d),
                               (int)(d.Progress * 100.0),
                               d.Seeds.ToString(),
                               d.Leechs + " (" + d.Available + ")",
                               ByteConverter.ConvertSpeed(d.DownloadSpeed),
                               ByteConverter.ConvertSize(d.UploadSpeed),
                               ((float)d.TotalUploaded / d.TotalDownloaded).ToString(),
                               ByteConverter.ConvertSize(d.Torrent.Size),
                               GetEtaString(d),
                               GetStatusColour(d),
                               d.Priority.ToString()
                               );
        }
Esempio n. 12
0
        void RemoveDownload(Download download)
        {
            TreeIter iter;

            if (Torrents.GetIterFirst(out iter))
            {
                do
                {
                    if (download != Torrents.GetValue(iter, 0))
                    {
                        continue;
                    }

                    download.PriorityChanged -= HandlePriorityChanged;
                    download.StateChanged    -= HandleStateChanged;
                    Torrents.Remove(ref iter);
                    Selection.UnselectAll();
                    break;
                } while (Torrents.IterNext(ref iter));
            }
        }
Esempio n. 13
0
        public PeriodicTorrent AddTorrent(TorrentWrapper torrent, bool startImmediately)
        {
            // Apply settings
            torrent.Settings.UseDht           = SettingsManager.EnableDHT;
            torrent.Settings.MaxConnections   = SettingsManager.MaxConnectionsPerTorrent;
            torrent.Settings.MaxDownloadSpeed = SettingsManager.MaxDownloadSpeed;
            torrent.Settings.MaxUploadSpeed   = SettingsManager.MaxUploadSpeed;
            torrent.Settings.UploadSlots      = SettingsManager.UploadSlotsPerTorrent;
            var periodicTorrent = new PeriodicTorrent(torrent);

            Task.Factory.StartNew(() =>
            {
                Client.Register(torrent);
                if (startImmediately)
                {
                    torrent.Start();
                }
            });
            Application.Current.Dispatcher.BeginInvoke(new Action(() => Torrents.Add(periodicTorrent)));
            return(periodicTorrent);
        }
Esempio n. 14
0
        async void DhtEnginePeersFound(object o, PeersFoundEventArgs e)
        {
            await MainLoop;

            TorrentManager manager = Torrents.FirstOrDefault(t => t.InfoHash == e.InfoHash);

            if (manager == null)
            {
                return;
            }

            if (manager.CanUseDht)
            {
                int successfullyAdded = await manager.AddPeersAsync(e.Peers);

                manager.RaisePeersFound(new DhtPeersAdded(manager, successfullyAdded, e.Peers.Count));
            }
            else
            {
                // This is only used for unit testing to validate that even if the DHT engine
                // finds peers for a private torrent, we will not add them to the manager.
                manager.RaisePeersFound(new DhtPeersAdded(manager, 0, 0));
            }
        }
Esempio n. 15
0
        private void btnTEST_Click(object sender, EventArgs e)
        {
            UTorrentWebRequest test = new UTorrentWebRequest();

            Torrents torrents = test.GetTorrents();
        }
Esempio n. 16
0
 public PeriodicTorrent GetTorrent(Torrent torrent)
 {
     return(Torrents.FirstOrDefault(t => t.Torrent.Torrent == torrent));
 }
        private void LoadTorrents()
        {
            var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);

            var filename = Path.Combine (documents, "delugemobile_torrents.xml");

            if (System.IO.File.Exists (filename)) {

                XmlSerializer deserializer = new XmlSerializer (typeof(Torrents));
                TextReader textReader = new StreamReader (filename);
                ts = (Torrents)deserializer.Deserialize (textReader);
                textReader.Close ();
            }

            List<CodeRinseRepeat.Deluge.Torrent> torrents = new List<Torrent>();

            if (ts != null) {

                foreach (TorrentsDetails td in ts.TorrentsList) {

                    CodeRinseRepeat.Deluge.Torrent t = new CodeRinseRepeat.Deluge.Torrent ();

                    t.TotalSize = td.dl;
                    t.TotalPayloadUpload = td.ul;
                    t.TrackerHost = td.host;
                    t.Name = td.name;
                    t.Ratio = td.ratio;
                    t.State = td.status;

                    torrents.Add (t);
                }

                var sortedTorrents = torrents.OrderBy (c => c.TrackerHost).ThenBy (c => c.TimeAdded);
                curTorrents = sortedTorrents;
            }
        }
Esempio n. 18
0
 public void RemoveTorrent(PeriodicTorrent torrent)
 {
     torrent.Torrent.TorrentStateChanged += (s, e) =>
     {
         if (e.NewState == TorrentState.Stopped || e.NewState == TorrentState.Error)
         {
             torrent.Stop();
             try
             {
                 Client.Unregister(torrent.Torrent);
             }
             catch { }     // TODO: See if we need to do more
             // Delete cache
             if (File.Exists(torrent.CacheFilePath))
             {
                 File.Delete(torrent.CacheFilePath);
             }
             if (File.Exists(Path.Combine(SettingsManager.TorrentCachePath,
                                          Path.GetFileNameWithoutExtension(torrent.CacheFilePath) + ".info")))
             {
                 File.Delete(Path.Combine(SettingsManager.TorrentCachePath,
                                          Path.GetFileNameWithoutExtension(torrent.CacheFilePath) + ".info"));
             }
             torrent.Torrent.Dispose();
             // We need to delay this until we're out of the handler for some reason
             Task.Factory.StartNew(() => Application.Current.Dispatcher.BeginInvoke(new Action(() => Torrents.Remove(torrent))));
         }
     };
     Task.Factory.StartNew(() => torrent.Stop());
 }
        private void SaveTorrents()
        {
            var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);

            ts = new Torrents ();
            ts.TorrentsList = new List<TorrentsDetails> ();

            var filename = Path.Combine (documents, "delugemobile_torrents.xml");

            foreach (CodeRinseRepeat.Deluge.Torrent t in curTorrents) {
                TorrentsDetails td = new TorrentsDetails ();

                td.dl = t.TotalSize;
                td.ul = t.TotalPayloadUpload;
                td.host = t.TrackerHost;
                td.name = t.Name;
                td.ratio = t.Ratio;
                td.status = t.State;

                ts.TorrentsList.Add (td);
            }

            XmlSerializer serializer = new XmlSerializer (typeof(Torrents));
            TextWriter textWriter = new StreamWriter (filename);
            serializer.Serialize (textWriter, ts);
            textWriter.Close ();
        }
Esempio n. 20
0
        async Task UpdateSettingsAsync(EngineSettings oldSettings, EngineSettings newSettings)
        {
            await DiskManager.UpdateSettingsAsync(newSettings);

            if (newSettings.DiskCacheBytes != oldSettings.DiskCacheBytes)
            {
                await Task.WhenAll(Torrents.Select(t => DiskManager.FlushAsync(t)));
            }

            ConnectionManager.Settings = newSettings;

            if (oldSettings.UsePartialFiles != newSettings.UsePartialFiles)
            {
                foreach (var manager in Torrents)
                {
                    await manager.UpdateUsePartialFiles(newSettings.UsePartialFiles);
                }
            }
            if (oldSettings.AllowPortForwarding != newSettings.AllowPortForwarding)
            {
                if (newSettings.AllowPortForwarding)
                {
                    await PortForwarder.StartAsync(CancellationToken.None);
                }
                else
                {
                    await PortForwarder.StopAsync(removeExistingMappings : true, CancellationToken.None);
                }
            }

            if (oldSettings.DhtEndPoint != newSettings.DhtEndPoint)
            {
                if (DhtListener.LocalEndPoint != null)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Udp, DhtListener.LocalEndPoint.Port), CancellationToken.None);
                }
                DhtListener.Stop();

                if (newSettings.DhtEndPoint == null)
                {
                    DhtListener = new NullDhtListener();
                    await RegisterDht(new NullDhtEngine());
                }
                else
                {
                    DhtListener = Factories.CreateDhtListener(Settings.DhtEndPoint) ?? new NullDhtListener();
                    if (IsRunning)
                    {
                        DhtListener.Start();
                    }

                    if (oldSettings.DhtEndPoint == null)
                    {
                        var dht = Factories.CreateDht();
                        await dht.SetListenerAsync(DhtListener);
                        await RegisterDht(dht);
                    }
                    else
                    {
                        await DhtEngine.SetListenerAsync(DhtListener);
                    }
                }

                if (DhtListener.LocalEndPoint != null)
                {
                    await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Udp, DhtListener.LocalEndPoint.Port));
                }
            }

            if (!Equals(oldSettings.ListenEndPoint, newSettings.ListenEndPoint))
            {
                if (PeerListener.LocalEndPoint != null)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Tcp, PeerListener.LocalEndPoint.Port), CancellationToken.None);
                }

                PeerListener.Stop();
                PeerListener = (newSettings.ListenEndPoint == null ? null : Factories.CreatePeerConnectionListener(newSettings.ListenEndPoint)) ?? new NullPeerListener();
                listenManager.SetListener(PeerListener);

                if (IsRunning)
                {
                    PeerListener.Start();
                    // The settings could say to listen at port 0, which means 'choose one dynamically'
                    if (PeerListener.LocalEndPoint != null)
                    {
                        await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Tcp, PeerListener.LocalEndPoint.Port));
                    }
                }
            }

            if (oldSettings.AllowLocalPeerDiscovery != newSettings.AllowLocalPeerDiscovery)
            {
                RegisterLocalPeerDiscovery(!newSettings.AllowLocalPeerDiscovery ? null : Factories.CreateLocalPeerDiscovery());
            }
        }
Esempio n. 21
0
 void AddDownload(Download download)
 {
     download.StateChanged    += HandleStateChanged;
     download.PriorityChanged += HandlePriorityChanged;
     Update(Torrents.AppendValues(download));
 }
Esempio n. 22
0
        void uTorrent_ListRefreshedEvent(ListRefreshedEventArgs ev)
        {
            if (ev.Torrents.Count != Torrents.Count)
            {
                System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action) delegate()
                {
                    Torrents.Clear();
                    ViewTorrents.Refresh();
                });
            }

            long dSpeed = 0, uSpeed = 0;

            // new or updated torrents
            foreach (Torrent tor in ev.Torrents)
            {
                dSpeed += tor.DownloadSpeed;
                uSpeed += tor.UploadSpeed;

                //logger.Trace(tor.ToString());

                bool foundTorrent = false;
                foreach (Torrent torExisting in Torrents)
                {
                    if (tor.Hash == torExisting.Hash)
                    {
                        foundTorrent = true;

                        // update details
                        torExisting.Availability      = tor.Availability;
                        torExisting.Downloaded        = tor.Downloaded;
                        torExisting.DownloadSpeed     = tor.DownloadSpeed;
                        torExisting.ETA               = tor.ETA;
                        torExisting.Label             = tor.Label;
                        torExisting.Name              = tor.Name;
                        torExisting.PeersConnected    = tor.PeersConnected;
                        torExisting.PeersInSwarm      = tor.PeersInSwarm;
                        torExisting.PercentProgress   = tor.PercentProgress;
                        torExisting.Ratio             = tor.Ratio;
                        torExisting.Remaining         = tor.Remaining;
                        torExisting.SeedsConnected    = tor.SeedsConnected;
                        torExisting.SeedsInSwarm      = tor.SeedsInSwarm;
                        torExisting.Size              = tor.Size;
                        torExisting.Status            = tor.Status;
                        torExisting.TorrentQueueOrder = tor.TorrentQueueOrder;
                        torExisting.Uploaded          = tor.Uploaded;
                        torExisting.UploadSpeed       = tor.UploadSpeed;

                        break;
                    }
                }

                if (!foundTorrent)
                {
                    System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action) delegate()
                    {
                        Torrents.Add(tor);
                    });
                }
            }

            DownloadSpeedSummaryFormatted = Utils.FormatByteSize((long)dSpeed) + "/sec";
            UploadSpeedSummaryFormatted   = Utils.FormatByteSize((long)uSpeed) + "/sec";

            System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action) delegate()
            {
                ViewTorrents.Refresh();
            });
        }
Esempio n. 23
0
        async Task UpdateSettingsAsync(EngineSettings oldSettings, EngineSettings newSettings)
        {
            await DiskManager.UpdateSettingsAsync(newSettings);

            if (newSettings.DiskCacheBytes != oldSettings.DiskCacheBytes)
            {
                await Task.WhenAll(Torrents.Select(t => DiskManager.FlushAsync(t)));
            }

            ConnectionManager.Settings = newSettings;

            if (oldSettings.AllowPortForwarding != newSettings.AllowPortForwarding)
            {
                if (newSettings.AllowPortForwarding)
                {
                    await PortForwarder.StartAsync(CancellationToken.None);
                }
                else
                {
                    await PortForwarder.StopAsync(removeExistingMappings : true, CancellationToken.None);
                }
            }

            if (oldSettings.DhtPort != newSettings.DhtPort)
            {
                if (DhtListener.EndPoint != null)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Udp, DhtListener.EndPoint.Port), CancellationToken.None);
                }
                else if (oldSettings.DhtPort > 0)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Udp, oldSettings.DhtPort), CancellationToken.None);
                }

                DhtListener = DhtListenerFactory.CreateUdp(newSettings.DhtPort);

                if (oldSettings.DhtPort == -1)
                {
                    await RegisterDht(DhtEngineFactory.Create(DhtListener));
                }
                else if (newSettings.DhtPort == -1)
                {
                    await RegisterDht(new NullDhtEngine());
                }

                DhtEngine.SetListener(DhtListener);

                if (IsRunning)
                {
                    DhtListener.Start();
                    if (Listener is ISocketListener newDhtListener)
                    {
                        await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Udp, newDhtListener.EndPoint.Port));
                    }
                    else
                    {
                        await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Udp, newSettings.DhtPort));
                    }
                }
            }

            if (oldSettings.ListenPort != newSettings.ListenPort)
            {
                if (Listener is ISocketListener oldListener)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Tcp, oldListener.EndPoint.Port), CancellationToken.None);
                }
                else if (oldSettings.ListenPort > 0)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Tcp, oldSettings.ListenPort), CancellationToken.None);
                }

                Listener.Stop();
                Listener = PeerListenerFactory.CreateTcp(newSettings.ListenPort);
                listenManager.SetListener(Listener);

                if (IsRunning)
                {
                    Listener.Start();
                    // The settings could say to listen at port 0, which means 'choose one dynamically'
                    if (Listener is ISocketListener peerListener)
                    {
                        await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Tcp, peerListener.EndPoint.Port));
                    }
                    else
                    {
                        await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Tcp, newSettings.ListenPort));
                    }
                }
            }

            // This depends on the Listener binding to it's local port.
            var localPort = newSettings.ListenPort;

            if (Listener is ISocketListener newListener)
            {
                localPort = newListener.EndPoint.Port;
            }

            if ((oldSettings.AllowLocalPeerDiscovery != newSettings.AllowLocalPeerDiscovery) ||
                (oldSettings.ListenPort != newSettings.ListenPort))
            {
                RegisterLocalPeerDiscovery(newSettings.AllowLocalPeerDiscovery && localPort > 0 ? new LocalPeerDiscovery(localPort) : null);
            }
        }
Esempio n. 24
0
        private void buildColumns()
        {
            Column downloadColumn = new Column {
                Ignore = true, Visible = false, Title = "N/A"
            };

            Gtk.CellRendererText     torrentNameCell      = new Gtk.CellRendererText();
            Gtk.CellRendererText     torrentStatusCell    = new Gtk.CellRendererText();
            Gtk.CellRendererProgress torrentDoneCell      = new Gtk.CellRendererProgress();
            Gtk.CellRendererText     torrentSeedsCell     = new Gtk.CellRendererText();
            Gtk.CellRendererText     torrentPeersCell     = new Gtk.CellRendererText();
            Gtk.CellRendererText     torrentPriorityCell  = new Gtk.CellRendererText();
            Gtk.CellRendererText     torrentDownSpeedCell = new Gtk.CellRendererText();
            Gtk.CellRendererText     torrentUpSpeedCell   = new Gtk.CellRendererText();
            Gtk.CellRendererText     torrentRatioCell     = new Gtk.CellRendererText();
            Gtk.CellRendererText     torrentSizeCell      = new Gtk.CellRendererText();
            Gtk.CellRendererText     torrentEtaCell       = new Gtk.CellRendererText();

            nameColumn.PackStart(torrentNameCell, true);
            statusColumn.PackStart(torrentStatusCell, true);
            doneColumn.PackStart(torrentDoneCell, true);
            seedsColumn.PackStart(torrentSeedsCell, true);
            peersColumn.PackStart(torrentPeersCell, true);
            priorityColumn.PackStart(torrentPriorityCell, true);
            downSpeedColumn.PackStart(torrentDownSpeedCell, true);
            upSpeedColumn.PackStart(torrentUpSpeedCell, true);
            ratioColumn.PackStart(torrentRatioCell, true);
            sizeColumn.PackStart(torrentSizeCell, true);
            etaColumn.PackStart(torrentEtaCell, true);

            nameColumn.AddAttribute(torrentNameCell, "text", 1);
            statusColumn.AddAttribute(torrentStatusCell, "text", 2);
            statusColumn.AddAttribute(torrentStatusCell, "foreground", 11);
            doneColumn.AddAttribute(torrentDoneCell, "value", 3);
            seedsColumn.AddAttribute(torrentSeedsCell, "text", 4);
            peersColumn.AddAttribute(torrentPeersCell, "text", 5);
            priorityColumn.AddAttribute(torrentPriorityCell, "text", 12);
            downSpeedColumn.AddAttribute(torrentDownSpeedCell, "text", 6);
            upSpeedColumn.AddAttribute(torrentUpSpeedCell, "text", 7);
            ratioColumn.AddAttribute(torrentRatioCell, "text", 8);
            sizeColumn.AddAttribute(torrentSizeCell, "text", 9);
            etaColumn.AddAttribute(torrentEtaCell, "text", 10);

            AppendColumn(priorityColumn);
            AppendColumn(downloadColumn);
            AppendColumn(nameColumn);
            AppendColumn(statusColumn);
            AppendColumn(doneColumn);
            AppendColumn(seedsColumn);
            AppendColumn(peersColumn);
            AppendColumn(downSpeedColumn);
            AppendColumn(upSpeedColumn);
            AppendColumn(etaColumn);
            AppendColumn(ratioColumn);
            AppendColumn(sizeColumn);

            foreach (TreeViewColumn c in this.Columns)
            {
                c.Sizing      = TreeViewColumnSizing.Fixed;
                c.Reorderable = true;
                c.Resizable   = true;

                c.Clicked += delegate(object o, EventArgs e) {
                    int            oldId;
                    SortType       oldSort;
                    TreeViewColumn sender = (TreeViewColumn)o;

                    Torrents.GetSortColumnId(out oldId, out oldSort);

                    // Invert the sort order if we're the same
                    if (oldId == sender.SortColumnId)
                    {
                        sender.SortOrder = sender.SortOrder == SortType.Ascending ? SortType.Descending : SortType.Ascending;
                    }
                    else
                    {
                        sender.SortOrder = SortType.Ascending;
                    }
                    Torrents.SetSortColumnId(sender.SortColumnId, sender.SortOrder);
                };
            }
        }