Logo Search packages:      
Sourcecode: qtorrent version File versions  Download package

mainwin.py

__all__ = ['USE_KDE', 'MainWin']

import os, sys
from qt import *
try:
      from kdecore import *
      from kdeui import *
      USE_KDE = True
      BaseClass = KMainWindow
except ImportError:
      USE_KDE = False
      BaseClass = QMainWindow

from torrentwin import TorrentWin
import BitTorrent

class MainWin(BaseClass):
      def __init__(self, qtorrent):
            self.qtorrent = qtorrent
            self.getFilenameObj = None
            self.statsData = {}
            
            self.lastOpen = {
                  'dir': os.path.expanduser('~'),
                  'showHidden': False
            }
            self.lastSave = {
                  'dir': os.path.expanduser('~'),
                  'showHidden': False
            }
            
            BaseClass.__init__(self, None, 'QTorrent')
            if USE_KDE:
                  self.setPlainCaption("QTorrent3")
            else:
                  self.setCaption('QTorrent3')
            self.statusBar().hide()
            
            menu = self.torrentMenu = QPopupMenu(self)
            menu.insertItem('&Open...', self.openFileNoAutoSave)
            menu.insertItem('Open and &auto-save...', self.openFileAutoSave)
            menu.insertSeparator()
            menu.insertItem('&Quit', self.close)
            
            self.helpmenu = menu = QPopupMenu(self)
            menu.insertItem('&About', self.about)
            
            menubar = self.menuBar()
            menubar.insertItem('&Torrent', self.torrentMenu)
            menubar.insertItem('&Help', self.helpmenu)
            
            self.stack = QWidgetStack(self)
            
            self.listview = lv = QListView(self.stack)
            self.listview.setAllColumnsShowFocus(True)
            for col in ('Torrent', 'Status', 'Progress (%)', 'Remaining', 'DL (KB/s)', 'UL (KB/s)', 'Size (MB)', 'Last error'):
                  lv.addColumn(col)
            self.listitems = {}
            self.connect(lv, SIGNAL('contextMenuRequested(QListViewItem*, const QPoint&, int)'), self.popupListMenu)
            self.connect(lv, SIGNAL('doubleClicked(QListViewItem*, const QPoint&, int)'), self.showTorrentWin)
            
            self.torrentwin = TorrentWin(self.stack)
            self.torrentwin.show()
            self.connect(self.torrentwin, PYSIGNAL('showList'), self.showList)
            self.connect(self.torrentwin, PYSIGNAL('stopTorrent'), self.stopStartTorrent)
            self.connect(self.torrentwin, PYSIGNAL('removeTorrent'), self.removeTorrent)
            self.connect(self.torrentwin, PYSIGNAL('prevTorrent'), self.prevTorrent)
            self.connect(self.torrentwin, PYSIGNAL('nextTorrent'), self.nextTorrent)
            
            self.setCentralWidget(self.stack)
            
            self.statsTimer = QTimer(self)
            self.connect(self.statsTimer, SIGNAL('timeout()'), self._stats)
            self.statsTimer.start(1000)
            
            self.setAcceptDrops(True)
            
            self.layout().activate()
            self.resize(500, self.minimumSize().height())
            
            QTimer.singleShot(0, self.qtorrent.gui_inited)
            QTimer.singleShot(0, self.showList)
            
            self.stack.raiseWidget(self.torrentwin)
      
      def popupListMenu(self, item, pos, c):
            if not item:
                  return
            for hash, obj in self.listitems.items():
                  if obj == item:
                        break
            else:
                  print 'not found'
                  return
            menu = QPopupMenu()
            
            def removeTorrent():
                  self.qtorrent.remove(hash)
            menu.insertItem('Remove', removeTorrent)
            if obj.text(1) != 'stopped':
                  def stopTorrent():
                        self.qtorrent.stop(hash)
                  menu.insertItem('Stop', stopTorrent)
            else:
                  def resumeTorrent():
                        self.qtorrent.resume(hash)
                  menu.insertItem('Resume', resumeTorrent)
            menu.exec_loop(pos)
            
      def openFileAutoSave(self):
            self.openFile(True)
      
      def openFileNoAutoSave(self):
            self.openFile(False)
      
      def openFile(self, autosave = False):
            dlg = QFileDialog(self.lastOpen['dir'], None, self, None, True)
            dlg.setShowHiddenFiles(self.lastOpen['showHidden'])
            dlg.addFilter('Torrent files (*.torrent)')
            dlg.setCaption('Open torrent file(s)')
            dlg.setMode(QFileDialog.ExistingFiles)
            if(dlg.exec_loop() == QDialog.Accepted):
                  self.lastOpen = {
                        'dir': dlg.dir().path().latin1(),
                        'showHidden': dlg.showHiddenFiles()
                  }
                  for path in dlg.selectedFiles():
                        self.qtorrent.add(path.latin1(), autosave)
      
      def getFilename(self, obj):
            self.getFilenameObj = obj
            QTimer.singleShot(0, self._getFilename)
      
      def _getFilename(self):
            obj = self.getFilenameObj
            is_dir = not obj['metainfo']['info'].has_key('length')
            
            dlg = QFileDialog(self.lastSave['dir'], None, self, None, True)
            dlg.setShowHiddenFiles(self.lastSave['showHidden'])
            if is_dir:
                  dlg.setCaption('Save to')
                  dlg.setMode(QFileDialog.DirectoryOnly)
            else:
                  dlg.setCaption('Save as')
                  dlg.setMode(QFileDialog.AnyFile)
                  dlg.setSelection(os.path.join(self.lastSave['dir'], obj['name']))
            if dlg.exec_loop() == QDialog.Accepted:
                  self.lastSave['dir'] = dlg.dir().path().latin1()
                  self.lastSave['showHidden'] = dlg.showHiddenFiles()
                  if is_dir:
                        self.qtorrent.setFilename(obj, os.path.join(dlg.dir().path().latin1(), obj['name']))
                  else:
                        self.qtorrent.setFilename(obj, dlg.selectedFile().latin1())
            else:
                  self.qtorrent.setFilename(obj, None)
      
      def stats(self, data, regular):
            self.statsData = data
            if not regular:
                  QTimer.singleShot(0, self._stats)
      
      def _stats(self):
            for key, stats in self.statsData.items():
                  if self.listitems.has_key(key):
                        item = self.listitems[key]
                  else:
                        item = QListViewItem(self.listview)
                        self.listitems[key] = item
                  
                  if key == self.torrentwin.current:
                        self.torrentwin.stats(stats)
                  
                  item.setText(0, stats[0])
                  item.setText(1, stats[2])
                  item.setText(2, '%.1f%%' % (stats[3] * 100.0))
                  def fmttime(s):
                        days = int(s / 86400)
                        s = s % 86400
                        hours = int(s / 3600)
                        s = s % 3600
                        minutes = int(s / 60)
                        s = s % 60
                        return '%id%ih%im%is' % (days, hours, minutes, s)
                  if stats[4] < 0:
                        item.setText(3, 'unknown')
                  elif stats[4] == 0:
                        item.setText(3, '')
                  else:
                        item.setText(3, fmttime(stats[4]))
                  item.setText(4, '%.1f' % (stats[5] / 1024.0))
                  item.setText(5, '%.1f' % (stats[6] / 1024.0))
                  item.setText(6, '%.1f' % (stats[1] / 1048576.0))
                  if stats[-1]:
                        item.setText(7, stats[-1][-1][1])
            
            to_del = []
            for hash in self.listitems.keys():
                  if not hash in self.statsData:
                        to_del.append(hash)
            for hash in to_del:
                  item = self.listitems[hash]
                  del self.listitems[hash]
                  self.listview.takeItem(item)
      
      def dragEnterEvent(self, ev):
            ev.accept(ev.provides('text/x-moz-url') or ev.provides('_NETSCAPE_URL') or ev.provides('text/uri_list'))
      
      def dropEvent(self, ev):
            url = None
            if ev.provides('text/x-moz-url'):
                  url = str(ev.encodedData('text/x-moz-url')).split('\n')[0]
            elif ev.provides('_NETSCAPE_URL'):
                  url = str(ev.encodedData('_NETSCAPE_URL')).split('\n')[0]
            elif ev.provides('text/uri-list'):
                  print 'text/uri-list', str(ev.encodedData('text/uri-list'))
            
            if not url:
                  ev.accept(False)
                  return
            
            self.qtorrent.add(url.decode('utf-16').encode('utf-8'))
            
            ev.accept()
      
      def showTorrentWin(self, item, pos, col):
            if not item or col == -1:
                  return
            
            for hash, obj in self.listitems.items():
                  if obj == item:
                        break
            else:
                  print 'not found'
                  return
            self._showTorrentWin(hash)
      
      def _showTorrentWin(self, hash):
            self.torrentwin.current = hash
            self.torrentwin.stats(self.statsData[hash])
            self.stack.raiseWidget(self.torrentwin)
      
      def showList(self):
            self.stack.raiseWidget(self.listview)
      
      def stopStartTorrent(self, hash):
            if not self.statsData.has_key(hash):
                  print 'not found'
                  return
            if self.statsData[hash][2] == 'stopped':
                  self.qtorrent.resume(hash)
            else:
                  self.qtorrent.stop(hash)
      
      def removeTorrent(self, hash):
            if not self.statsData.has_key(hash):
                  print 'not found'
                  return
            self.showList()
            self.qtorrent.remove(hash)

      def prevTorrent(self, hash):
            keys = self.listitems.keys()
            keys.sort()
            try:
                  ix = keys.index(hash)
            except ValueError:
                  return
            if ix == 0:
                  ix = len(keys) - 1
            else:
                  ix -= 1
            self._showTorrentWin(keys[ix])
      
      def nextTorrent(self, hash):
            keys = self.listitems.keys()
            keys.sort()
            try:
                  ix = keys.index(hash)
            except ValueError:
                  return
            ix += 1
            if ix == len(keys):
                  ix = 0
            self._showTorrentWin(keys[ix])
      
      def about(self):
            QMessageBox.about(self, "QTorrent3",
                  '''QTorrent3 %s by Hyriand (Copyright 2005)

(uses BitTorrent %s)''' % (self.qtorrent.version, BitTorrent.version))

Generated by  Doxygen 1.6.0   Back to index