systray mit function integrieren

Plattformunabhängige GUIs mit wxWidgets.
Antworten
matrixnet
User
Beiträge: 35
Registriert: Donnerstag 21. April 2005, 16:45

Freitag 21. Oktober 2005, 15:20

hi

ich habe nach einem anderem python geschrieben sourcecode den sourc ein mein source übernommen aber es kommt fheler beim kompilieren!

was ich über nommen habe sind diese codes:

Code: Alles auswählen

        if (sys.platform == 'win32'):
            self.icon = wxIcon('icon_bt.ico', wxBITMAP_TYPE_ICO)
        self.starttime = time ()

        self.frame = frame
        if (sys.platform == 'win32'):
            self.frame.SetIcon(self.icon)

Code: Alles auswählen

if (sys.platform == 'win32'):
            EVT_ICONIZE(self.frame, self.onIconify)

Code: Alles auswählen

def onIconify(self, evt):
         icon = 0
         if self.config is None:
             try:
                 self.config = self.dow.getConfig()
                 icon = self.config['win32_taskbar_icon']
             except NameError:
                 icon = 1
         else:
             icon = self.config['win32_taskbar_icon']
         if (icon):
           if not hasattr(self.frame, "tbicon"):
             self.frame.tbicon = wxTaskBarIcon()
             self.frame.tbicon.SetIcon(self.icon, "BitTorrent")
             # setup a taskbar icon, and catch some events from it
             EVT_TASKBAR_LEFT_DCLICK(self.frame.tbicon, self.onTaskBarActivate)
             EVT_TASKBAR_RIGHT_UP(self.frame.tbicon, self.onTaskBarMenu)
             EVT_MENU(self.frame.tbicon, self.TBMENU_RESTORE, self.onTaskBarActivate)
             EVT_MENU(self.frame.tbicon, self.TBMENU_CLOSE, self.done)
           self.frame.Hide()
         else:
           self.frame.Iconize(1)

     def onTaskBarActivate(self, evt):
         if self.frame.IsIconized():
             self.frame.Iconize(false)
         if not self.frame.IsShown():
             self.frame.Show(true)
         self.frame.Raise()
         if hasattr(self.frame, "tbicon"):
             del self.frame.tbicon
         return

    TBMENU_RESTORE = 1000
    TBMENU_CLOSE   = 1001

    def onTaskBarMenu(self, evt):
        menu = wxMenu()
        menu.Append(self.TBMENU_RESTORE, "Restore BitTorrent")
        menu.Append(self.TBMENU_CLOSE,   "Close")
        self.frame.tbicon.PopupMenu(menu)
        menu.Destroy()
und das ist der gesamte source :

Code: Alles auswählen

#!/usr/bin/env python

# Written by Bram Cohen and Myers Carpenter
# see LICENSE.txt for license information

from sys import argv
from BitTorrent import version
from BitTorrent.download import download
from btdownloadheadless import print_spew
from threading import Event, Thread
from os.path import join, split, exists
from os import getcwd
from wxPython.wx import *
from time import strftime, time
from webbrowser import open_new
from traceback import print_exc
import sys

def hours(n):
    if n == -1:
        return '<unknown>'
    if n == 0:
        return 'complete!'
    n = int(n)
    h, r = divmod(n, 60 * 60)
    m, sec = divmod(r, 60)
    if h > 1000000:
        return '<unknown>'
    if h > 0:
        return '%d hour %02d min %02d sec' % (h, m, sec)
    else:
        return '%d min %02d sec' % (m, sec)

wxEVT_INVOKE = wxNewEventType()

def EVT_INVOKE(win, func):
    win.Connect(-1, -1, wxEVT_INVOKE, func)

class InvokeEvent(wxPyEvent):
    def __init__(self):
        wxPyEvent.__init__(self)
        self.SetEventType(wxEVT_INVOKE)

class DownloadInfoFrame:
    def __init__(self, flag):
        frame = wxFrame(None, -1, 'BitTorrent ' + version + ' download', size = wxSize(400, 250))
        self.frame = frame
        self.flag = flag
        self.uiflag = Event()
        self.fin = False
        self.last_update_time = 0
        self.showing_error = False
        self.event = InvokeEvent()
        self.funclist = []

        if (sys.platform == 'win32'):
            self.icon = wxIcon('bittorrent.ico', wxBITMAP_TYPE_ICO)
        self.starttime = time ()

        self.frame = frame
        if (sys.platform == 'win32'):
            self.frame.SetIcon(self.icon)

        panel = wxPanel(frame, -1)
        colSizer = wxFlexGridSizer(cols = 1, vgap = 3)

        fnsizer = wxBoxSizer(wxHORIZONTAL)

        self.fileNameText = wxStaticText(panel, -1, '', style = wxALIGN_LEFT)
        fnsizer.Add(self.fileNameText, 1, wxALIGN_BOTTOM)
#I2P: cant have this for anonymity reasons
#       self.aboutText = wxStaticText(panel, -1, 'about', style = wxALIGN_RIGHT)
#       self.aboutText.SetForegroundColour('Blue')
#       self.aboutText.SetFont(wxFont(14, wxNORMAL, wxNORMAL, wxNORMAL, True))
#       fnsizer.Add(self.aboutText, 0, wxEXPAND)
#/I2P
        colSizer.Add(fnsizer, 0, wxEXPAND)

        self.gauge = wxGauge(panel, -1, range = 1000, style = wxGA_SMOOTH)
        colSizer.Add(self.gauge, 0, wxEXPAND)

        gridSizer = wxFlexGridSizer(cols = 2, vgap = 3, hgap = 8)
        
        gridSizer.Add(wxStaticText(panel, -1, 'Estimated time left:'))
        self.timeEstText = wxStaticText(panel, -1, '')
        gridSizer.Add(self.timeEstText, 0, wxEXPAND)

        gridSizer.Add(wxStaticText(panel, -1, 'Download to:'))
        self.fileDestText = wxStaticText(panel, -1, '')
        gridSizer.Add(self.fileDestText, 0, wxEXPAND)
        
        gridSizer.AddGrowableCol(1)

        rategridSizer = wxFlexGridSizer(cols = 4, vgap = 3, hgap = 8)

        rategridSizer.Add(wxStaticText(panel, -1, 'Download rate:'))
        self.downRateText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.downRateText, 0, wxEXPAND)

        rategridSizer.Add(wxStaticText(panel, -1, 'Downloaded:'))
        self.downTotalText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.downTotalText, 0, wxEXPAND)
        
        rategridSizer.Add(wxStaticText(panel, -1, 'Upload rate:'))
        self.upRateText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.upRateText, 0, wxEXPAND)
        
        
        rategridSizer.Add(wxStaticText(panel, -1, 'Uploaded:'))
        self.upTotalText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.upTotalText, 0, wxEXPAND)
       
        rategridSizer.AddGrowableCol(1)
        rategridSizer.AddGrowableCol(3)

        
        colSizer.Add(gridSizer, 0, wxEXPAND)
        colSizer.Add(rategridSizer, 0, wxEXPAND)
#I2P: wxPython 2.5 fix        
        colSizer.Add((50, 50), 0, wxEXPAND)
#/I2P
        self.cancelButton = wxButton(panel, -1, 'Cancel')
        colSizer.Add(self.cancelButton, 0, wxALIGN_CENTER)
        colSizer.AddGrowableCol(0)
        colSizer.AddGrowableRow(3)

        border = wxBoxSizer(wxHORIZONTAL)
        border.Add(colSizer, 1, wxEXPAND | wxALL, 4)
        panel.SetSizer(border)
        panel.SetAutoLayout(True)
        
#I2P: we cant have this for anonymity reasons
#       EVT_LEFT_DOWN(self.aboutText, self.donate)
#/I2P
        EVT_CLOSE(frame, self.done)
        EVT_BUTTON(frame, self.cancelButton.GetId(), self.done)
        EVT_INVOKE(frame, self.onInvoke)
        if (sys.platform == 'win32'):
            EVT_ICONIZE(self.frame, self.onIconify)
        self.frame.SetIcon(wxIcon(join(split(argv[0])[0], 'bittorrent.ico'), wxBITMAP_TYPE_ICO))
        self.frame.Show()

#I2P: we cant have this for anonymity reasons
#   def donate(self, event):
#       Thread(target = self.donate2).start()
#
#   def donate2(self):
#       open_new('http://bitconjurer.org/BitTorrent/donate.html')
#/I2P

     def onIconify(self, evt):
         icon = 0
         if self.config is None:
             try:
                 self.config = self.dow.getConfig()
                 icon = self.config['win32_taskbar_icon']
             except NameError:
                 icon = 1
         else:
             icon = self.config['win32_taskbar_icon']
         if (icon):
           if not hasattr(self.frame, "tbicon"):
             self.frame.tbicon = wxTaskBarIcon()
             self.frame.tbicon.SetIcon(self.icon, "BitTorrent")
             # setup a taskbar icon, and catch some events from it
             EVT_TASKBAR_LEFT_DCLICK(self.frame.tbicon, self.onTaskBarActivate)
             EVT_TASKBAR_RIGHT_UP(self.frame.tbicon, self.onTaskBarMenu)
             EVT_MENU(self.frame.tbicon, self.TBMENU_RESTORE, self.onTaskBarActivate)
             EVT_MENU(self.frame.tbicon, self.TBMENU_CLOSE, self.done)
           self.frame.Hide()
         else:
           self.frame.Iconize(1)

     def onTaskBarActivate(self, evt):
         if self.frame.IsIconized():
             self.frame.Iconize(false)
         if not self.frame.IsShown():
             self.frame.Show(true)
         self.frame.Raise()
         if hasattr(self.frame, "tbicon"):
             del self.frame.tbicon
         return

    TBMENU_RESTORE = 1000
    TBMENU_CLOSE   = 1001

    def onTaskBarMenu(self, evt):
        menu = wxMenu()
        menu.Append(self.TBMENU_RESTORE, "Restore BitTorrent")
        menu.Append(self.TBMENU_CLOSE,   "Close")
        self.frame.tbicon.PopupMenu(menu)
        menu.Destroy()


    def onInvoke(self, event):
        while not self.uiflag.isSet() and self.funclist:
            func, args, kwargs = self.funclist.pop(0)
            apply(func, args, kwargs)

    def invokeLater(self, func, args = [], kwargs = {}):
        if not self.uiflag.isSet():
            self.funclist.append((func, args, kwargs))
            if len(self.funclist) == 1:
                wxPostEvent(self.frame, self.event)

    def updateStatus(self, d):
        if (self.last_update_time + 0.1 < time() and not self.showing_error) or d.get('fractionDone') in (0.0, 1.0) or d.has_key('activity'):
            self.invokeLater(self.onUpdateStatus, [d])

    def onUpdateStatus(self, d):
        try:
            if d.has_key('spew'):
                print_spew(d['spew'])
            activity = d.get('activity')
            fractionDone = d.get('fractionDone')
            timeEst = d.get('timeEst')
            downRate = d.get('downRate')
            upRate = d.get('upRate')
            downTotal = d.get('downTotal')
            upTotal = d.get('upTotal')
            if activity is not None and not self.fin:
                self.timeEstText.SetLabel(activity)
            if fractionDone is not None and not self.fin:
                self.gauge.SetValue(int(fractionDone * 1000))
                self.frame.SetTitle('%d%% %s - BitTorrent %s' % (int(fractionDone*100), self.filename, version))
            if timeEst is not None:
                self.timeEstText.SetLabel(hours(timeEst))
            if downRate is not None:
                self.downRateText.SetLabel('%.0f KiB/s' % (float(downRate) / (1 << 10)))
            if upRate is not None:
                self.upRateText.SetLabel('%.0f KiB/s' % (float(upRate) / (1 << 10)))
            if downTotal is not None:
                self.downTotalText.SetLabel('%.1f M' % (downTotal))
            if upTotal is not None:
                self.upTotalText.SetLabel('%.1f M' % (upTotal))
            self.last_update_time = time()
        except:
            print_exc()

    def finished(self):
        self.fin = True
        self.invokeLater(self.onFinishEvent)

    def failed(self):
        self.fin = True
        self.invokeLater(self.onFailEvent)

    def error(self, errormsg):
        if not self.showing_error:
            self.invokeLater(self.onErrorEvent, [errormsg])

    def onFinishEvent(self):
        self.timeEstText.SetLabel('Download Succeeded!')
        self.cancelButton.SetLabel('Close')
        self.gauge.SetValue(1000)
        self.frame.SetTitle('%s - Upload - BitTorrent %s' % (self.filename, version))
        self.downRateText.SetLabel('')

    def onFailEvent(self):
        self.timeEstText.SetLabel('Failed!')
        self.cancelButton.SetLabel('Close')
        self.gauge.SetValue(0)
        self.downRateText.SetLabel('')

    def onErrorEvent(self, errormsg):
        self.showing_error = True
        dlg = wxMessageDialog(self.frame, message = errormsg, 
            caption = 'Download Error', style = wxOK | wxICON_ERROR)
        dlg.Fit()
        dlg.Center()
        dlg.ShowModal()
        self.showing_error = False

    def chooseFile(self, default, size, saveas, dir):
        f = Event()
        bucket = [None]
        self.invokeLater(self.onChooseFile, [default, bucket, f, size, dir, saveas])
        f.wait()
        return bucket[0]
    
    def onChooseFile(self, default, bucket, f, size, dir, saveas):
        if not saveas:
            if dir:
                dl = wxDirDialog(self.frame, 'Choose a directory to save to, pick a partial download to resume', 
                    join(getcwd(), default), style = wxDD_DEFAULT_STYLE | wxDD_NEW_DIR_BUTTON)
            else:
                dl = wxFileDialog(self.frame, 'Choose file to save as, pick a partial download to resume', '', default, '*', wxSAVE)
            if dl.ShowModal() != wxID_OK:
                self.done(None)
                f.set()
                return
            saveas = dl.GetPath()
        bucket[0] = saveas
        self.fileNameText.SetLabel('%s (%.1f MB)' % (default, float(size) / (1 << 20)))
        self.timeEstText.SetLabel('Starting up...')
        self.fileDestText.SetLabel(saveas)
        self.filename = default
        self.frame.SetTitle(default + '- BitTorrent ' + version)
        f.set()

    def newpath(self, path):
        self.fileDestText.SetLabel(path)

    def done(self, event):
        self.uiflag.set()
        self.flag.set()
        self.frame.Destroy()

class btWxApp(wxApp):
    def __init__(self, x, params):
        self.params = params
        wxApp.__init__(self, x)

    def OnInit(self):
        doneflag = Event()
#I2P: workaround for wxpython 2.4.x        
        wxInitAllImageHandlers() 
#/I2P
        d = DownloadInfoFrame(doneflag)
        self.SetTopWindow(d.frame)
#I2P: no args => file dialog
        if ''.join(self.params)[:2] in ['--','']:
            b = wxFileDialog (d.frame, 'Choose .torrent file to use',
                        defaultDir = '', defaultFile = '', wildcard = '*.torrent',
                        style = wxOPEN)

            if b.ShowModal() == wxID_OK:
                self.params.insert(0, b.GetPath())
            else:
                d.done(None)
                return 1
#/I2P
        thread = Thread(target = next, args = [self.params, d, doneflag])
        thread.setDaemon(False)
        thread.start()
        return 1

def run(params):
    try:
        app = btWxApp(0, params)
        app.MainLoop()
    except:
        print_exc()

def next(params, d, doneflag):
    try:
#I2P: remove donation shit, anonymity reasons
#        p = join(split(argv[0])[0], 'donated')
#        if not exists(p) and long(time()) % 3 == 0:
#            open_new('http://bitconjurer.org/BitTorrent/donate.html')
#            dlg = wxMessageDialog(d.frame, 'BitTorrent is Donation supported software. ' + 
#                'Please go to the donation page (which should be appearing for you now) and make a donation from there. ' + 
#                'Or you can click no and donate later.\n\nHave you made a donation yet?',
#                'Donate!', wxYES_NO | wxICON_INFORMATION | wxNO_DEFAULT)
#            if dlg.ShowModal() == wxID_YES:
#                dlg.Destroy()
#                dlg = wxMessageDialog(d.frame, 'Thanks for your donation! You will no longer be shown donation requests.\n\n' + 
#                    "If you haven't actually made a donation and are feeling guilty (as you should!) you can always get to " + 
#                    "the donation page by clicking the 'about' link in the upper-right corner of the main BitTorrent window and " + 
#                    'donating from there.', 'Thanks!', wxOK)
#                dlg.ShowModal()
#                dlg.Destroy()
#                try:
#                    open(p, 'wb').close()
#                except IOError, e:
#                    dlg = wxMessageDialog(d.frame, "Sorry, but I couldn't set the flag to not ask you for donations in the future - " + str(e),
#                        'Sorry!', wxOK | wxICON_ERROR)
#                    dlg.ShowModal()
#                    dlg.Destroy()
#            else:
#                dlg.Destroy()
#/I2P
        download(params, d.chooseFile, d.updateStatus, d.finished, d.error, doneflag, 100, d.newpath)
        if not d.fin:
            d.failed()
    except:
        print_exc()

if __name__ == '__main__':
    run(argv[1:])
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p
-bt\build.bat

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>del /F /S /Q build dist

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>c:\python23\python.exe winsetup.py py2
exe
running py2exe
*** searching for required modules ***
error: compiling 'btdownloadgui.py' failed
IndentationError: unindent does not match any outer indentation level (btdow
nloadgui.py, line 149)

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>e:\Programme\NSIS\makensis.exe" bittor
rent.nsi
Der Befehl "e:\Programme\NSIS\makensis.exe" bittorrent.nsi" ist entweder falsch
geschrieben oder
konnte nicht gefunden werden.

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p
-bt\build.bat

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>del /F /S /Q build dist

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>c:\python23\python.exe winsetup.py py2
exe
running py2exe
*** searching for required modules ***
error: compiling 'btdownloadgui.py' failed
IndentationError: unindent does not match any outer indentation level (btdow
nloadgui.py, line 148)

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>e:\Programme\NSIS\makensis.exe" bittor
rent.nsi
Der Befehl "e:\Programme\NSIS\makensis.exe" bittorrent.nsi" ist entweder falsch
geschrieben oder
konnte nicht gefunden werden.

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p
-bt\build.bat

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>del /F /S /Q build dist

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>c:\python23\python.exe winsetup.py py2
exe
running py2exe
*** searching for required modules ***
error: compiling 'btdownloadgui.py' failed
IndentationError: unindent does not match any outer indentation level (btdow
nloadgui.py, line 150)

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>e:\Programme\NSIS\makensis.exe" bittor
rent.nsi
Der Befehl "e:\Programme\NSIS\makensis.exe" bittorrent.nsi" ist entweder falsch
geschrieben oder
konnte nicht gefunden werden.

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p
-bt\build.bat

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>del /F /S /Q build dist

E:\Bittorrent-I2P\BitTorrent-3.4.2\i2p-bt>c:\python23\python.exe winsetup.py py2
exe
running py2exe
*** searching for required modules ***
error: compiling 'btdownloadgui.py' failed
IndentationError: unindent does not match any outer indentation level (btdow
nloadgui.py, line 151)


das ist der fehler im cmd:
E:\Bittest\i2p\build.bat

E:\Bittest\i2p-bt>del /F /S /Q build dist

E:\Bitest\i2p-bt>c:\python23\python.exe winsetup.py py2
exe
running py2exe
*** searching for required modules ***
error: compiling 'btdownloadgui.py' failed
IndentationError: unindent does not match any outer indentation level (btdownloadgui.py, line 151)
kann mit jemand weiterhelfen?

mfg

matrixnet
joe

Freitag 21. Oktober 2005, 16:55

matrixnet hat geschrieben:
E:\Bittest\i2p\build.bat

E:\Bittest\i2p-bt>del /F /S /Q build dist

E:\Bitest\i2p-bt>c:\python23\python.exe winsetup.py py2
exe
running py2exe
*** searching for required modules ***
error: compiling 'btdownloadgui.py' failed
IndentationError: unindent does not match any outer indentation level (btdownloadgui.py, line 151)
kann mit jemand weiterhelfen?
Die fehlermeldung ist doch ziemlich unmißverständlich. Die 151. Zeile (und tats. nicht nur die) ist falsch eingerückt.
joe
matrixnet
User
Beiträge: 35
Registriert: Donnerstag 21. April 2005, 16:45

Freitag 21. Oktober 2005, 18:33

also habe das porblem gelöst aber nun es geht nicht in stray wenn ich auf minimieren klicke!

Code: Alles auswählen

#!/usr/bin/env python

# Written by Bram Cohen and Myers Carpenter
# see LICENSE.txt for license information

from sys import argv
from BitTorrent import version
from BitTorrent.download import download
from btdownloadheadless import print_spew
from threading import Event, Thread
from os.path import join, split, exists
from os import getcwd
from wxPython.wx import *
from time import strftime, time
from webbrowser import open_new
from traceback import print_exc
import sys

def hours(n):
    if n == -1:
        return '<unknown>'
    if n == 0:
        return 'complete!'
    n = int(n)
    h, r = divmod(n, 60 * 60)
    m, sec = divmod(r, 60)
    if h > 1000000:
        return '<unknown>'
    if h > 0:
        return '%d hour %02d min %02d sec' % (h, m, sec)
    else:
        return '%d min %02d sec' % (m, sec)

wxEVT_INVOKE = wxNewEventType()

def EVT_INVOKE(win, func):
    win.Connect(-1, -1, wxEVT_INVOKE, func)

class InvokeEvent(wxPyEvent):
    def __init__(self):
        wxPyEvent.__init__(self)
        self.SetEventType(wxEVT_INVOKE)

class DownloadInfoFrame:
    def __init__(self, flag):
        frame = wxFrame(None, -1, 'BitTorrent ' + version + ' download', size = wxSize(400, 250))
        self.frame = frame
        self.flag = flag
        self.uiflag = Event()
        self.fin = False
        self.last_update_time = 0
        self.showing_error = False
        self.event = InvokeEvent()
        self.funclist = []

        if (sys.platform == 'win32'):
            self.icon = wxIcon('bittorrent.ico', wxBITMAP_TYPE_ICO)
        self.starttime = time ()

        self.frame = frame
        if (sys.platform == 'win32'):
            self.frame.SetIcon(self.icon)

        panel = wxPanel(frame, -1)
        colSizer = wxFlexGridSizer(cols = 1, vgap = 3)

        fnsizer = wxBoxSizer(wxHORIZONTAL)

        self.fileNameText = wxStaticText(panel, -1, '', style = wxALIGN_LEFT)
        fnsizer.Add(self.fileNameText, 1, wxALIGN_BOTTOM)
#I2P: cant have this for anonymity reasons
#       self.aboutText = wxStaticText(panel, -1, 'about', style = wxALIGN_RIGHT)
#       self.aboutText.SetForegroundColour('Blue')
#       self.aboutText.SetFont(wxFont(14, wxNORMAL, wxNORMAL, wxNORMAL, True))
#       fnsizer.Add(self.aboutText, 0, wxEXPAND)
#/I2P
        colSizer.Add(fnsizer, 0, wxEXPAND)

        self.gauge = wxGauge(panel, -1, range = 1000, style = wxGA_SMOOTH)
        colSizer.Add(self.gauge, 0, wxEXPAND)

        gridSizer = wxFlexGridSizer(cols = 2, vgap = 3, hgap = 8)
        
        gridSizer.Add(wxStaticText(panel, -1, 'Estimated time left:'))
        self.timeEstText = wxStaticText(panel, -1, '')
        gridSizer.Add(self.timeEstText, 0, wxEXPAND)

        gridSizer.Add(wxStaticText(panel, -1, 'Download to:'))
        self.fileDestText = wxStaticText(panel, -1, '')
        gridSizer.Add(self.fileDestText, 0, wxEXPAND)
        
        gridSizer.AddGrowableCol(1)

        rategridSizer = wxFlexGridSizer(cols = 4, vgap = 3, hgap = 8)

        rategridSizer.Add(wxStaticText(panel, -1, 'Download rate:'))
        self.downRateText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.downRateText, 0, wxEXPAND)

        rategridSizer.Add(wxStaticText(panel, -1, 'Downloaded:'))
        self.downTotalText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.downTotalText, 0, wxEXPAND)
        
        rategridSizer.Add(wxStaticText(panel, -1, 'Upload rate:'))
        self.upRateText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.upRateText, 0, wxEXPAND)
        
        
        rategridSizer.Add(wxStaticText(panel, -1, 'Uploaded:'))
        self.upTotalText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.upTotalText, 0, wxEXPAND)
       
        rategridSizer.AddGrowableCol(1)
        rategridSizer.AddGrowableCol(3)

        
        colSizer.Add(gridSizer, 0, wxEXPAND)
        colSizer.Add(rategridSizer, 0, wxEXPAND)
#I2P: wxPython 2.5 fix        
        colSizer.Add((50, 50), 0, wxEXPAND)
#/I2P
        self.cancelButton = wxButton(panel, -1, 'Cancel')
        colSizer.Add(self.cancelButton, 0, wxALIGN_CENTER)
        colSizer.AddGrowableCol(0)
        colSizer.AddGrowableRow(3)

        border = wxBoxSizer(wxHORIZONTAL)
        border.Add(colSizer, 1, wxEXPAND | wxALL, 4)
        panel.SetSizer(border)
        panel.SetAutoLayout(True)
        
#I2P: we cant have this for anonymity reasons
#       EVT_LEFT_DOWN(self.aboutText, self.donate)
#/I2P
        EVT_CLOSE(frame, self.done)
        EVT_BUTTON(frame, self.cancelButton.GetId(), self.done)
        EVT_INVOKE(frame, self.onInvoke)
        if (sys.platform == 'win32'):
            EVT_ICONIZE(self.frame, self.onIconify)
        self.frame.SetIcon(wxIcon(join(split(argv[0])[0], 'bittorrent.ico'), wxBITMAP_TYPE_ICO))
        self.frame.Show()

#I2P: we cant have this for anonymity reasons
#   def donate(self, event):
#       Thread(target = self.donate2).start()
#
#   def donate2(self):
#       open_new('http://bitconjurer.org/BitTorrent/donate.html')
#/I2P

    def onIconify(self, evt):
        icon = 0
        if self.config is None:
            try:
                self.config = self.dow.getConfig()
                icon = self.config['win32_taskbar_icon']
            except NameError:
                icon = 1
        else:
            icon = self.config['win32_taskbar_icon']
        if (icon):
          if not hasattr(self.frame, "tbicon"):
            self.frame.tbicon = wxTaskBarIcon()
            self.frame.tbicon.SetIcon(self.icon, "BitTorrent")
            # setup a taskbar icon, and catch some events from it
            EVT_TASKBAR_LEFT_DCLICK(self.frame.tbicon, self.onTaskBarActivate)
            EVT_TASKBAR_RIGHT_UP(self.frame.tbicon, self.onTaskBarMenu)
            EVT_MENU(self.frame.tbicon, self.TBMENU_RESTORE, self.onTaskBarActivate)
            EVT_MENU(self.frame.tbicon, self.TBMENU_CLOSE, self.done)
          self.frame.Hide()
        else:
          self.frame.Iconize(1)

    def onTaskBarActivate(self, evt):
        if self.frame.IsIconized():
            self.frame.Iconize(false)
        if not self.frame.IsShown():
            self.frame.Show(true)
        self.frame.Raise()
        if hasattr(self.frame, "tbicon"):
            del self.frame.tbicon
        return

    TBMENU_RESTORE = 1000
    TBMENU_CLOSE   = 1001

    def onTaskBarMenu(self, evt):
        menu = wxMenu()
        menu.Append(self.TBMENU_RESTORE, "Restore BitTorrent")
        menu.Append(self.TBMENU_CLOSE,   "Close")
        self.frame.tbicon.PopupMenu(menu)
        menu.Destroy()


    def onInvoke(self, event):
        while not self.uiflag.isSet() and self.funclist:
            func, args, kwargs = self.funclist.pop(0)
            apply(func, args, kwargs)

    def invokeLater(self, func, args = [], kwargs = {}):
        if not self.uiflag.isSet():
            self.funclist.append((func, args, kwargs))
            if len(self.funclist) == 1:
                wxPostEvent(self.frame, self.event)

    def updateStatus(self, d):
        if (self.last_update_time + 0.1 < time() and not self.showing_error) or d.get('fractionDone') in (0.0, 1.0) or d.has_key('activity'):
            self.invokeLater(self.onUpdateStatus, [d])

    def onUpdateStatus(self, d):
        try:
            if d.has_key('spew'):
                print_spew(d['spew'])
            activity = d.get('activity')
            fractionDone = d.get('fractionDone')
            timeEst = d.get('timeEst')
            downRate = d.get('downRate')
            upRate = d.get('upRate')
            downTotal = d.get('downTotal')
            upTotal = d.get('upTotal')
            if activity is not None and not self.fin:
                self.timeEstText.SetLabel(activity)
            if fractionDone is not None and not self.fin:
                self.gauge.SetValue(int(fractionDone * 1000))
                self.frame.SetTitle('%d%% %s - BitTorrent %s' % (int(fractionDone*100), self.filename, version))
            if timeEst is not None:
                self.timeEstText.SetLabel(hours(timeEst))
            if downRate is not None:
                self.downRateText.SetLabel('%.0f KiB/s' % (float(downRate) / (1 << 10)))
            if upRate is not None:
                self.upRateText.SetLabel('%.0f KiB/s' % (float(upRate) / (1 << 10)))
            if downTotal is not None:
                self.downTotalText.SetLabel('%.1f M' % (downTotal))
            if upTotal is not None:
                self.upTotalText.SetLabel('%.1f M' % (upTotal))
            self.last_update_time = time()
        except:
            print_exc()

    def finished(self):
        self.fin = True
        self.invokeLater(self.onFinishEvent)

    def failed(self):
        self.fin = True
        self.invokeLater(self.onFailEvent)

    def error(self, errormsg):
        if not self.showing_error:
            self.invokeLater(self.onErrorEvent, [errormsg])

    def onFinishEvent(self):
        self.timeEstText.SetLabel('Download Succeeded!')
        self.cancelButton.SetLabel('Close')
        self.gauge.SetValue(1000)
        self.frame.SetTitle('%s - Upload - BitTorrent %s' % (self.filename, version))
        self.downRateText.SetLabel('')

    def onFailEvent(self):
        self.timeEstText.SetLabel('Failed!')
        self.cancelButton.SetLabel('Close')
        self.gauge.SetValue(0)
        self.downRateText.SetLabel('')

    def onErrorEvent(self, errormsg):
        self.showing_error = True
        dlg = wxMessageDialog(self.frame, message = errormsg, 
            caption = 'Download Error', style = wxOK | wxICON_ERROR)
        dlg.Fit()
        dlg.Center()
        dlg.ShowModal()
        self.showing_error = False

    def chooseFile(self, default, size, saveas, dir):
        f = Event()
        bucket = [None]
        self.invokeLater(self.onChooseFile, [default, bucket, f, size, dir, saveas])
        f.wait()
        return bucket[0]
    
    def onChooseFile(self, default, bucket, f, size, dir, saveas):
        if not saveas:
            if dir:
                dl = wxDirDialog(self.frame, 'Choose a directory to save to, pick a partial download to resume', 
                    join(getcwd(), default), style = wxDD_DEFAULT_STYLE | wxDD_NEW_DIR_BUTTON)
            else:
                dl = wxFileDialog(self.frame, 'Choose file to save as, pick a partial download to resume', '', default, '*', wxSAVE)
            if dl.ShowModal() != wxID_OK:
                self.done(None)
                f.set()
                return
            saveas = dl.GetPath()
        bucket[0] = saveas
        self.fileNameText.SetLabel('%s (%.1f MB)' % (default, float(size) / (1 << 20)))
        self.timeEstText.SetLabel('Starting up...')
        self.fileDestText.SetLabel(saveas)
        self.filename = default
        self.frame.SetTitle(default + '- BitTorrent ' + version)
        f.set()

    def newpath(self, path):
        self.fileDestText.SetLabel(path)

    def done(self, event):
        self.uiflag.set()
        self.flag.set()
        self.frame.Destroy()

class btWxApp(wxApp):
    def __init__(self, x, params):
        self.params = params
        wxApp.__init__(self, x)

    def OnInit(self):
        doneflag = Event()
#I2P: workaround for wxpython 2.4.x        
        wxInitAllImageHandlers() 
#/I2P
        d = DownloadInfoFrame(doneflag)
        self.SetTopWindow(d.frame)
#I2P: no args => file dialog
        if ''.join(self.params)[:2] in ['--','']:
            b = wxFileDialog (d.frame, 'Choose .torrent file to use',
                        defaultDir = '', defaultFile = '', wildcard = '*.torrent',
                        style = wxOPEN)

            if b.ShowModal() == wxID_OK:
                self.params.insert(0, b.GetPath())
            else:
                d.done(None)
                return 1
#/I2P
        thread = Thread(target = next, args = [self.params, d, doneflag])
        thread.setDaemon(False)
        thread.start()
        return 1

def run(params):
    try:
        app = btWxApp(0, params)
        app.MainLoop()
    except:
        print_exc()

def next(params, d, doneflag):
    try:
#I2P: remove donation shit, anonymity reasons
#        p = join(split(argv[0])[0], 'donated')
#        if not exists(p) and long(time()) % 3 == 0:
#            open_new('http://bitconjurer.org/BitTorrent/donate.html')
#            dlg = wxMessageDialog(d.frame, 'BitTorrent is Donation supported software. ' + 
#                'Please go to the donation page (which should be appearing for you now) and make a donation from there. ' + 
#                'Or you can click no and donate later.\n\nHave you made a donation yet?',
#                'Donate!', wxYES_NO | wxICON_INFORMATION | wxNO_DEFAULT)
#            if dlg.ShowModal() == wxID_YES:
#                dlg.Destroy()
#                dlg = wxMessageDialog(d.frame, 'Thanks for your donation! You will no longer be shown donation requests.\n\n' + 
#                    "If you haven't actually made a donation and are feeling guilty (as you should!) you can always get to " + 
#                    "the donation page by clicking the 'about' link in the upper-right corner of the main BitTorrent window and " + 
#                    'donating from there.', 'Thanks!', wxOK)
#                dlg.ShowModal()
#                dlg.Destroy()
#                try:
#                    open(p, 'wb').close()
#                except IOError, e:
#                    dlg = wxMessageDialog(d.frame, "Sorry, but I couldn't set the flag to not ask you for donations in the future - " + str(e),
#                        'Sorry!', wxOK | wxICON_ERROR)
#                    dlg.ShowModal()
#                    dlg.Destroy()
#            else:
#                dlg.Destroy()
#/I2P
        download(params, d.chooseFile, d.updateStatus, d.finished, d.error, doneflag, 100, d.newpath)
        if not d.fin:
            d.failed()
    except:
        print_exc()

if __name__ == '__main__':
    run(argv[1:])
und im btdownloadgui.exe.log steht das:
Traceback (most recent call last):
File "btdownloadgui.py", line 153, in onIconify
AttributeError: DownloadInfoFrame instance has no attribute 'config'
es geht nicht in straytray aber als ich das porgramm geschlossen habe habe ich gesehen das im taskmanager noch aktive ist btdownloadgui.exe!
matrixnet
User
Beiträge: 35
Registriert: Donnerstag 21. April 2005, 16:45

Freitag 21. Oktober 2005, 22:08

nun habe ich das config porblem gelöst!
aber ich weis nciht wie ich das dow problem lösen soll?
ich weis nicht woher es dow holel soll?

habe mein sourcecode wieder angepasst!

Code: Alles auswählen

#!/usr/bin/env python

# Written by Bram Cohen and Myers Carpenter
# see LICENSE.txt for license information

from sys import argv
from BitTorrent import version
from BitTorrent.download import download
from btdownloadheadless import print_spew
from threading import Event, Thread
from os.path import join, split, exists
from os import getcwd
from wxPython.wx import *
from time import strftime, time
from webbrowser import open_new
from traceback import print_exc
import sys

def hours(n):
    if n == -1:
        return '<unknown>'
    if n == 0:
        return 'complete!'
    n = int(n)
    h, r = divmod(n, 60 * 60)
    m, sec = divmod(r, 60)
    if h > 1000000:
        return '<unknown>'
    if h > 0:
        return '%d hour %02d min %02d sec' % (h, m, sec)
    else:
        return '%d min %02d sec' % (m, sec)

wxEVT_INVOKE = wxNewEventType()

def EVT_INVOKE(win, func):
    win.Connect(-1, -1, wxEVT_INVOKE, func)

class InvokeEvent(wxPyEvent):
    def __init__(self):
        wxPyEvent.__init__(self)
        self.SetEventType(wxEVT_INVOKE)

class DownloadInfoFrame:
    def __init__(self, flag):
        frame = wxFrame(None, -1, 'BitTorrent ' + version + ' download', size = wxSize(400, 250))
        self.frame = frame
        self.flag = flag
        self.uiflag = Event()
        self.fin = False
        self.last_update_time = 0
        self.showing_error = False
        self.event = InvokeEvent()
        self.funclist = []
        self.config = None

        if (sys.platform == 'win32'):
            self.icon = wxIcon('bittorrent.ico', wxBITMAP_TYPE_ICO)
        self.starttime = time ()

        self.frame = frame
        if (sys.platform == 'win32'):
            self.frame.SetIcon(self.icon)

        panel = wxPanel(frame, -1)
        colSizer = wxFlexGridSizer(cols = 1, vgap = 3)

        fnsizer = wxBoxSizer(wxHORIZONTAL)

        self.fileNameText = wxStaticText(panel, -1, '', style = wxALIGN_LEFT)
        fnsizer.Add(self.fileNameText, 1, wxALIGN_BOTTOM)
#I2P: cant have this for anonymity reasons
#       self.aboutText = wxStaticText(panel, -1, 'about', style = wxALIGN_RIGHT)
#       self.aboutText.SetForegroundColour('Blue')
#       self.aboutText.SetFont(wxFont(14, wxNORMAL, wxNORMAL, wxNORMAL, True))
#       fnsizer.Add(self.aboutText, 0, wxEXPAND)
#/I2P
        colSizer.Add(fnsizer, 0, wxEXPAND)

        self.gauge = wxGauge(panel, -1, range = 1000, style = wxGA_SMOOTH)
        colSizer.Add(self.gauge, 0, wxEXPAND)

        gridSizer = wxFlexGridSizer(cols = 2, vgap = 3, hgap = 8)
        
        gridSizer.Add(wxStaticText(panel, -1, 'Estimated time left:'))
        self.timeEstText = wxStaticText(panel, -1, '')
        gridSizer.Add(self.timeEstText, 0, wxEXPAND)

        gridSizer.Add(wxStaticText(panel, -1, 'Download to:'))
        self.fileDestText = wxStaticText(panel, -1, '')
        gridSizer.Add(self.fileDestText, 0, wxEXPAND)
        
        gridSizer.AddGrowableCol(1)

        rategridSizer = wxFlexGridSizer(cols = 4, vgap = 3, hgap = 8)

        rategridSizer.Add(wxStaticText(panel, -1, 'Download rate:'))
        self.downRateText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.downRateText, 0, wxEXPAND)

        rategridSizer.Add(wxStaticText(panel, -1, 'Downloaded:'))
        self.downTotalText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.downTotalText, 0, wxEXPAND)
        
        rategridSizer.Add(wxStaticText(panel, -1, 'Upload rate:'))
        self.upRateText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.upRateText, 0, wxEXPAND)
        
        
        rategridSizer.Add(wxStaticText(panel, -1, 'Uploaded:'))
        self.upTotalText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.upTotalText, 0, wxEXPAND)
       
        rategridSizer.AddGrowableCol(1)
        rategridSizer.AddGrowableCol(3)

        
        colSizer.Add(gridSizer, 0, wxEXPAND)
        colSizer.Add(rategridSizer, 0, wxEXPAND)
#I2P: wxPython 2.5 fix        
        colSizer.Add((50, 50), 0, wxEXPAND)
#/I2P
        self.cancelButton = wxButton(panel, -1, 'Cancel')
        colSizer.Add(self.cancelButton, 0, wxALIGN_CENTER)
        colSizer.AddGrowableCol(0)
        colSizer.AddGrowableRow(3)

        border = wxBoxSizer(wxHORIZONTAL)
        border.Add(colSizer, 1, wxEXPAND | wxALL, 4)
        panel.SetSizer(border)
        panel.SetAutoLayout(True)
        
#I2P: we cant have this for anonymity reasons
#       EVT_LEFT_DOWN(self.aboutText, self.donate)
#/I2P
        EVT_CLOSE(frame, self.done)
        EVT_BUTTON(frame, self.cancelButton.GetId(), self.done)
        EVT_INVOKE(frame, self.onInvoke)
        if (sys.platform == 'win32'):
            EVT_ICONIZE(self.frame, self.onIconify)
        self.frame.SetIcon(wxIcon(join(split(argv[0])[0], 'bittorrent.ico'), wxBITMAP_TYPE_ICO))
        self.frame.Show()

#I2P: we cant have this for anonymity reasons
#   def donate(self, event):
#       Thread(target = self.donate2).start()
#
#   def donate2(self):
#       open_new('http://bitconjurer.org/BitTorrent/donate.html')
#/I2P

    def onIconify(self, evt):
        icon = 0
        if self.config is None:
            try:
                self.config = self.dow.getConfig()
                icon = self.config['win32_taskbar_icon']
            except NameError:
                icon = 1
        else:
            icon = self.config['win32_taskbar_icon']
        if (icon):
          if not hasattr(self.frame, "tbicon"):
            self.frame.tbicon = wxTaskBarIcon()
            self.frame.tbicon.SetIcon(self.icon, "BitTorrent")
            # setup a taskbar icon, and catch some events from it
            EVT_TASKBAR_LEFT_DCLICK(self.frame.tbicon, self.onTaskBarActivate)
            EVT_TASKBAR_RIGHT_UP(self.frame.tbicon, self.onTaskBarMenu)
            EVT_MENU(self.frame.tbicon, self.TBMENU_RESTORE, self.onTaskBarActivate)
            EVT_MENU(self.frame.tbicon, self.TBMENU_CLOSE, self.done)
          self.frame.Hide()
        else:
          self.frame.Iconize(1)

    def onTaskBarActivate(self, evt):
        if self.frame.IsIconized():
            self.frame.Iconize(false)
        if not self.frame.IsShown():
            self.frame.Show(true)
        self.frame.Raise()
        if hasattr(self.frame, "tbicon"):
            del self.frame.tbicon
        return

    TBMENU_RESTORE = 1000
    TBMENU_CLOSE   = 1001

    def onTaskBarMenu(self, evt):
        menu = wxMenu()
        menu.Append(self.TBMENU_RESTORE, "Restore BitTorrent")
        menu.Append(self.TBMENU_CLOSE,   "Close")
        self.frame.tbicon.PopupMenu(menu)
        menu.Destroy()


    def onInvoke(self, event):
        while not self.uiflag.isSet() and self.funclist:
            func, args, kwargs = self.funclist.pop(0)
            apply(func, args, kwargs)

    def invokeLater(self, func, args = [], kwargs = {}):
        if not self.uiflag.isSet():
            self.funclist.append((func, args, kwargs))
            if len(self.funclist) == 1:
                wxPostEvent(self.frame, self.event)

    def updateStatus(self, d):
        if (self.last_update_time + 0.1 < time() and not self.showing_error) or d.get('fractionDone') in (0.0, 1.0) or d.has_key('activity'):
            self.invokeLater(self.onUpdateStatus, [d])

    def onUpdateStatus(self, d):
        try:
            if d.has_key('spew'):
                print_spew(d['spew'])
            activity = d.get('activity')
            fractionDone = d.get('fractionDone')
            timeEst = d.get('timeEst')
            downRate = d.get('downRate')
            upRate = d.get('upRate')
            downTotal = d.get('downTotal')
            upTotal = d.get('upTotal')
            if activity is not None and not self.fin:
                self.timeEstText.SetLabel(activity)
            if fractionDone is not None and not self.fin:
                self.gauge.SetValue(int(fractionDone * 1000))
                self.frame.SetTitle('%d%% %s - BitTorrent %s' % (int(fractionDone*100), self.filename, version))
            if timeEst is not None:
                self.timeEstText.SetLabel(hours(timeEst))
            if downRate is not None:
                self.downRateText.SetLabel('%.0f KiB/s' % (float(downRate) / (1 << 10)))
            if upRate is not None:
                self.upRateText.SetLabel('%.0f KiB/s' % (float(upRate) / (1 << 10)))
            if downTotal is not None:
                self.downTotalText.SetLabel('%.1f M' % (downTotal))
            if upTotal is not None:
                self.upTotalText.SetLabel('%.1f M' % (upTotal))
            self.last_update_time = time()
        except:
            print_exc()

    def finished(self):
        self.fin = True
        self.invokeLater(self.onFinishEvent)

    def failed(self):
        self.fin = True
        self.invokeLater(self.onFailEvent)

    def error(self, errormsg):
        if not self.showing_error:
            self.invokeLater(self.onErrorEvent, [errormsg])

    def onFinishEvent(self):
        self.timeEstText.SetLabel('Download Succeeded!')
        self.cancelButton.SetLabel('Close')
        self.gauge.SetValue(1000)
        self.frame.SetTitle('%s - Upload - BitTorrent %s' % (self.filename, version))
        self.downRateText.SetLabel('')

    def onFailEvent(self):
        self.timeEstText.SetLabel('Failed!')
        self.cancelButton.SetLabel('Close')
        self.gauge.SetValue(0)
        self.downRateText.SetLabel('')

    def onErrorEvent(self, errormsg):
        self.showing_error = True
        dlg = wxMessageDialog(self.frame, message = errormsg, 
            caption = 'Download Error', style = wxOK | wxICON_ERROR)
        dlg.Fit()
        dlg.Center()
        dlg.ShowModal()
        self.showing_error = False

    def chooseFile(self, default, size, saveas, dir):
        f = Event()
        bucket = [None]
        self.invokeLater(self.onChooseFile, [default, bucket, f, size, dir, saveas])
        f.wait()
        return bucket[0]
    
    def onChooseFile(self, default, bucket, f, size, dir, saveas):
        if not saveas:
            if dir:
                dl = wxDirDialog(self.frame, 'Choose a directory to save to, pick a partial download to resume', 
                    join(getcwd(), default), style = wxDD_DEFAULT_STYLE | wxDD_NEW_DIR_BUTTON)
            else:
                dl = wxFileDialog(self.frame, 'Choose file to save as, pick a partial download to resume', '', default, '*', wxSAVE)
            if dl.ShowModal() != wxID_OK:
                self.done(None)
                f.set()
                return
            saveas = dl.GetPath()
        bucket[0] = saveas
        self.fileNameText.SetLabel('%s (%.1f MB)' % (default, float(size) / (1 << 20)))
        self.timeEstText.SetLabel('Starting up...')
        self.fileDestText.SetLabel(saveas)
        self.filename = default
        self.frame.SetTitle(default + '- BitTorrent ' + version)
        f.set()

    def newpath(self, path):
        self.fileDestText.SetLabel(path)

    def done(self, event):
        self.uiflag.set()
        self.flag.set()
        self.frame.Destroy()

class btWxApp(wxApp):
    def __init__(self, x, params):
        self.params = params
        wxApp.__init__(self, x)

    def OnInit(self):
        doneflag = Event()
#I2P: workaround for wxpython 2.4.x        
        wxInitAllImageHandlers() 
#/I2P
        d = DownloadInfoFrame(doneflag)
        self.SetTopWindow(d.frame)
#I2P: no args => file dialog
        if ''.join(self.params)[:2] in ['--','']:
            b = wxFileDialog (d.frame, 'Choose .torrent file to use',
                        defaultDir = '', defaultFile = '', wildcard = '*.torrent',
                        style = wxOPEN)

            if b.ShowModal() == wxID_OK:
                self.params.insert(0, b.GetPath())
            else:
                d.done(None)
                return 1
#/I2P
        thread = Thread(target = next, args = [self.params, d, doneflag])
        thread.setDaemon(False)
        thread.start()
        return 1

def run(params):
    try:
        app = btWxApp(0, params)
        app.MainLoop()
    except:
        print_exc()

def next(params, d, doneflag):
    try:
#I2P: remove donation shit, anonymity reasons
#        p = join(split(argv[0])[0], 'donated')
#        if not exists(p) and long(time()) % 3 == 0:
#            open_new('http://bitconjurer.org/BitTorrent/donate.html')
#            dlg = wxMessageDialog(d.frame, 'BitTorrent is Donation supported software. ' + 
#                'Please go to the donation page (which should be appearing for you now) and make a donation from there. ' + 
#                'Or you can click no and donate later.\n\nHave you made a donation yet?',
#                'Donate!', wxYES_NO | wxICON_INFORMATION | wxNO_DEFAULT)
#            if dlg.ShowModal() == wxID_YES:
#                dlg.Destroy()
#                dlg = wxMessageDialog(d.frame, 'Thanks for your donation! You will no longer be shown donation requests.\n\n' + 
#                    "If you haven't actually made a donation and are feeling guilty (as you should!) you can always get to " + 
#                    "the donation page by clicking the 'about' link in the upper-right corner of the main BitTorrent window and " + 
#                    'donating from there.', 'Thanks!', wxOK)
#                dlg.ShowModal()
#                dlg.Destroy()
#                try:
#                    open(p, 'wb').close()
#                except IOError, e:
#                    dlg = wxMessageDialog(d.frame, "Sorry, but I couldn't set the flag to not ask you for donations in the future - " + str(e),
#                        'Sorry!', wxOK | wxICON_ERROR)
#                    dlg.ShowModal()
#                    dlg.Destroy()
#            else:
#                dlg.Destroy()
#/I2P
        download(params, d.chooseFile, d.updateStatus, d.finished, d.error, doneflag, 100, d.newpath)
        if not d.fin:
            d.failed()
    except:
        print_exc()

if __name__ == '__main__':
    run(argv[1:])

Traceback (most recent call last):
File "btdownloadgui.py", line 156, in onIconify
AttributeError: DownloadInfoFrame instance has no attribute 'dow'
BlackJack

Freitag 21. Oktober 2005, 23:39

Auch die Fehlermeldung ist ziemlich eindeutig. Es gibt kein `dow` Attribut und Du versuchst drauf zuzugreifen. Warum machst Du das?
Gast

Samstag 22. Oktober 2005, 10:11

ja die fehlermeldung ist mir klar irgendwo muss dow existieren!

ich will unbedingt ein sysstrayfuntion!

ich habes nach dem experimental sourcecode abgeschaut weil das systray hat!

heir ist der source bei dem systray geht! ich will das bei meinem source auch klappt!

Code: Alles auswählen

#!c:\python23\python.exe

# Written by Bram Cohen and Myers Carpenter
# Modifications by various people
# see LICENSE.txt for license information

from sys import argv, version
assert version >= '2', "Install Python 2.0 or greater"

from BitTorrent import version
from BitTorrent.download import *
from BitTorrent.ConnChoice import *
from threading import Event, Thread
from os.path import *
from os import getcwd
from wxPython.wx import *
from time import strftime
from webbrowser import open_new
import re
import sys
true = 1
false = 0

def hours(n):
    if n == -1:
        return '<unknown>'
    if n == 0:
        return 'complete!'
    n = int(n)
    h, r = divmod(n, 60 * 60)
    m, sec = divmod(r, 60)
    if h > 1000000:
        return '<unknown>'
    if h > 0:
        return '%d hour(s) %02d min %02d sec' % (h, m, sec)
    else:
        return '%d min %02d sec' % (m, sec)

wxEVT_INVOKE = wxNewEventType()

def EVT_INVOKE(win, func):
    win.Connect(-1, -1, wxEVT_INVOKE, func)

class InvokeEvent(wxPyEvent):
    def __init__(self, func, args, kwargs):
        wxPyEvent.__init__(self)
        self.SetEventType(wxEVT_INVOKE)
        self.func = func
        self.args = args
        self.kwargs = kwargs

def pr(event):
    print 'augh!'

class DownloadInfoFrame:
    def __init__(self, flag):
        frame = wxFrame(None, -1, 'BitTorrent ' + version + ' download')
        self.aaa = 0
        self.flag = flag
        self.fin = false
        self.aboutBox = None
        self.detailBox = None
        self.advBox = None
        self.creditsBox = None
        self.reannouncelast = 0
        self.spinlock = 0
        self.scrollock = 0
        self.lastError = 0
        self.spewwait = time ()
        self.config = None
        self.updateSpinnerFlag = 0
        self.updateSliderFlag = 0

        if (sys.platform == 'win32'):
            self.icon = wxIcon('icon_bt.ico', wxBITMAP_TYPE_ICO)
        self.starttime = time ()

        self.frame = frame
        if (sys.platform == 'win32'):
            self.frame.SetIcon(self.icon)

        panel = wxPanel(frame, -1)
        colSizer = wxFlexGridSizer(cols = 1, vgap = 3)
        colSizer.AddGrowableCol (0)
        colSizer.AddGrowableRow (6)
        border = wxBoxSizer(wxHORIZONTAL)
        border.Add(colSizer, 1, wxEXPAND | wxALL, 4)
        panel.SetSizer(border)
        panel.SetAutoLayout(true)

        fnsizer = wxFlexGridSizer(cols = 4)
        fnsizer.AddGrowableCol (0)
        fileNameText = wxStaticText(panel, -1, '', style = wxALIGN_LEFT)
        fileNameText.SetFont(wxFont(12, wxDEFAULT, wxNORMAL, wxNORMAL, false))
        fnsizer.Add(fileNameText, 1, wxALIGN_BOTTOM|wxEXPAND)

        fileDetails = wxStaticText(panel, -1, 'Details', style = wxALIGN_RIGHT)
        fileDetails.SetFont(wxFont(12, wxDEFAULT, wxNORMAL, wxNORMAL, true))
        fileDetails.SetForegroundColour('Blue')

        fnsizer.Add(fileDetails, 0, wxALIGN_BOTTOM)                                     
        fnspacer = wxStaticText(panel, -1, '  ', style = wxALIGN_RIGHT)
        fnsizer.Add(fnspacer)

        aboutText = wxStaticText(panel, -1, 'About', style = wxALIGN_RIGHT)
        aboutText.SetForegroundColour('Blue')
        aboutText.SetFont(wxFont(12, wxDEFAULT, wxNORMAL, wxNORMAL, true))
        fnsizer.Add(aboutText, 0, wxEXPAND)
        self.fileNameText = fileNameText
        self.fnsizer = fnsizer
        colSizer.Add(fnsizer, 0, wxEXPAND)

        self.gauge = wxGauge(panel, -1, range = 1000, style = wxGA_SMOOTH)
        colSizer.Add(self.gauge, 0, wxEXPAND)
        self.gauge.SetForegroundColour(wx.wxSystemSettings_GetColour(wxSYS_COLOUR_3DSHADOW))

        timeSizer = wxFlexGridSizer(cols = 2)
        timeSizer.Add(wxStaticText(panel, -1, 'Time elapsed / estimated : '))
        self.timeText = wxStaticText(panel, -1, '                                  ')
        timeSizer.Add(self.timeText)
        timeSizer.AddGrowableCol(1)
        colSizer.Add(timeSizer)

        destSizer = wxFlexGridSizer(cols = 2, hgap = 8)
        destSizer.Add(wxStaticText(panel, -1, 'Download to:'))
        self.fileDestText = wxStaticText(panel, -1, '')
        destSizer.Add(self.fileDestText, flag = wxEXPAND)
        destSizer.AddGrowableCol(1)
        colSizer.Add(destSizer, flag = wxEXPAND)

        statSizer = wxFlexGridSizer(cols = 3, hgap = 8)

        self.ratesSizer = wxFlexGridSizer(cols = 2)
        self.infoSizer = wxFlexGridSizer(cols = 2)

        self.ratesSizer.Add(wxStaticText(panel, -1, 'Download rate: '))
        self.downRateText = wxStaticText(panel, -1, '   0 kB/s')
        self.ratesSizer.Add(self.downRateText, flag = wxEXPAND)

        self.infoSizer.Add(wxStaticText(panel, -1, 'Downloaded: '))
        self.downText = wxStaticText(panel, -1, '    0.00 MiB')
        self.infoSizer.Add(self.downText, flag = wxEXPAND)

        self.ratesSizer.Add(wxStaticText(panel, -1, 'Upload rate: '))
        self.upRateText = wxStaticText(panel, -1, '   0 kB/s')
        self.ratesSizer.Add(self.upRateText, flag = wxEXPAND)

        self.infoSizer.Add(wxStaticText(panel, -1, 'Uploaded: '))
        self.upText = wxStaticText(panel, -1, '    0.00 MiB')
        self.infoSizer.Add(self.upText, flag = wxEXPAND)

        shareSizer = wxFlexGridSizer(cols = 2, hgap = 8)
        shareSizer.Add(wxStaticText(panel, -1, 'Share rating:'))
        self.shareRatingText = wxStaticText(panel, -1, '')
        shareSizer.AddGrowableCol(1)
        shareSizer.Add(self.shareRatingText, flag = wxEXPAND)

        statSizer.Add(self.ratesSizer)
        statSizer.Add(self.infoSizer)
        statSizer.Add(shareSizer, flag = wxALIGN_CENTER_VERTICAL)
        colSizer.Add (statSizer)

        torrentSizer = wxFlexGridSizer(cols = 1)
        self.peerStatusText = wxStaticText(panel, -1, '')
        torrentSizer.Add(self.peerStatusText, 0, wxEXPAND)
        self.seedStatusText = wxStaticText(panel, -1, '')
        torrentSizer.Add(self.seedStatusText, 0, wxEXPAND)
        torrentSizer.AddGrowableCol(0)
        colSizer.Add(torrentSizer, 0, wxEXPAND)

        self.errorText = wxStaticText(panel, -1, '', style = wxALIGN_LEFT)
        self.errorText.SetForegroundColour('Red')
        colSizer.Add(self.errorText, 0, wxEXPAND)

        self.cancelButton = wxButton(panel, -1, 'Cancel')
        colSizer.Add(self.cancelButton, 0, wxALIGN_CENTER)

        # Setting options

        slideSizer = wxFlexGridSizer(cols = 7, hgap = 0, vgap = 5)

        # dropdown

        slideSizer.Add (wxStaticText(panel, -1, 'Settings for '), 0, wxALIGN_LEFT)
        self.connChoice = wxChoice (panel, -1, (-1, -1), (90, -1), choices = connChoiceList)
        self.connChoice.SetSelection(0)
        slideSizer.Add (self.connChoice, 0, wxALIGN_CENTER)
        slideSizer.Add (wxStaticText(panel, -1, ' Upload rate (kB/s) '), 0, wxALIGN_RIGHT)

        # max upload rate

        self.rateSpinner = wxSpinCtrl (panel, -1, "", (-1,-1), (50, -1))
        self.rateSpinner.SetRange(0,5000)
        self.rateSpinner.SetValue(0)
        slideSizer.Add (self.rateSpinner, 0, wxALIGN_CENTER)

        self.rateLowerText = wxStaticText(panel, -1, '  %5d' % (0))
        self.rateUpperText = wxStaticText(panel, -1, '%5d' % (5000))
        self.rateslider = wxSlider(panel, -1, 0, 0, 5000, (-1, -1), (80, -1))

        slideSizer.Add(self.rateLowerText, 0, wxALIGN_RIGHT)
        slideSizer.Add(self.rateslider,    0, wxALIGN_CENTER)
        slideSizer.Add(self.rateUpperText, 0, wxALIGN_LEFT)

        # Placeholders in Layout


        slideSizer.Add(wxStaticText(panel, -1, ''), 0, wxALIGN_LEFT)
        advText = wxStaticText(panel, -1, 'Advanced', style = wxALIGN_RIGHT)
        advText.SetForegroundColour('Blue')
        advText.SetFont(wxFont(-1, wxDEFAULT, wxNORMAL, wxNORMAL, true))
        slideSizer.Add(advText, 0, wxALIGN_RIGHT)

        # max uploads

        slideSizer.Add(wxStaticText(panel, -1, ' Max uploads '), 0, wxALIGN_RIGHT)
        self.connSpinner = wxSpinCtrl (panel, -1, "", (-1,-1), (50, -1))
        self.connSpinner.SetRange(4,100)
        self.connSpinner.SetValue(4)
        slideSizer.Add (self.connSpinner, 0, wxALIGN_CENTER)

        self.connLowerText = wxStaticText(panel, -1, '  %5d' % (4))
        self.connUpperText = wxStaticText(panel, -1, '%5d' % (100))
        self.connslider = wxSlider(panel, -1, 4, 4, 100, (-1, -1), (80, -1))

        slideSizer.Add(self.connLowerText, 0, wxALIGN_RIGHT)
        slideSizer.Add(self.connslider,    0, wxALIGN_CENTER)
        slideSizer.Add(self.connUpperText, 0, wxALIGN_LEFT)

        colSizer.Add(slideSizer, 1, wxALL|wxALIGN_CENTER|wxEXPAND, 0)

        colSizer.Add(wxStaticText(panel, -1, '0 kB/s means unlimited. Tip: your download rate is proportional to your upload rate'), 0, wxALIGN_CENTER)

        EVT_LEFT_DOWN(aboutText, self.about)
        EVT_LEFT_DOWN(fileDetails, self.details)
        EVT_LEFT_DOWN(advText, self.advanced)
        EVT_CLOSE(frame, self.done)
        EVT_BUTTON(frame, self.cancelButton.GetId(), self.done)
        EVT_INVOKE(frame, self.onInvoke)
        EVT_SCROLL(self.rateslider, self.onRateScroll)
        EVT_SCROLL(self.connslider, self.onConnScroll)
        EVT_CHOICE(self.connChoice, -1, self.onConnChoice)
        EVT_SPINCTRL(self.connSpinner, -1, self.onConnSpinner)
        EVT_SPINCTRL(self.rateSpinner, -1, self.onRateSpinner)
        if (sys.platform == 'win32'):
            EVT_ICONIZE(self.frame, self.onIconify)

        self.frame.Show()
        border.Fit(panel)
        self.frame.Fit()
        self.panel = panel
        self.border = border
        self.addwidth = aboutText.GetBestSize().GetWidth() + fileDetails.GetBestSize().GetWidth() + fnspacer.GetBestSize().GetWidth() + 10
        self.fnsizer = fnsizer
        self.colSizer = colSizer
        minsize = self.colSizer.GetSize()
        minsize.SetWidth (minsize.GetWidth())
        minsize.SetHeight (minsize.GetHeight())
        self.colSizer.SetMinSize (minsize)
        self.colSizer.Fit(self.frame)
        colSizer.Fit(frame)

    def onIconify(self, evt):
        icon = 0
        if self.config is None:
            try:
                self.config = self.dow.getConfig()
                icon = self.config['win32_taskbar_icon']
            except NameError:
                icon = 1
        else:
            icon = self.config['win32_taskbar_icon']
        if (icon):
          if not hasattr(self.frame, "tbicon"):
            self.frame.tbicon = wxTaskBarIcon()
            self.frame.tbicon.SetIcon(self.icon, "BitTorrent")
            # setup a taskbar icon, and catch some events from it
            EVT_TASKBAR_LEFT_DCLICK(self.frame.tbicon, self.onTaskBarActivate)
            EVT_TASKBAR_RIGHT_UP(self.frame.tbicon, self.onTaskBarMenu)
            EVT_MENU(self.frame.tbicon, self.TBMENU_RESTORE, self.onTaskBarActivate)
            EVT_MENU(self.frame.tbicon, self.TBMENU_CLOSE, self.done)
          self.frame.Hide()
        else:
          self.frame.Iconize(1)

    def onTaskBarActivate(self, evt):
        if self.frame.IsIconized():
            self.frame.Iconize(false)
        if not self.frame.IsShown():
            self.frame.Show(true)
        self.frame.Raise()
        if hasattr(self.frame, "tbicon"):
            del self.frame.tbicon
        return

    TBMENU_RESTORE = 1000
    TBMENU_CLOSE   = 1001

    def onTaskBarMenu(self, evt):
        menu = wxMenu()
        menu.Append(self.TBMENU_RESTORE, "Restore BitTorrent")
        menu.Append(self.TBMENU_CLOSE,   "Close")
        self.frame.tbicon.PopupMenu(menu)
        menu.Destroy()

    def onRateScroll(self, event):
      if (self.scrollock == 0):
        self.scrollock = 1
        if self.config is None:
            self.config = self.dow.getConfig()
        newValue = self.rateslider.GetValue()
        if self.connChoice.GetSelection() == 0:
          newValue = self.rateslider.GetValue()
          if newValue != 0:
            newValue /= 50
            newValue *= 50
          if (self.rateslider.GetValue () != newValue):
            self.rateslider.SetValue (newValue)
        self.updateSpinnerFlag = 1
        self.config['max_upload_rate'] = self.rateslider.GetValue() * 1000
        self.dow.setUploadRate ()
        self.scrollock = 0

    def onConnScroll(self, event):
        if self.config is None:
            self.config = self.dow.getConfig()
        self.connSpinner.SetValue (self.connslider.GetValue ())
        self.config['max_uploads'] = self.connslider.GetValue ()
        if (self.connSpinner.GetValue() > 30):
            self.config['max_initiate'] = self.connslider.GetValue () + 10

    def onRateSpinner(self, event):
      if self.config is None:
          self.config = self.dow.getConfig()
      if (self.spinlock == 0):
        self.spinlock = 1
        if self.connChoice.GetSelection() == 0:
          newValue = self.rateSpinner.GetValue ()
          if newValue != 0:
            newValue /= 50
            if self.rateSpinner.GetValue () % 10 != 9:
              newValue += 1
          newValue *= 50
          self.updateSliderFlag = 1
          if (self.rateSpinner.GetValue () != newValue):
            self.rateSpinner.SetValue (newValue)
          self.config['max_upload_rate'] = self.rateSpinner.GetValue () * 1000
          self.dow.setUploadRate ()
        else:
          self.config['max_upload_rate'] = self.rateSpinner.GetValue () * 1000
          self.dow.setUploadRate ()
          self.updateSliderFlag = 1
        self.spinlock = 0

    def onConnSpinner(self, event):
        if self.config is None:
            self.config = self.dow.getConfig()
        self.connslider.SetValue (self.connSpinner.GetValue())
        self.config['max_uploads'] = self.connSpinner.GetValue()
        if (self.connSpinner.GetValue() > 30):
            self.config['max_initiate'] = self.connSpinner.GetValue() + 10

    def onConnChoice(self, event):
        if self.config is None:
            self.config = self.dow.getConfig()
        num = self.connChoice.GetSelection()
        self.rateSpinner.SetValue (connChoices[num]['rate']['def'])
        self.rateSpinner.SetRange (connChoices[num]['rate']['min'],
                               connChoices[num]['rate']['max'])
        self.rateslider.SetRange (
            connChoices[num]['rate']['min']/connChoices[num]['rate'].get('div',1),
            connChoices[num]['rate']['max']/connChoices[num]['rate'].get('div',1))
        self.rateslider.SetValue (
            connChoices[num]['rate']['def']/connChoices[num]['rate'].get('div',1))
        self.rateLowerText.SetLabel ('  %d' % (connChoices[num]['rate']['min']))
        self.rateUpperText.SetLabel ('%d' % (connChoices[num]['rate']['max']))
        self.connSpinner.SetValue (connChoices[num]['conn']['def'])
        self.connSpinner.SetRange (connChoices[num]['conn']['min'],
                                   connChoices[num]['conn']['max'])
        self.connslider.SetRange (connChoices[num]['conn']['min'],
                                  connChoices[num]['conn']['max'])
        self.connslider.SetValue (connChoices[num]['conn']['def'])
        self.connLowerText.SetLabel ('  %d' % (connChoices[num]['conn']['min']))
        self.connUpperText.SetLabel ('%d' % (connChoices[num]['conn']['max']))
        self.onConnScroll (0)
        self.onRateScroll (0)

        self.config['max_initiate'] = connChoices[num].get('initiate', 40)

    def about(self, event):
        if (self.aboutBox is not None):
            try:
                self.aboutBox.Close ()
            except wxPyDeadObjectError, e:
                self.aboutBox = None

        self.aboutBox = wxFrame(None, -1, 'About BitTorrent', size = (1,1))
        if (sys.platform == 'win32'):
            self.aboutBox.SetIcon(self.icon)

        panel = wxPanel(self.aboutBox, -1)
        colSizer = wxFlexGridSizer(cols = 1, vgap = 3)

        titleSizer = wxBoxSizer(wxHORIZONTAL)
        aboutTitle = wxStaticText(panel, -1, 'BitTorrent ' + version)
        aboutTitle.SetFont(wxFont(14, wxDEFAULT, wxNORMAL, wxNORMAL, false))
        titleSizer.Add (aboutTitle)
        linkDonate = wxStaticText(panel, -1, 'Donate to Bram\n(link)', style = wxALIGN_RIGHT)
        linkDonate.SetForegroundColour('Blue');
        linkDonate.SetFont(wxFont(-1, wxDEFAULT, wxNORMAL, wxNORMAL, true))
        titleSizer.Add (linkDonate, 1, wxALIGN_BOTTOM&wxEXPAND)
        colSizer.Add(titleSizer, 0, wxEXPAND)

        colSizer.Add(wxStaticText(panel, -1, 'created by Bram Cohen, Copyright 2001-2003,'))
        colSizer.Add(wxStaticText(panel, -1, 'experimental tree maintained by Eike Frost 2003'))
        credits = wxStaticText(panel, -1, 'full credits\n')
        credits.SetForegroundColour('Blue');
        credits.SetFont(wxFont(-1, wxDEFAULT, wxNORMAL, wxNORMAL, true))
        colSizer.Add(credits);

        systemInformation = wxStaticText(panel, -1,
          'exact Version String: ' + version + '\n'+
          'Python version: ' + sys.version + '\n')
        colSizer.Add(systemInformation)

        babble1 = wxStaticText(panel, -1,
         'This is an experimental, unofficial build of BitTorrent.\n' +
         'It is Free Software under an MIT-Style license.')
        babble2 = wxStaticText(panel, -1,'BitTorrent Homepage (link)')
        babble2.SetForegroundColour('Blue');
        babble2.SetFont(wxFont(-1, wxDEFAULT, wxNORMAL, wxNORMAL, true))
        babble4 = wxStaticText(panel, -1,'Experimental Client Homepage (link)')
        babble4.SetForegroundColour('Blue');
        babble4.SetFont(wxFont(-1, wxDEFAULT, wxNORMAL, wxNORMAL, true))
        babble6 = wxStaticText(panel, -1, 'License Terms (link)')
        babble6.SetForegroundColour('Blue');
        babble6.SetFont(wxFont(-1, wxDEFAULT, wxNORMAL, wxNORMAL, true))
        colSizer.Add (babble1)
        colSizer.Add (babble2)
        colSizer.Add (babble4)
        colSizer.Add (babble6)

        okButton = wxButton(panel, -1, 'Ok')
        colSizer.Add(okButton, 0, wxALIGN_RIGHT)
        colSizer.AddGrowableCol(0)

        border = wxBoxSizer(wxHORIZONTAL)
        border.Add(colSizer, 1, wxEXPAND | wxALL, 4)
        panel.SetSizer(border)
        panel.SetAutoLayout(true)

        def donatelink(self):
            Thread(target = open_new('https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=bram@bitconjurer.org&item_name=BitTorrent&amount=5.00&submit=donate')).start()
        EVT_LEFT_DOWN(linkDonate, donatelink)
        def aboutlink(self):
            Thread(target = open_new('http://bitconjurer.org/BitTorrent/')).start()
        EVT_LEFT_DOWN(babble2, aboutlink)
        def explink(self):
            Thread(target = open_new('http://ei.kefro.st/projects/btclient/')).start()
        EVT_LEFT_DOWN(babble4, explink)
        def licenselink(self):
            Thread(target = open_new('http://ei.kefro.st/projects/btclient/LICENSE.TXT')).start()
        EVT_LEFT_DOWN(babble6, licenselink)
        EVT_LEFT_DOWN(credits, self.credits)

        def closeAbout(self, frame = self):
            frame.aboutBox.Close ()
        EVT_BUTTON(self.aboutBox, okButton.GetId(), closeAbout)

        self.aboutBox.Show ()
        border.Fit(panel)
        self.aboutBox.Fit()

    def details(self, event):
        metainfo = self.dow.getResponse()
        announce = metainfo['announce']
        info = metainfo['info']
        info_hash = sha(bencode(info))
        piece_length = info['piece length']

        if (self.detailBox is not None):
            try:
                self.detailBox.Close ()
            except wxPyDeadObjectError, e:
                self.detailBox = None

        self.detailBox = wxFrame(None, -1, 'Torrent Details ', size = wxSize(405,230))
        if (sys.platform == 'win32'):
            self.detailBox.SetIcon(self.icon)

        panel = wxPanel(self.detailBox, -1, size = wxSize (400,220))
        colSizer = wxFlexGridSizer(cols = 1, vgap = 3)

        titleSizer = wxBoxSizer(wxHORIZONTAL)
        aboutTitle = wxStaticText(panel, -1, 'Details about ' + self.filename)
        aboutTitle.SetFont(wxFont(14, wxDEFAULT, wxNORMAL, wxNORMAL, false))
        titleSizer.Add (aboutTitle)
        colSizer.Add (titleSizer)

        detailSizer = wxFlexGridSizer(cols = 2, vgap = 3)
        detailSizer.AddGrowableCol(1)
        colSizer.Add (detailSizer)

        if info.has_key('length'):
            detailSizer.Add(wxStaticText(panel, -1, 'file name :'))
            detailSizer.Add(wxStaticText(panel, -1, info['name']))
            file_length = info['length']
            name = "file size";
        else:
            detailSizer.Add(wxStaticText(panel, -1, 'directory name :'))
            detailSizer.Add(wxStaticText(panel, -1, info['name']))
            detailSizer.Add(wxStaticText(panel, -1, 'files :'))
            file_length = 0;
            for file in info['files']:
                path = ''
                for item in file['path']:
                    if (path != ''):
                        path = path + "/"
                    path = path + item
                detailSizer.Add(wxStaticText(panel, -1, '%s (%d)' % (path, file['length'])))
                detailSizer.Add(wxStaticText(panel, -1, ''))
                file_length += file['length']
            name = 'archive size'
            detailSizer.Add(wxStaticText(panel, -1, ''))

        detailSizer.Add(wxStaticText(panel, -1, 'info_hash :'))
        detailSizer.Add(wxTextCtrl(panel, -1, info_hash.hexdigest(), size = (300, -1), style = wxTE_READONLY))
        piece_number, last_piece_length = divmod(file_length, piece_length)
        detailSizer.Add(wxStaticText(panel, -1, name + ' : '))
        detailSizer.Add(wxStaticText(panel, -1, '%i (%i * %i + %i)' % (file_length, piece_number, piece_length, last_piece_length)))
        detailSizer.Add(wxStaticText(panel, -1, 'announce url : '))
        detailSizer.Add(wxTextCtrl(panel, -1, announce, size = (300, -1), style = wxTE_READONLY))
        detailSizer.Add(wxStaticText(panel, -1, 'likely tracker :'))
        p = re.compile( '(.*/)[^/]+')
        turl = p.sub (r'\1', announce)
        trackerUrl = wxStaticText(panel, -1, turl)
        trackerUrl.SetForegroundColour('Blue');
        trackerUrl.SetFont(wxFont(-1, wxDEFAULT, wxNORMAL, wxNORMAL, true))
        detailSizer.Add(trackerUrl)
        if info.has_key('comment'):
            detailSizer.Add(wxStaticText(panel, -1, 'comment :'))
            detailSizer.Add(wxStaticText(panel, -1, info['comment']))
        if info.has_key('creation date'):
            detailSizer.Add(wxStaticText(panel, -1, 'creation date :'))
            detailSizer.Add(wxStaticText(panel, -1, info['creation date']))

        okButton = wxButton(panel, -1, 'Ok')
        colSizer.Add(okButton, 0, wxALIGN_RIGHT)
        colSizer.AddGrowableCol(0)

        border = wxBoxSizer(wxHORIZONTAL)
        border.Add(colSizer, 1, wxEXPAND | wxALL, 4)
        panel.SetSizer(border)
        panel.SetAutoLayout(true)

        def closeDetail(self, frame = self):
            frame.detailBox.Close ()
        EVT_BUTTON(self.detailBox, okButton.GetId(), closeDetail)

        def trackerurl(self, turl = turl):
            Thread(target = open_new(turl)).start()

        EVT_LEFT_DOWN(trackerUrl, trackerurl)

        self.detailBox.Show ()
        border.Fit(panel)
        self.detailBox.Fit()

    def credits(self, event):
        if (self.creditsBox is not None):
            try:
                self.creditsBox.Close ()
            except wxPyDeadObjectError, e:
                self.creditsBox = None

        self.creditsBox = wxFrame(None, -1, 'Credits', size = (1,1))
        if (sys.platform == 'win32'):
            self.creditsBox.SetIcon(self.icon)

        panel = wxPanel(self.creditsBox, -1)
        colSizer = wxFlexGridSizer(cols = 1, vgap = 3)

        titleSizer = wxBoxSizer(wxHORIZONTAL)
        aboutTitle = wxStaticText(panel, -1, 'Credits')
        aboutTitle.SetFont(wxFont(14, wxDEFAULT, wxNORMAL, wxNORMAL, false))
        titleSizer.Add (aboutTitle)
        colSizer.Add (titleSizer)
        colSizer.Add (wxStaticText(panel, -1,
          'The following people have all helped with this\n' +
          'version of BitTorrent in some way (in no particular order) -\n'));
        creditSizer = wxFlexGridSizer(cols = 3)
        creditSizer.Add(wxStaticText(panel, -1,
          'Bill Bumgarner\n' +
          'David Creswick\n' +
          'Andrew Loewenstern\n' +
          'Ross Cohen\n' +
          'Jeremy Avnet\n' +
          'Greg Broiles\n' +
          'Barry Cohen\n' +
          'Bram Cohen\n' +
          'sayke\n' +
          'Steve Jenson\n' +
          'Myers Carpenter\n' +
          'Francis Crick\n' +
          'Petru Paler\n' +
          'Jeff Darcy\n' +
          'John Gilmore\n'))
        creditSizer.Add(wxStaticText(panel, -1, '  '))
        creditSizer.Add(wxStaticText(panel, -1,
          'Yann Vernier\n' +
          'Pat Mahoney\n' +
          'Boris Zbarsky\n' +
          'Eric Tiedemann\n' +
          'Henry "Pi" James\n' +
          'Loring Holden\n' +
          'Robert Stone\n' +
          'Michael Janssen\n' +
          'Eike Frost\n' +
          'Andrew Todd\n' +
          'otaku\n' +
          'Edward Keyes\n' +
          'John Hoffman\n'))
        colSizer.Add (creditSizer, flag = wxALIGN_CENTER_HORIZONTAL)
        okButton = wxButton(panel, -1, 'Ok')
        colSizer.Add(okButton, 0, wxALIGN_RIGHT)
        colSizer.AddGrowableCol(0)

        border = wxBoxSizer(wxHORIZONTAL)
        border.Add(colSizer, 1, wxEXPAND | wxALL, 4)
        panel.SetSizer(border)
        panel.SetAutoLayout(true)

        def closeCredits(self, frame = self):
            frame.creditsBox.Close ()
        EVT_BUTTON(self.creditsBox, okButton.GetId(), closeCredits)

        self.creditsBox.Show ()
        border.Fit(panel)
        self.creditsBox.Fit()

    def advanced(self, event):
        if (self.advBox is not None):
            try:
                self.advBox.Close ()
            except wxPyDeadObjectError, e:
                self.advBox = None

        self.advBox = wxFrame(None, -1, 'Torrent Advanced', size = wxSize(200,200))
        if (sys.platform == 'win32'):
            self.advBox.SetIcon(self.icon)

        panel = wxPanel(self.advBox, -1, size = wxSize (200,200))

        colSizer = wxBoxSizer (wxVERTICAL)
        title = wxStaticText(panel, -1, 'Advanced')
        title.SetFont(wxFont(14, wxDEFAULT, wxNORMAL, wxNORMAL, false))

        colSizer.Add (title)
        colSizer.Add (wxStaticText(panel, -1, 'Advanced Info for ' + self.filename))
        spewList = wxListCtrl(panel, -1, wxPoint(-1,-1), (578,400), wxLC_REPORT|wxLC_HRULES|wxLC_VRULES)
        spewList.SetAutoLayout (true)

        colSizer.Add(spewList, -1, wxEXPAND)

        buttonSizer = wxBoxSizer (wxHORIZONTAL)

        reannounceButton = wxButton(panel, -1, 'Initiate Manual Announce')
        buttonSizer.Add (reannounceButton)

        okButton = wxButton(panel, -1, 'Ok')
        buttonSizer.Add (okButton, -1, wxALIGN_RIGHT)

        colSizer.Add (buttonSizer)
        colSizer.SetMinSize ((578,400))

        panel.SetSizer(colSizer)
        panel.SetAutoLayout(true)

        self.spewList = spewList
        spewList.InsertColumn(0, "optimistic unchoke")
        spewList.InsertColumn(1, "IP")
        spewList.InsertColumn(2, "local/remote")
        spewList.InsertColumn(3, "Up")
        spewList.InsertColumn(4, "Interested")
        spewList.InsertColumn(5, "Choking")
        spewList.InsertColumn(6, "Down")
        spewList.InsertColumn(7, "Interesting")
        spewList.InsertColumn(8, "Choked")
        spewList.InsertColumn(9, "Snubbed")
        spewList.InsertColumn(10, "Downloaded")
        spewList.InsertColumn(11, "Uploaded")
        spewList.InsertColumn(12, "Completed")
        spewList.InsertColumn(13, "Peer Download Speed")

        spewList.SetColumnWidth(0, 18)
        spewList.SetColumnWidth(1, 100)
        spewList.SetColumnWidth(2, 18)
        spewList.SetColumnWidth(3, 55)
        spewList.SetColumnWidth(4, 18)
        spewList.SetColumnWidth(5, 18)
        spewList.SetColumnWidth(6, 55)
        spewList.SetColumnWidth(7, 18)
        spewList.SetColumnWidth(8, 18)
        spewList.SetColumnWidth(9, 18)
        spewList.SetColumnWidth(10, 65)
        spewList.SetColumnWidth(11, 65)
        spewList.SetColumnWidth(12, 55)
        spewList.SetColumnWidth(13, 55)

        def closeAdv(self, frame = self):
            frame.advBox.Close ()
        def killAdv(self, frame = self):
            frame.advBox.Destroy()
            frame.advBox = None
        EVT_BUTTON(self.advBox, okButton.GetId(), closeAdv)
        EVT_CLOSE(self.advBox, killAdv)

        def reannounce(self, frame = self):
            if (time () - frame.reannouncelast > 60):
                frame.reannouncelast = time ()
                frame.dow.reannounce()
        EVT_BUTTON(self.advBox, reannounceButton.GetId(), reannounce)

        self.advBox.Show ()
        colSizer.Fit(panel)
        self.advBox.Fit()

    def onInvoke(self, event):
        if not self.flag.isSet():
            apply(event.func, event.args, event.kwargs)

    def invokeLater(self, func, args = [], kwargs = {}):
        if not self.flag.isSet():
            wxPostEvent(self.frame, InvokeEvent(func, args, kwargs))

    def updateStatus(self, fractionDone = None,
            timeEst = None, downRate = None, upRate = None,
            activity = None, statistics = None, spew = None, sizeDone = None,
            **kws):
        self.invokeLater(self.onUpdateStatus, [fractionDone, timeEst, downRate, upRate, activity, statistics, spew, sizeDone])

    def onUpdateStatus(self, fractionDone, timeEst, downRate, upRate, activity, statistics, spew, sizeDone):
        if self.updateSliderFlag == 1:
          self.updateSliderFlag = 0
          self.rateslider.SetValue (self.rateSpinner.GetValue())
        if self.updateSpinnerFlag == 1:
          self.updateSpinnerFlag = 0
          self.rateSpinner.SetValue (self.rateslider.GetValue())
        if self.fin:
            if statistics is not None:
                if statistics.numOldSeeds > 0 or statistics.numCopies > 1:
                    self.gauge.SetValue(1000)
                else:
                    self.gauge.SetValue(int(1000*statistics.numCopies))
        elif fractionDone is not None:
            gaugelevel = int(fractionDone * 1000)
            self.gauge.SetValue(gaugelevel)
            if statistics is not None and statistics.downTotal is not None:
                self.frame.SetTitle('%.1f%% (%.2f MiB) %s - BitTorrent %s' % (float(gaugelevel)/10, float(sizeDone) / (1<<20), self.filename, version))
                self.gauge.SetForegroundColour(wx.wxSystemSettings_GetColour(wxSYS_COLOUR_ACTIVECAPTION))
            else:
                self.frame.SetTitle('%.0f%% %s - BitTorrent %s' % (float(gaugelevel)/10, self.filename, version))
        if timeEst is not None:
            self.timeText.SetLabel(hours(time () - self.starttime) + ' / ' + hours(timeEst))
            self.gauge.SetForegroundColour(wx.wxSystemSettings_GetColour(wxSYS_COLOUR_ACTIVECAPTION))
        if activity is not None and not self.fin:
            self.timeText.SetLabel(hours(time () - self.starttime) + ' / ' + activity)
        if downRate is not None:
            self.downRateText.SetLabel('%.0f kB/s' % (float(downRate) / 1000))
        if upRate is not None:
            self.upRateText.SetLabel('%.0f kB/s' % (float(upRate) / 1000))
        if hasattr(self.frame, "tbicon"):
            icontext='BitTorrent '
            if fractionDone is not None and not self.fin:
                icontext=icontext+' %.1f%% (%.2f MiB)' % (fractionDone*100, float(sizeDone) / (1<<20))
            if upRate is not None:
                icontext=icontext+' u:%.0f kB/s' % (float(upRate) / 1000)
            if downRate is not None:
                icontext=icontext+' d:%.0f kB/s' % (float(downRate) / 1000)
            icontext+=' %s' % self.filename
            self.frame.tbicon.SetIcon(self.icon,icontext)
        if statistics is not None:
            self.downText.SetLabel('%.2f MiB' % (float(statistics.downTotal) / (1 << 20)))
            self.upText.SetLabel('%.2f MiB' % (float(statistics.upTotal) / (1 << 20)))
            if (statistics.shareRating < 0) or (statistics.shareRating > 1000):
                self.shareRatingText.SetLabel('oo :-D')
                self.shareRatingText.SetForegroundColour('Forest Green')
            else:
                shareSmiley = ''
                color = 'Black'
                if ((statistics.shareRating >= 0) and (statistics.shareRating < 0.5)):
                    shareSmiley = ':-('
                    color = 'Red'
                else:
                    if ((statistics.shareRating >= 0.5) and (statistics.shareRating < 1.0)):
                        shareSmiley = ':-|'
                        color = 'Orange'
                    else:
                        if (statistics.shareRating >= 1.0):
                            shareSmiley = ':-)'
                            color = 'Forest Green'
                self.shareRatingText.SetLabel('%.3f %s' % (statistics.shareRating, shareSmiley))
                self.shareRatingText.SetForegroundColour(color)

            if not self.fin:
               self.seedStatusText.SetLabel('connected to %d seeds; also seeing %.3f distributed copies' % (statistics.numSeeds,0.001*int(1000*statistics.numCopies)))
            else:
               self.seedStatusText.SetLabel('%d seeds seen recently; also seeing %.3f distributed copies' % (statistics.numOldSeeds,0.001*int(1000*statistics.numCopies)))
            self.peerStatusText.SetLabel('connected to %d peers with an average of %.1f%% completed (total speed %.0f kB/s)' % (statistics.numPeers,statistics.percentDone,float(statistics.torrentRate) / (1000)))
        if ((time () - self.lastError) > 300):
            self.errorText.SetLabel('')
        if spew is not None and (time()-self.spewwait>1):
            if (self.advBox is not None):
               self.spewwait = time()
               spewList = self.spewList
               if (spewList.GetItemCount()-len(spew)) < 0:
                 for x in range(len(spew)-spewList.GetItemCount()):
                   spewList.InsertStringItem(x,'')
               if (spewList.GetItemCount()-len(spew)) > 0:
                 for x in range(spewList.GetItemCount()-len(spew)):
                   spewList.SetStringItem((len(spew))+x, 0, '')
                   spewList.SetStringItem((len(spew))+x, 1, '')
                   spewList.SetStringItem((len(spew))+x, 2, '')
                   spewList.SetStringItem((len(spew))+x, 3, '')
                   spewList.SetStringItem((len(spew))+x, 4, '')
                   spewList.SetStringItem((len(spew))+x, 5, '')
                   spewList.SetStringItem((len(spew))+x, 6, '')
                   spewList.SetStringItem((len(spew))+x, 7, '')
                   spewList.SetStringItem((len(spew))+x, 8, '')
                   spewList.SetStringItem((len(spew))+x, 9, '')
                   spewList.SetStringItem((len(spew))+x, 10, '')
                   spewList.SetStringItem((len(spew))+x, 11, '')
                   spewList.SetStringItem((len(spew))+x, 12, '')
                   spewList.SetStringItem((len(spew))+x, 13, '')

               for x in range(len(spew)):
                   if (spew[x]['optimistic'] == 1):
                       a = '*'
                   else:
                       a = ' '
                   spewList.SetStringItem(x, 0, a)
                   spewList.SetStringItem(x, 1, spew[x]['ip'])
                   spewList.SetStringItem(x, 2, spew[x]['direction'])
                   if spew[x]['uprate'] > 100:
                       spewList.SetStringItem(x, 3, '%.0f kB/s' % (float(spew[x]['uprate']) / 1000))
                   else:
                       spewList.SetStringItem(x, 3, '')
                   if (spew[x]['uinterested'] == 1):
                       a = '*'
                   else:
                       a = ' '
                   spewList.SetStringItem(x, 4, a)
                   if (spew[x]['uchoked'] == 1):
                       a = '*'
                   else:
                       a = ' '
                   spewList.SetStringItem(x, 5, a)
                   spewList.SetStringItem(x, 6, '%.0f kB/s' % (float(spew[x]['downrate']) / 1000))
                   if (spew[x]['dinterested'] == 1):
                       a = '*'
                   else:
                       a = ' '
                   spewList.SetStringItem(x, 7, a)
                   if (spew[x]['dchoked'] == 1):
                       a = '*'
                   else:
                       a = ' '
                   spewList.SetStringItem(x, 8, a)
                   if (spew[x]['snubbed'] == 1):
                       a = '*'
                   else:
                       a = ' '
                   spewList.SetStringItem(x, 9, a)
                   spewList.SetStringItem(x, 10, '%.2f MiB' % (float(spew[x]['dtotal']) / (1 << 20)))
                   spewList.SetStringItem(x, 11, '%.2f MiB' % (float(spew[x]['utotal']) / (1 << 20)))
                   spewList.SetStringItem(x, 12, '%.1f%%' % (float(int(spew[x]['completed']*1000)/10)))
                   spewList.SetStringItem(x, 13, '%.0f kB/s' % (float(spew[x]['speed']) / 1000))

    def finished(self):
        self.fin = true
        self.invokeLater(self.onFinishEvent)

    def failed(self):
        self.fin = true
        self.invokeLater(self.onFailEvent)

    def error(self, errormsg):
        self.invokeLater(self.onErrorEvent, [errormsg])

    def onFinishEvent(self):
        self.timeText.SetLabel(hours(time () - self.starttime) + ' / ' +'Download Succeeded!')
        self.cancelButton.SetLabel('Finish')
        self.gauge.SetBackgroundColour(wx.wxSystemSettings_GetColour(wxSYS_COLOUR_ACTIVECAPTION))
        self.gauge.SetValue(0)
        self.gauge.SetForegroundColour('Steel Blue')
        self.frame.SetTitle('%s - Upload - BitTorrent %s' % (self.filename, version))
        if (sys.platform == 'win32'):
            self.icon = wxIcon('icon_done.ico', wxBITMAP_TYPE_ICO)
            self.frame.SetIcon(self.icon)
        if hasattr(self.frame, "tbicon"):
                self.frame.tbicon.SetIcon(self.icon, "BitTorrent - Finished")
        self.downRateText.SetLabel('')

    def onFailEvent(self):
        self.timeText.SetLabel(hours(time () - self.starttime) + ' / ' +'Failed!')
        self.cancelButton.SetLabel('Close')
        self.gauge.SetValue(0)
        self.downRateText.SetLabel('')

    def onErrorEvent(self, errormsg):
        self.errorText.SetLabel(strftime('ERROR (%I:%M %p) -\n') + errormsg)
        self.lastError = time ()

    def chooseFile(self, default, size, saveas, dir):
        f = Event()
        bucket = [None]
        self.invokeLater(self.onChooseFile, [default, bucket, f, size, dir, saveas])
        f.wait()
        return bucket[0]
    
    def onChooseFile(self, default, bucket, f, size, dir, saveas):
        dl = None
        if saveas != '':
            dl = saveas
        else:
            if dir:
                dl = wxDirDialog(self.frame, 'Choose a directory to save to, pick a partial download to resume',
                     join(getcwd(), default), style = wxDD_DEFAULT_STYLE | wxDD_NEW_DIR_BUTTON)
            else:
                dl = wxFileDialog(self.frame, 'Choose file to save as, pick a partial download to resume', '', default, '*.*', wxSAVE)

        if ((saveas == '') and (dl.ShowModal() != wxID_OK)):
            f.set()
            self.done(None)
        else:
            if saveas != '':
                bucket[0] = dl
                default = saveas
            else:
                bucket[0] = dl.GetPath()
            self.fileNameText.SetLabel('%s (%.2f MiB)' % (default, float(size) / (1 << 20)))
            self.timeText.SetLabel(hours(time () - self.starttime) + ' / ' + 'Starting up...')
            self.fileDestText.SetLabel(default)
            # Kludge to make details and about catch the event
            self.frame.SetSize ((self.frame.GetSizeTuple()[0]+1, self.frame.GetSizeTuple()[1]+1))
            self.frame.SetSize ((self.frame.GetSizeTuple()[0]-1, self.frame.GetSizeTuple()[1]-1))
            self.filename = default
            self.frame.SetTitle(default + '- BitTorrent ' + version)
            f.set()
            minsize = self.fileNameText.GetBestSize()
            minsize.SetWidth (minsize.GetWidth() + self.addwidth)
            self.fnsizer.SetMinSize (minsize)
            self.colSizer.Fit(self.frame)

    def newpath(self, path):
        self.fileDestText.SetLabel(path)

    def done(self, event):
        if hasattr(self.frame, "tbicon"):
            self.frame.tbicon.Destroy()
            del self.frame.tbicon
        self.flag.set()
        if (self.detailBox is not None):
            try:
                self.detailBox.Close ()
            except wxPyDeadObjectError, e:
                self.detailBox = None
        if (self.aboutBox is not None):
            try:
                self.aboutBox.Close ()
            except wxPyDeadObjectError, e:
                self.aboutBox = None
        if (self.creditsBox is not None):
            try:
                self.creditsBox.Close ()
            except wxPyDeadObjectError, e:
                self.creditsBox = None
        if (self.advBox is not None):
            try:
                self.advBox.Close ()
            except wxPyDeadObjectError, e:
                self.advBox = None
        self.frame.Destroy()


class btWxApp(wxApp):
    def __init__(self, x, params):
        self.params = params
        wxApp.__init__(self, x)

    def OnInit(self):
        doneflag = Event()
        d = DownloadInfoFrame(doneflag)
        self.SetTopWindow(d.frame)
        if len(self.params) == 0:
            b = wxFileDialog (d.frame, 'Choose .torrent file to use', '', '', '*.torrent', wxOPEN)
            if b.ShowModal() != wxID_OK:
                d.done(None)
                return 0
            else:
                self.params.append (b.GetPath())

        thread = Thread(target = next, args = [self.params, d, doneflag])
        thread.setDaemon(false)
        thread.start()
        return 1

def run(params):
    app = btWxApp(0, params)
    app.MainLoop()

def next(params, d, doneflag):
    dow = Download ()
    d.dow = dow
    dow.download(params, d.chooseFile, d.updateStatus, d.finished, d.error, doneflag, 100, d.newpath)
    if not d.fin:
        d.failed()

if __name__ == '__main__':
    run(argv[1:])
habe mit suchen gesucht wo dow noch steckth habe es leider nicht gefunden in dem experimental source!

Edit (Leonidas): Code in Python-Tags gesetzt.
Gast

Samstag 22. Oktober 2005, 13:28

Hallo!
Anonymous hat geschrieben:habe mit suchen gesucht wo dow noch steckth habe es leider nicht gefunden in dem experimental source!

Code: Alles auswählen

def next(params, d, doneflag): 
    dow = Download () 
    d.dow = dow 
Da wird dow als member von d erzeugt und d ist vom typ DownloadInfoFrame und DownloadInfoFrame braucht dow. Alles innerhalb einer minute herauszubekommen. Ums aneignen rudimentärer python-kenntnisse kommst du nicht rum.
joe

Edit (Leonidas): Code in Python-Tags gesetzt.
matrixnet
User
Beiträge: 35
Registriert: Donnerstag 21. April 2005, 16:45

Samstag 22. Oktober 2005, 14:12

danke das hatte ich übersehen!
habe nun diese fehler:
aber mein client läuft jetzt nicht mehr richtig!

Exception in thread Thread-1:Traceback (most recent call last):
File "threading.pyc", line 442, in __bootstrap
File "threading.pyc", line 422, in run
File "btdownloadgui.py", line 381, in next
NameError: global name 'Download' is not defined
Traceback (most recent call last):
File "btdownloadgui.py", line 156, in onIconify
AttributeError: DownloadInfoFrame instance has no attribute 'dow'

das dow geht immer noch nicht richtig!

Code: Alles auswählen

#!/usr/bin/env python

# Written by Bram Cohen and Myers Carpenter
# see LICENSE.txt for license information

from sys import argv
from BitTorrent import version
from BitTorrent.download import download
from btdownloadheadless import print_spew
from threading import Event, Thread
from os.path import join, split, exists
from os import getcwd
from wxPython.wx import *
from time import strftime, time
from webbrowser import open_new
from traceback import print_exc
import sys

def hours(n):
    if n == -1:
        return '<unknown>'
    if n == 0:
        return 'complete!'
    n = int(n)
    h, r = divmod(n, 60 * 60)
    m, sec = divmod(r, 60)
    if h > 1000000:
        return '<unknown>'
    if h > 0:
        return '%d hour %02d min %02d sec' % (h, m, sec)
    else:
        return '%d min %02d sec' % (m, sec)

wxEVT_INVOKE = wxNewEventType()

def EVT_INVOKE(win, func):
    win.Connect(-1, -1, wxEVT_INVOKE, func)

class InvokeEvent(wxPyEvent):
    def __init__(self):
        wxPyEvent.__init__(self)
        self.SetEventType(wxEVT_INVOKE)

class DownloadInfoFrame:
    def __init__(self, flag):
        frame = wxFrame(None, -1, 'I2P-BT ' + version + ' download', size = wxSize(400, 250))
        self.frame = frame
        self.flag = flag
        self.uiflag = Event()
        self.fin = False
        self.last_update_time = 0
        self.showing_error = False
        self.event = InvokeEvent()
        self.funclist = []
        self.config = None

        if (sys.platform == 'win32'):
            self.icon = wxIcon('bittorrent.ico', wxBITMAP_TYPE_ICO)
        self.starttime = time ()

        self.frame = frame
        if (sys.platform == 'win32'):
            self.frame.SetIcon(self.icon)

        panel = wxPanel(frame, -1)
        colSizer = wxFlexGridSizer(cols = 1, vgap = 3)

        fnsizer = wxBoxSizer(wxHORIZONTAL)

        self.fileNameText = wxStaticText(panel, -1, '', style = wxALIGN_LEFT)
        fnsizer.Add(self.fileNameText, 1, wxALIGN_BOTTOM)
#I2P: cant have this for anonymity reasons
#       self.aboutText = wxStaticText(panel, -1, 'about', style = wxALIGN_RIGHT)
#       self.aboutText.SetForegroundColour('Blue')
#       self.aboutText.SetFont(wxFont(14, wxNORMAL, wxNORMAL, wxNORMAL, True))
#       fnsizer.Add(self.aboutText, 0, wxEXPAND)
#/I2P
        colSizer.Add(fnsizer, 0, wxEXPAND)

        self.gauge = wxGauge(panel, -1, range = 1000, style = wxGA_SMOOTH)
        colSizer.Add(self.gauge, 0, wxEXPAND)

        gridSizer = wxFlexGridSizer(cols = 2, vgap = 3, hgap = 8)
        
        gridSizer.Add(wxStaticText(panel, -1, 'Estimated time left:'))
        self.timeEstText = wxStaticText(panel, -1, '')
        gridSizer.Add(self.timeEstText, 0, wxEXPAND)

        gridSizer.Add(wxStaticText(panel, -1, 'Download to:'))
        self.fileDestText = wxStaticText(panel, -1, '')
        gridSizer.Add(self.fileDestText, 0, wxEXPAND)
        
        gridSizer.AddGrowableCol(1)

        rategridSizer = wxFlexGridSizer(cols = 4, vgap = 3, hgap = 8)

        rategridSizer.Add(wxStaticText(panel, -1, 'Download rate:'))
        self.downRateText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.downRateText, 0, wxEXPAND)

        rategridSizer.Add(wxStaticText(panel, -1, 'Downloaded:'))
        self.downTotalText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.downTotalText, 0, wxEXPAND)
        
        rategridSizer.Add(wxStaticText(panel, -1, 'Upload rate:'))
        self.upRateText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.upRateText, 0, wxEXPAND)
        
        
        rategridSizer.Add(wxStaticText(panel, -1, 'Uploaded:'))
        self.upTotalText = wxStaticText(panel, -1, '')
        rategridSizer.Add(self.upTotalText, 0, wxEXPAND)
       
        rategridSizer.AddGrowableCol(1)
        rategridSizer.AddGrowableCol(3)

        
        colSizer.Add(gridSizer, 0, wxEXPAND)
        colSizer.Add(rategridSizer, 0, wxEXPAND)
#I2P: wxPython 2.5 fix        
        colSizer.Add((50, 50), 0, wxEXPAND)
#/I2P
        self.cancelButton = wxButton(panel, -1, 'Cancel')
        colSizer.Add(self.cancelButton, 0, wxALIGN_CENTER)
        colSizer.AddGrowableCol(0)
        colSizer.AddGrowableRow(3)

        border = wxBoxSizer(wxHORIZONTAL)
        border.Add(colSizer, 1, wxEXPAND | wxALL, 4)
        panel.SetSizer(border)
        panel.SetAutoLayout(True)
        
#I2P: we cant have this for anonymity reasons
#       EVT_LEFT_DOWN(self.aboutText, self.donate)
#/I2P
        EVT_CLOSE(frame, self.done)
        EVT_BUTTON(frame, self.cancelButton.GetId(), self.done)
        EVT_INVOKE(frame, self.onInvoke)
        if (sys.platform == 'win32'):
            EVT_ICONIZE(self.frame, self.onIconify)
        self.frame.SetIcon(wxIcon(join(split(argv[0])[0], 'bittorrent.ico'), wxBITMAP_TYPE_ICO))
        self.frame.Show()

#I2P: we cant have this for anonymity reasons
#   def donate(self, event):
#       Thread(target = self.donate2).start()
#
#   def donate2(self):
#       open_new('http://bitconjurer.org/BitTorrent/donate.html')
#/I2P

    def onIconify(self, evt):
        icon = 0
        if self.config is None:
            try:
                self.config = self.dow.getConfig()
                icon = self.config['win32_taskbar_icon']
            except NameError:
                icon = 1
        else:
            icon = self.config['win32_taskbar_icon']
        if (icon):
          if not hasattr(self.frame, "tbicon"):
            self.frame.tbicon = wxTaskBarIcon()
            self.frame.tbicon.SetIcon(self.icon, "BitTorrent")
            # setup a taskbar icon, and catch some events from it
            EVT_TASKBAR_LEFT_DCLICK(self.frame.tbicon, self.onTaskBarActivate)
            EVT_TASKBAR_RIGHT_UP(self.frame.tbicon, self.onTaskBarMenu)
            EVT_MENU(self.frame.tbicon, self.TBMENU_RESTORE, self.onTaskBarActivate)
            EVT_MENU(self.frame.tbicon, self.TBMENU_CLOSE, self.done)
          self.frame.Hide()
        else:
          self.frame.Iconize(1)

    def onTaskBarActivate(self, evt):
        if self.frame.IsIconized():
            self.frame.Iconize(false)
        if not self.frame.IsShown():
            self.frame.Show(true)
        self.frame.Raise()
        if hasattr(self.frame, "tbicon"):
            del self.frame.tbicon
        return

    TBMENU_RESTORE = 1000
    TBMENU_CLOSE   = 1001

    def onTaskBarMenu(self, evt):
        menu = wxMenu()
        menu.Append(self.TBMENU_RESTORE, "Restore BitTorrent")
        menu.Append(self.TBMENU_CLOSE,   "Close")
        self.frame.tbicon.PopupMenu(menu)
        menu.Destroy()


    def onInvoke(self, event):
        while not self.uiflag.isSet() and self.funclist:
            func, args, kwargs = self.funclist.pop(0)
            apply(func, args, kwargs)

    def invokeLater(self, func, args = [], kwargs = {}):
        if not self.uiflag.isSet():
            self.funclist.append((func, args, kwargs))
            if len(self.funclist) == 1:
                wxPostEvent(self.frame, self.event)

    def updateStatus(self, d):
        if (self.last_update_time + 0.1 < time() and not self.showing_error) or d.get('fractionDone') in (0.0, 1.0) or d.has_key('activity'):
            self.invokeLater(self.onUpdateStatus, [d])

    def onUpdateStatus(self, d):
        try:
            if d.has_key('spew'):
                print_spew(d['spew'])
            activity = d.get('activity')
            fractionDone = d.get('fractionDone')
            timeEst = d.get('timeEst')
            downRate = d.get('downRate')
            upRate = d.get('upRate')
            downTotal = d.get('downTotal')
            upTotal = d.get('upTotal')
            if activity is not None and not self.fin:
                self.timeEstText.SetLabel(activity)
            if fractionDone is not None and not self.fin:
                self.gauge.SetValue(int(fractionDone * 1000))
                self.frame.SetTitle('%d%% %s - BitTorrent %s' % (int(fractionDone*100), self.filename, version))
            if timeEst is not None:
                self.timeEstText.SetLabel(hours(timeEst))
            if downRate is not None:
                self.downRateText.SetLabel('%.0f KiB/s' % (float(downRate) / (1 << 10)))
            if upRate is not None:
                self.upRateText.SetLabel('%.0f KiB/s' % (float(upRate) / (1 << 10)))
            if downTotal is not None:
                self.downTotalText.SetLabel('%.1f M' % (downTotal))
            if upTotal is not None:
                self.upTotalText.SetLabel('%.1f M' % (upTotal))
            self.last_update_time = time()
        except:
            print_exc()

    def finished(self):
        self.fin = True
        self.invokeLater(self.onFinishEvent)

    def failed(self):
        self.fin = True
        self.invokeLater(self.onFailEvent)

    def error(self, errormsg):
        if not self.showing_error:
            self.invokeLater(self.onErrorEvent, [errormsg])

    def onFinishEvent(self):
        self.timeEstText.SetLabel('Download Succeeded!')
        self.cancelButton.SetLabel('Close')
        self.gauge.SetValue(1000)
        self.frame.SetTitle('%s - Upload - BitTorrent %s' % (self.filename, version))
        self.downRateText.SetLabel('')

    def onFailEvent(self):
        self.timeEstText.SetLabel('Failed!')
        self.cancelButton.SetLabel('Close')
        self.gauge.SetValue(0)
        self.downRateText.SetLabel('')

    def onErrorEvent(self, errormsg):
        self.showing_error = True
        dlg = wxMessageDialog(self.frame, message = errormsg, 
            caption = 'Download Error', style = wxOK | wxICON_ERROR)
        dlg.Fit()
        dlg.Center()
        dlg.ShowModal()
        self.showing_error = False

    def chooseFile(self, default, size, saveas, dir):
        f = Event()
        bucket = [None]
        self.invokeLater(self.onChooseFile, [default, bucket, f, size, dir, saveas])
        f.wait()
        return bucket[0]
    
    def onChooseFile(self, default, bucket, f, size, dir, saveas):
        if not saveas:
            if dir:
                dl = wxDirDialog(self.frame, 'Choose a directory to save to, pick a partial download to resume', 
                    join(getcwd(), default), style = wxDD_DEFAULT_STYLE | wxDD_NEW_DIR_BUTTON)
            else:
                dl = wxFileDialog(self.frame, 'Choose file to save as, pick a partial download to resume', '', default, '*', wxSAVE)
            if dl.ShowModal() != wxID_OK:
                self.done(None)
                f.set()
                return
            saveas = dl.GetPath()
        bucket[0] = saveas
        self.fileNameText.SetLabel('%s (%.1f MB)' % (default, float(size) / (1 << 20)))
        self.timeEstText.SetLabel('Starting up...')
        self.fileDestText.SetLabel(saveas)
        self.filename = default
        self.frame.SetTitle(default + '- BitTorrent ' + version)
        f.set()

    def newpath(self, path):
        self.fileDestText.SetLabel(path)

    def done(self, event):
        self.uiflag.set()
        self.flag.set()
        self.frame.Destroy()

class btWxApp(wxApp):
    def __init__(self, x, params):
        self.params = params
        wxApp.__init__(self, x)

    def OnInit(self):
        doneflag = Event()
#I2P: workaround for wxpython 2.4.x        
        wxInitAllImageHandlers() 
#/I2P
        d = DownloadInfoFrame(doneflag)
        self.SetTopWindow(d.frame)
#I2P: no args => file dialog
        if ''.join(self.params)[:2] in ['--','']:
            b = wxFileDialog (d.frame, 'Choose .torrent file to use',
                        defaultDir = '', defaultFile = '', wildcard = '*.torrent',
                        style = wxOPEN)

            if b.ShowModal() == wxID_OK:
                self.params.insert(0, b.GetPath())
            else:
                d.done(None)
                return 1
#/I2P
        thread = Thread(target = next, args = [self.params, d, doneflag])
        thread.setDaemon(False)
        thread.start()
        return 1

def run(params):
    try:
        app = btWxApp(0, params)
        app.MainLoop()
    except:
        print_exc()

def next(params, d, doneflag):
    try:
#I2P: remove donation shit, anonymity reasons
#        p = join(split(argv[0])[0], 'donated')
#        if not exists(p) and long(time()) % 3 == 0:
#            open_new('http://bitconjurer.org/BitTorrent/donate.html')
#            dlg = wxMessageDialog(d.frame, 'BitTorrent is Donation supported software. ' + 
#                'Please go to the donation page (which should be appearing for you now) and make a donation from there. ' + 
#                'Or you can click no and donate later.\n\nHave you made a donation yet?',
#                'Donate!', wxYES_NO | wxICON_INFORMATION | wxNO_DEFAULT)
#            if dlg.ShowModal() == wxID_YES:
#                dlg.Destroy()
#                dlg = wxMessageDialog(d.frame, 'Thanks for your donation! You will no longer be shown donation requests.\n\n' + 
#                    "If you haven't actually made a donation and are feeling guilty (as you should!) you can always get to " + 
#                    "the donation page by clicking the 'about' link in the upper-right corner of the main BitTorrent window and " + 
#                    'donating from there.', 'Thanks!', wxOK)
#                dlg.ShowModal()
#                dlg.Destroy()
#                try:
#                    open(p, 'wb').close()
#                except IOError, e:
#                    dlg = wxMessageDialog(d.frame, "Sorry, but I couldn't set the flag to not ask you for donations in the future - " + str(e),
#                        'Sorry!', wxOK | wxICON_ERROR)
#                    dlg.ShowModal()
#                    dlg.Destroy()
#            else:
#                dlg.Destroy()
#/I2P
        download(params, d.chooseFile, d.updateStatus, d.finished, d.error, doneflag, 100, d.newpath)
        if not d.fin:
            d.failed()
    except:
        print_exc()

def next(params, d, doneflag):
    dow = Download ()
    d.dow = dow


if __name__ == '__main__':
    run(argv[1:])
der code:

Code: Alles auswählen

def next(params, d, doneflag):
    dow = Download ()
    d.dow = dow
lässt das pop up dialog fürs spechern nicht mehr aufrufen !
matrixnet
User
Beiträge: 35
Registriert: Donnerstag 21. April 2005, 16:45

Samstag 22. Oktober 2005, 14:15

sorry ich mein es tut sich nichts mehr mit den balken, das pop up fürs speichern geht!

aber es kommt keine verbindung zu stande!
und systray geht auch nicht!
joe

Samstag 22. Oktober 2005, 14:27

Jetzt hast du zwei next-funktionen, eine ohne dow und mit download()-aufruf und eine mit dow und ohne download()-aufruf.
Und von mir kommt jetzt ein EOD.
joe
btw: das wx-forum scheint weiter unten zu sein.
Gast

Samstag 22. Oktober 2005, 15:03

und wie siehts so aus?

Code: Alles auswählen

def next(params, d, doneflag):
    try:
#I2P: remove donation shit, anonymity reasons
#        p = join(split(argv[0])[0], 'donated')
#        if not exists(p) and long(time()) % 3 == 0:
#            open_new('http://bitconjurer.org/BitTorrent/donate.html')
#            dlg = wxMessageDialog(d.frame, 'BitTorrent is Donation supported software. ' + 
#                'Please go to the donation page (which should be appearing for you now) and make a donation from there. ' + 
#                'Or you can click no and donate later.\n\nHave you made a donation yet?',
#                'Donate!', wxYES_NO | wxICON_INFORMATION | wxNO_DEFAULT)
#            if dlg.ShowModal() == wxID_YES:
#                dlg.Destroy()
#                dlg = wxMessageDialog(d.frame, 'Thanks for your donation! You will no longer be shown donation requests.\n\n' + 
#                    "If you haven't actually made a donation and are feeling guilty (as you should!) you can always get to " + 
#                    "the donation page by clicking the 'about' link in the upper-right corner of the main BitTorrent window and " + 
#                    'donating from there.', 'Thanks!', wxOK)
#                dlg.ShowModal()
#                dlg.Destroy()
#                try:
#                    open(p, 'wb').close()
#                except IOError, e:
#                    dlg = wxMessageDialog(d.frame, "Sorry, but I couldn't set the flag to not ask you for donations in the future - " + str(e),
#                        'Sorry!', wxOK | wxICON_ERROR)
#                    dlg.ShowModal()
#                    dlg.Destroy()
#            else:
#                dlg.Destroy()
#/I2P
    dow = download ()
    d.dow = dow
    download(params, d.chooseFile, d.updateStatus, d.finished, d.error, doneflag, 100, d.newpath)
        if not d.fin:
            d.failed()
    except:
        print_exc()


if __name__ == '__main__':
    run(argv[1:])
es lässt sich nicht compilieren!

irgendwo stekckt der fehler
Leonidas
Administrator
Beiträge: 16024
Registriert: Freitag 20. Juni 2003, 16:30
Kontaktdaten:

Samstag 22. Oktober 2005, 17:09

Anonymous hat geschrieben:es lässt sich nicht compilieren!

irgendwo stekckt der fehler
Wie wärs denn mal zur abwechslung mit selber suchen?
joe hat geschrieben:Und von mir kommt jetzt ein EOD.
joe
btw: das wx-forum scheint weiter unten zu sein.
Ja, ich werd den Thread mal verschieben, aber eigentlich ist dieser Thread auch so ein Schließungskandidat.
My god, it's full of CARs! | Leonidasvoice vs Modvoice
Gast

Samstag 22. Oktober 2005, 19:04

also nun habe es wieder abgeändert:

Code: Alles auswählen

def next(params, d, doneflag):
    try:
#I2P: remove donation shit, anonymity reasons
#        p = join(split(argv[0])[0], 'donated')
#        if not exists(p) and long(time()) % 3 == 0:
#            open_new('http://bitconjurer.org/BitTorrent/donate.html')
#            dlg = wxMessageDialog(d.frame, 'BitTorrent is Donation supported software. ' + 
#                'Please go to the donation page (which should be appearing for you now) and make a donation from there. ' + 
#                'Or you can click no and donate later.\n\nHave you made a donation yet?',
#                'Donate!', wxYES_NO | wxICON_INFORMATION | wxNO_DEFAULT)
#            if dlg.ShowModal() == wxID_YES:
#                dlg.Destroy()
#                dlg = wxMessageDialog(d.frame, 'Thanks for your donation! You will no longer be shown donation requests.\n\n' + 
#                    "If you haven't actually made a donation and are feeling guilty (as you should!) you can always get to " + 
#                    "the donation page by clicking the 'about' link in the upper-right corner of the main BitTorrent window and " + 
#                    'donating from there.', 'Thanks!', wxOK)
#                dlg.ShowModal()
#                dlg.Destroy()
#                try:
#                    open(p, 'wb').close()
#                except IOError, e:
#                    dlg = wxMessageDialog(d.frame, "Sorry, but I couldn't set the flag to not ask you for donations in the future - " + str(e),
#                        'Sorry!', wxOK | wxICON_ERROR)
#                    dlg.ShowModal()
#                    dlg.Destroy()
#            else:
#                dlg.Destroy()
#/I2P
        dow = download
        download(params, d.chooseFile, d.updateStatus, d.finished, d.error, doneflag, 100, d.newpath)
        if not d.fin:
            d.failed()
    except:
        print_exc()


if __name__ == '__main__':
    run(argv[1:])
File "btdownloadgui.py", line 156, in onIconify
AttributeError: DownloadInfoFrame instance has no attribute 'dow'
Traceback (most recent call last):
mfg

matrixnet

Edit(Leonidas): Code in Python-Tags gesetzt.
matrixnet
User
Beiträge: 35
Registriert: Donnerstag 21. April 2005, 16:45

Sonntag 23. Oktober 2005, 15:21

leider fehlt mir das nötige know how weil ich kein python kann!
um es zum laufen zu bringen!
python ist jedenfalls übersichtlicher als java für mich!
Antworten