Ejemplo n.º 1
0
    def startDownload(self,torrentfilename,destdir=None,tdef = None, cmdline = False):
        try:
            if tdef is None:
                tdef = TorrentDef.load(torrentfilename)
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            dscfg = defaultDLConfig.copy()
            if destdir is not None:
                dscfg.set_dest_dir(destdir)
        
            videofiles = tdef.get_files(exts=videoextdefaults)
            
            if tdef.get_live() or (cmdline and len(videofiles) > 0):
                videoplayer = VideoPlayer.getInstance()
                return videoplayer.start_and_play(tdef,dscfg)
            else:
                return self.utility.session.start_download(tdef,dscfg)

        except DuplicateDownloadException:
            # show nice warning dialog
            dlg = wx.MessageDialog(None,
                                   self.utility.lang.get('duplicate_download_msg'),
                                   self.utility.lang.get('duplicate_download_title'),
                                   wx.OK|wx.ICON_INFORMATION)
            result = dlg.ShowModal()
            dlg.Destroy()

        except Exception,e:
            print_exc()
            self.onWarning(e)
Ejemplo n.º 2
0
    def __init__(self, utility = None, params = None, app = None):
        if GUIUtility.__single:
            raise RuntimeError, "GUIUtility is singleton"
        GUIUtility.__single = self 
        self.registered = False
        
        # do other init
        self.utility = utility
        self.vwxGUI_path = os.path.join(self.utility.getPath(), LIBRARYNAME, 'Main', 'vwxGUI')
        self.utility.guiUtility = self
        self.params = params
        self.frame = None
        self.app = app

        # videoplayer
        self.videoplayer = VideoPlayer.getInstance()
        self.useExternalVideo = False

        # current GUI page
        self.guiPage = 'home'
        # previous pages
        self.oldpage = []

        # port number
        self.port_number = None

        # firewall
        self.firewall_restart = False # ie Tribler needs to restart for the port number to be updated

        # Recall improves by 20-25% by increasing the number of peers to query to 20 from 10 !
        self.max_remote_queries = 20    # max number of remote peers to query
        
        self.current_search_query = ''
        
        self.lists = []
Ejemplo n.º 3
0
    def __init__(self, utility=None, params=None, app=None):
        if GUIUtility.__single:
            raise RuntimeError, "GUIUtility is singleton"
        GUIUtility.__single = self

        # do other init
        self.utility = utility
        self.vwxGUI_path = os.path.join(self.utility.getPath(), LIBRARYNAME,
                                        'Main', 'vwxGUI')
        self.utility.guiUtility = self
        self.params = params
        self.frame = None
        self.app = app

        # videoplayer
        self.videoplayer = VideoPlayer.getInstance()
        self.useExternalVideo = False

        # current GUI page
        self.guiPage = 'home'
        # previous pages
        self.oldpage = []

        # port number
        self.port_number = None

        # firewall
        self.firewall_restart = False  # ie Tribler needs to restart for the port number to be updated

        # Recall improves by 20-25% by increasing the number of peers to query to 20 from 10 !
        self.max_remote_queries = 20  # max number of remote peers to query

        self.current_search_query = ''
Ejemplo n.º 4
0
    def Load(self, url, streaminfo=None):
        if DEBUG:
            print >>sys.stderr, "embedplay: Load:", url, streaminfo, currentThread().getName()

        if streaminfo is not None:
            self.estduration = streaminfo.get("estduration", None)
            self.download = VideoPlayer.getInstance().get_vod_download()

        # 19/02/10 Boudewijn: no self.slider when self.vlcwrap is None
        # 26/05/09 Boudewijn: when using the external player we do not have a vlcwrap
        if self.vlcwrap:
            self.slider.Enable(True)

            # Arno, 2009-02-17: If we don't do this VLC gets the wrong playlist somehow
            self.vlcwrap.stop()
            self.vlcwrap.playlist_clear()
            self.vlcwrap.load(url, streaminfo=streaminfo)

            # Enable update of progress slider
            wx.CallAfter(self.slider.SetValue, 0)
            if self.timer is None:
                self.timer = wx.Timer(self)
                self.Bind(wx.EVT_TIMER, self.UpdateSlider)
            self.timer.Start(500)

        self.fsbtn.Enable(True)
        self.ppbtn.SetBitmapLabel(self.bmp_pause, recreate=True)
        self.ppbtn.Enable(True)
        self.sbtn.Enable(True)
Ejemplo n.º 5
0
    def Load(self, url, streaminfo=None):
        if DEBUG:
            print >> sys.stderr, "embedplay: Load:", url, streaminfo, currentThread().getName()

        if streaminfo is not None:
            self.estduration = streaminfo.get('estduration', None)
            self.download = VideoPlayer.getInstance().get_vod_download()

        # 19/02/10 Boudewijn: no self.slider when self.vlcwrap is None
        # 26/05/09 Boudewijn: when using the external player we do not have a vlcwrap
        if self.vlcwrap:
            self.slider.Enable(True)

            # Arno, 2009-02-17: If we don't do this VLC gets the wrong playlist somehow
            self.vlcwrap.stop()
            self.vlcwrap.playlist_clear()
            self.vlcwrap.load(url, streaminfo=streaminfo)

            # Enable update of progress slider
            wx.CallAfter(self.slider.SetValue, 0)
            if self.timer is None:
                self.timer = wx.Timer(self)
                self.Bind(wx.EVT_TIMER, self.UpdateSlider)
            self.timer.Start(500)

        self.fsbtn.Enable(True)
        self.ppbtn.SetBitmapLabel(self.bmp_pause, recreate=True)
        self.ppbtn.Enable(True)
        self.sbtn.Enable(True)
Ejemplo n.º 6
0
        def do_monitor():
            from Tribler.Video.VideoPlayer import VideoPlayer
            d = VideoPlayer.getInstance().get_vod_download()
            self.assert_(bool(d), "No VOD download found")

            self.screenshot('After starting a VOD download')
            self.CallConditional(60, lambda: d.network_get_vod_stats()['status'] == "started", take_screenshot, "streaming did not start")
Ejemplo n.º 7
0
 def do_monitor():
     from Tribler.Video.VideoPlayer import VideoPlayer
     d = VideoPlayer.getInstance().get_vod_download()
     self.assert_(bool(d), "No VOD download found")
     
     self.screenshot('After starting a VOD download')
     self.CallConditional(60, lambda : d.network_calc_prebuf_frac() == 1.0, do_assert)
Ejemplo n.º 8
0
    def startDownload(self,
                      torrentfilename,
                      destdir=None,
                      tdef=None,
                      cmdline=False):
        try:
            if tdef is None:
                tdef = TorrentDef.load(torrentfilename)
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            dscfg = defaultDLConfig.copy()
            if destdir is not None:
                dscfg.set_dest_dir(destdir)

            videofiles = tdef.get_files(exts=videoextdefaults)

            if tdef.get_live() or (cmdline and len(videofiles) > 0):
                videoplayer = VideoPlayer.getInstance()
                return videoplayer.start_and_play(tdef, dscfg)
            else:
                return self.utility.session.start_download(tdef, dscfg)

        except DuplicateDownloadException:
            # show nice warning dialog
            dlg = wx.MessageDialog(
                None, self.utility.lang.get('duplicate_download_msg'),
                self.utility.lang.get('duplicate_download_title'),
                wx.OK | wx.ICON_INFORMATION)
            result = dlg.ShowModal()
            dlg.Destroy()

        except Exception, e:
            print_exc()
            self.onWarning(e)
Ejemplo n.º 9
0
 def deleteTorrentDS(self, ds, infohash, removecontent = False):
     if not ds is None:
         videoplayer = VideoPlayer.getInstance()
         playd = videoplayer.get_vod_download()
         
         if playd == ds.download:
             self._get_videoplayer(ds).stop_playback()
         
     self.deleteTorrentDownload(ds.get_download(), infohash, removecontent)
Ejemplo n.º 10
0
        def do_monitor():
            from Tribler.Video.VideoPlayer import VideoPlayer
            d = VideoPlayer.getInstance().get_vod_download()
            self.assert_(bool(d), "No VOD download found")

            self.screenshot('After starting a VOD download')
            self.CallConditional(60,
                                 lambda: d.network_calc_prebuf_frac() == 1.0,
                                 do_assert)
Ejemplo n.º 11
0
 def _get_videoplayer(self, exclude=None):
     """
     Returns the VideoPlayer instance and ensures that it knows if
     there are other downloads running.
     """
     other_downloads = False
     for ds in self.dslist:
         if ds is not exclude and ds.get_status() not in (DLSTATUS_STOPPED, DLSTATUS_STOPPED_ON_ERROR):
             other_downloads = True
             break
     
     videoplayer = VideoPlayer.getInstance()
     videoplayer.set_other_downloads(other_downloads)
     
     self.guiUtility.ShowPlayer(True)
     return videoplayer
Ejemplo n.º 12
0
 def monitorSwiftProgress(self, ds, vodmode, torrentfilename, dscfg, selectedFile):
     if ds.get_progress() == 0:
         if ds.get_status() == DLSTATUS_ALLOCATING_DISKSPACE:
             return (5.0, True)
         
         download = ds.get_download()
         self.utility.session.remove_download(download)
         
         #pause for swift file release
         time.sleep(1)
         
         print >> sys.stderr, "Switching to Bittorrent"
         cdef = TorrentDef.load(torrentfilename)
         if vodmode:
             videoplayer = VideoPlayer.getInstance()
             wx.CallAfter(videoplayer.start_and_play, cdef, dscfg, selectedFile)
         else:
             self.utility.session.start_download(cdef, dscfg)
     return (0, False)
Ejemplo n.º 13
0
    def __init__(self, utility = None, params = None):
        if GUIUtility.__single:
            raise RuntimeError, "GUIUtility is singleton"
        GUIUtility.__single = self

        # do other init
        self.utility = utility
        self.vwxGUI_path = os.path.join(self.utility.getPath(), LIBRARYNAME, 'Main', 'vwxGUI')
        self.utility.guiUtility = self
        self.params = params
        self.frame = None

       # videoplayer
        self.videoplayer = VideoPlayer.getInstance()
        self.useExternalVideo = False

        # current GUI page
        self.guiPage = None

        # port number
        self.port_number = None

        # firewall
        self.firewall_restart = False # ie Tribler needs to restart for the port number to be updated

        self.mainColour = wx.Colour(216,233,240) # main color theme used throughout the interface

        self.selectedColour = self.mainColour
        self.unselectedColour = wx.WHITE ## 102,102,102
        self.unselectedColour2 = wx.WHITE ## 230,230,230
        self.selectedColourPending = self.mainColour  ## 208,251,244
        self.bgColour = wx.Colour(102,102,102)

        # Recall improves by 20-25% by increasing the number of peers to query to 20 from 10 !
        self.max_remote_queries = 20    # max number of remote peers to query

        self.current_search_query = ''
Ejemplo n.º 14
0
 def switch_to_vod(self,ds):
     videoplayer = VideoPlayer.getInstance()
     videoplayer.play(ds)
Ejemplo n.º 15
0
    def __init__(self, params, single_instance_checker, installdir):
        self.params = params
        self.single_instance_checker = single_instance_checker
        self.installdir = self.configure_install_dir(installdir)

        self.state_dir = None
        self.error = None
        self.last_update = 0
        self.ready = False
        self.done = False
        self.frame = None

        self.guiserver = GUITaskQueue.getInstance()
        self.said_start_playback = False
        self.decodeprogress = 0

        self.old_reputation = 0

        # DISPERSY will be set when available
        self.dispersy = None
        # BARTER_COMMUNITY will be set when both Dispersy and the EffortCommunity are available
        self.barter_community = None

        self.seedingmanager = None
        self.i2is = None
        self.torrentfeed = None
        self.webUI = None
        self.utility = None
        self.videoplayer = None

        try:
            bm = wx.Bitmap(os.path.join(self.installdir, 'Tribler', 'Main', 'vwxGUI', 'images', 'splash.png'), wx.BITMAP_TYPE_ANY)
            self.splash = GaugeSplash(bm)
            self.splash.setTicks(10)
            self.splash.Show()

            print >> sys.stderr, 'Client Starting Up.'
            print >> sys.stderr, "Tribler is using", self.installdir, "as working directory"

            self.splash.tick('Starting API')
            s = self.startAPI(self.splash.tick)

            print >> sys.stderr, "Tribler is expecting swift in", self.sconfig.get_swift_path()

            self.dispersy = s.lm.dispersy

            self.utility = Utility(self.installdir, s.get_state_dir())
            self.utility.app = self
            self.utility.session = s
            self.guiUtility = GUIUtility.getInstance(self.utility, self.params, self)
            GUIDBProducer.getInstance(self.dispersy.callback)

            print >> sys.stderr, 'Tribler Version:', self.utility.lang.get('version'), ' Build:', self.utility.lang.get('build')

            self.splash.tick('Loading userdownloadchoice')
            from Tribler.Main.vwxGUI.UserDownloadChoice import UserDownloadChoice
            UserDownloadChoice.get_singleton().set_session_dir(s.get_state_dir())

            self.splash.tick('Initializing Family Filter')
            cat = Category.getInstance()

            state = self.utility.config.Read('family_filter')
            if state in ('1', '0'):
                cat.set_family_filter(state == '1')
            else:
                self.utility.config.Write('family_filter', '1')
                self.utility.config.Flush()

                cat.set_family_filter(True)

            # Create global rate limiter
            self.splash.tick('Setting up ratelimiters')
            self.ratelimiter = UserDefinedMaxAlwaysOtherwiseDividedOverActiveSwarmsRateManager()

            # Counter to suppress some event from occurring
            self.ratestatecallbackcount = 0

            # So we know if we asked for peer details last cycle
            self.lastwantpeers = []

            # boudewijn 01/04/2010: hack to fix the seedupload speed that
            # was never used and defaulted to 0 (unlimited upload)
            maxup = self.utility.config.Read('maxuploadrate', "int")
            if maxup == -1:  # no upload
                self.ratelimiter.set_global_max_speed(UPLOAD, 0.00001)
                self.ratelimiter.set_global_max_seedupload_speed(0.00001)
            else:
                self.ratelimiter.set_global_max_speed(UPLOAD, maxup)
                self.ratelimiter.set_global_max_seedupload_speed(maxup)

            maxdown = self.utility.config.Read('maxdownloadrate', "int")
            self.ratelimiter.set_global_max_speed(DOWNLOAD, maxdown)

            self.seedingmanager = GlobalSeedingManager(self.utility.config.Read)

            # Only allow updates to come in after we defined ratelimiter
            self.prevActiveDownloads = []
            s.set_download_states_callback(self.sesscb_states_callback)

            # Schedule task for checkpointing Session, to avoid hash checks after
            # crashes.
            self.guiserver.add_task(self.guiservthread_checkpoint_timer, SESSION_CHECKPOINT_INTERVAL)

            self.utility.postAppInit(os.path.join(self.installdir, 'Tribler', 'Main', 'vwxGUI', 'images', 'tribler.ico'))

            # Put it here so an error is shown in the startup-error popup
            # Start server for instance2instance communication
            self.i2iconnhandler = InstanceConnectionHandler(self.i2ithread_readlinecallback)
            self.i2is = Instance2InstanceServer(I2I_LISTENPORT, self.i2iconnhandler)
            self.i2is.start()

            # Arno, 2010-01-15: VLC's reading behaviour of doing open-ended
            # Range: GETs causes performance problems in our code. Disable for now.
            # Arno, 2010-01-22: With the addition of a CachingStream the problem
            # is less severe (see VideoPlayer), so keep GET Range enabled.
            #
            # SimpleServer.RANGE_REQUESTS_ENABLED = False

            # Fire up the VideoPlayer, it abstracts away whether we're using
            # an internal or external video player.
            playbackmode = self.utility.config.Read('videoplaybackmode', "int")
            self.videoplayer = VideoPlayer.getInstance(httpport=VIDEOHTTP_LISTENPORT)
            self.videoplayer.register(self.utility, preferredplaybackmode=playbackmode)

            notification_init(self.utility)
            self.guiUtility.register()

            channel_only = os.path.exists(os.path.join(self.installdir, 'joinchannel'))
            if channel_only:
                f = open(os.path.join(self.installdir, 'joinchannel'), 'rb')
                channel_only = f.readline()
                f.close()

            self.frame = MainFrame(None, channel_only, PLAYBACKMODE_INTERNAL in return_feasible_playback_modes(self.utility.getPath()), self.splash.tick)

            # Arno, 2011-06-15: VLC 1.1.10 pops up separate win, don't have two.
            self.frame.videoframe = None
            if PLAYBACKMODE_INTERNAL in return_feasible_playback_modes(self.utility.getPath()):
                vlcwrap = self.videoplayer.get_vlcwrap()

                self.frame.videoframe = VideoDummyFrame(self.frame.videoparentpanel, self.utility, vlcwrap)
                self.videoplayer.set_videoframe(self.frame.videoframe)

            if sys.platform == 'win32':
                wx.CallAfter(self.frame.top_bg.Refresh)
                wx.CallAfter(self.frame.top_bg.Layout)
            else:
                self.frame.top_bg.Layout()

            # Arno, 2007-05-03: wxWidgets 2.8.3.0 and earlier have the MIME-type for .bmp
            # files set to 'image/x-bmp' whereas 'image/bmp' is the official one.
            try:
                bmphand = None
                hands = wx.Image.GetHandlers()
                for hand in hands:
                    # print "Handler",hand.GetExtension(),hand.GetType(),hand.GetMimeType()
                    if hand.GetMimeType() == 'image/x-bmp':
                        bmphand = hand
                        break
                # wx.Image.AddHandler()
                if bmphand is not None:
                    bmphand.SetMimeType('image/bmp')
            except:
                # wx < 2.7 don't like wx.Image.GetHandlers()
                print_exc()

            self.splash.Destroy()
            self.frame.Show(True)

            self.torrentfeed = RssParser.getInstance()

            self.webUI = None
            if self.utility.config.Read('use_webui', "boolean"):
                try:
                    from Tribler.Main.webUI.webUI import WebUI
                    self.webUI = WebUI.getInstance(self.guiUtility.library_manager, self.guiUtility.torrentsearch_manager, self.utility.config.Read('webui_port', "int"))
                    self.webUI.start()
                except Exception:
                    print_exc()

            wx.CallAfter(self.PostInit2)

            # 08/02/10 Boudewijn: Working from home though console
            # doesn't allow me to press close.  The statement below
            # gracefully closes Tribler after 120 seconds.
            # wx.CallLater(120*1000, wx.GetApp().Exit)

            status = get_status_holder("LivingLab")
            status.add_reporter(NullReporter("Periodically remove all events", 0))
# status.add_reporter(LivingLabPeriodicReporter("Living lab CS reporter", 300, "Tribler client")) # Report every 5 minutes
# status.add_reporter(LivingLabPeriodicReporter("Living lab CS reporter", 30, "Tribler client")) # Report every 30 seconds - ONLY FOR TESTING

            # report client version
            status.create_and_add_event("client-startup-version", [self.utility.lang.get("version")])
            status.create_and_add_event("client-startup-build", [self.utility.lang.get("build")])
            status.create_and_add_event("client-startup-build-date", [self.utility.lang.get("build_date")])

            self.ready = True

        except Exception as e:
            self.onError(e)
            return False
Ejemplo n.º 16
0
    def OnCloseWindow(self, event = None):
        found = False
        if event != None:
            nr = event.GetEventType()
            lookup = { wx.EVT_CLOSE.evtType[0]: "EVT_CLOSE", wx.EVT_QUERY_END_SESSION.evtType[0]: "EVT_QUERY_END_SESSION", wx.EVT_END_SESSION.evtType[0]: "EVT_END_SESSION" }
            if nr in lookup: 
                nr = lookup[nr]
                found = True
                
            print "mainframe: Closing due to event ",nr,`event`
            print >>sys.stderr,"mainframe: Closing due to event ",nr,`event`
        else:
            print "mainframe: Closing untriggered by event"
        
        
        # Don't do anything if the event gets called twice for some reason
        if self.utility.abcquitting:
            return

        # Check to see if we can veto the shutdown
        # (might not be able to in case of shutting down windows)
        if event is not None:
            try:
                if isinstance(event,wx.CloseEvent) and event.CanVeto() and self.utility.config.Read('confirmonclose', "boolean") and not event.GetEventType() == wx.EVT_QUERY_END_SESSION.evtType[0]:
                    if self.shutdown_and_upgrade_notes:
                        confirmmsg = self.utility.lang.get('confirmupgrademsg') + "\n\n" + self.shutdown_and_upgrade_notes
                        confirmtitle = self.utility.lang.get('confirmupgrade')
                    else:
                        confirmmsg = self.utility.lang.get('confirmmsg')
                        confirmtitle = self.utility.lang.get('confirm')

                    dialog = wx.MessageDialog(self, confirmmsg, confirmtitle, wx.OK|wx.CANCEL|wx.ICON_QUESTION)
                    result = dialog.ShowModal()
                    dialog.Destroy()
                    if result != wx.ID_OK:
                        event.Veto()
                        return
            except:
                print_exc()
            
        self.utility.abcquitting = True
        self.GUIupdate = False
        
        videoplayer = VideoPlayer.getInstance()
        videoplayer.stop_playback()

        try:
            # Restore the window before saving size and position
            # (Otherwise we'll get the size of the taskbar button and a negative position)
            self.onTaskBarActivate()
            self.saveWindowSettings()
        except:
            print_exc()

        try:
            if self.videoframe is not None:
                self.videoframe.Destroy()
        except:
            print_exc()
        
        try:
            if self.tbicon is not None:
                self.tbicon.RemoveIcon()
                self.tbicon.Destroy()
            self.Destroy()
        except:
            print_exc()

        if DEBUG:    
            print >>sys.stderr,"mainframe: OnCloseWindow END"

        if DEBUG:
            ts = enumerate()
            for t in ts:
                print >>sys.stderr,"mainframe: Thread still running",t.getName(),"daemon",t.isDaemon()

        if not found or sys.platform =="darwin":
            # On Linux with wx 2.8.7.1 this method gets sometimes called with
            # a CommandEvent instead of EVT_CLOSE, wx.EVT_QUERY_END_SESSION or
            # wx.EVT_END_SESSION
            self.quit()
Ejemplo n.º 17
0
 def play(self,ds):
     videoplayer = VideoPlayer.getInstance()
     videoplayer.play(ds)
Ejemplo n.º 18
0
    def startDownload(self,torrentfilename=None,destdir=None,tdef = None,cmdline=False,clicklog=None,name=None,vodmode=False,doemode=None,fixtorrent=False,selectedFiles=None):
        if DEBUG:
            print >>sys.stderr,"mainframe: startDownload:",torrentfilename,destdir,tdef
        
        if fixtorrent and torrentfilename:
            self.fixTorrent(torrentfilename)
        try:
            if tdef is None:
                tdef = TorrentDef.load(torrentfilename)
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            dscfg = defaultDLConfig.copy()
            
            cancelDownload = False
            useDefault = not dscfg.get_show_saveas()
            if not useDefault and not destdir:
                dlg = SaveAs(self, tdef, dscfg.get_dest_dir(), os.path.join(self.utility.session.get_state_dir(), 'recent_download_history'))
                dlg.CenterOnParent()
                if dlg.ShowModal() == wx.ID_OK:
                    destdir = dlg.GetPath()
                else:
                    cancelDownload = True
                dlg.Destroy()
            
            if not cancelDownload:
                if destdir is not None:
                    dscfg.set_dest_dir(destdir)
            
                # ProxyService 90s Test_
#                if doemode is not None:
#                    dscfg.set_doe_mode(doemode)
#                    dscfg.set_proxyservice_role(PROXYSERVICE_ROLE_DOE)
                # _ProxyService 90s Test
            
                videofiles = tdef.get_files(exts=videoextdefaults)
                if vodmode and len(videofiles) == 0:
                    vodmode = False
    
                if vodmode or tdef.get_live():
                    print >>sys.stderr, 'MainFrame: startDownload: Starting in VOD mode'
                    videoplayer = VideoPlayer.getInstance()
                    result = videoplayer.start_and_play(tdef,dscfg)
    
                    # 02/03/09 boudewijn: feedback to the user when there
                    # are no playable files in the torrent
                    if not result:
                        dlg = wx.MessageDialog(self,
                                   self.utility.lang.get("invalid_torrent_no_playable_files_msg"),
                                   self.utility.lang.get("invalid_torrent_no_playable_files_title"),
                                   wx.OK|wx.ICON_ERROR)
                        dlg.ShowModal()
                        dlg.Destroy()
                else:
                    if selectedFiles:
                        dscfg.set_selected_files(selectedFiles)
                    
                    print >>sys.stderr, 'MainFrame: startDownload: Starting in DL mode'
                    result = self.utility.session.start_download(tdef,dscfg)
                
                if result:
                    self.show_saved()
                
                # store result because we want to store clicklog data
                # right after d#        self.frame.sendButton.Disable()
#        # Disabling the focused button disables keyboard navigation
#        # unless we set the focus to something else - let's put it
#        # on close button
#        self.frame.closeButton.SetFocus() 
#        self.frame.sendButton.SetLabel(_(u'Sending...'))
#        
#        try:
#            from M2Crypto import httpslib, SSL
#            # Try to load the CA certificates for secure SSL.
#            # If we can't load them, the data is hidden from casual observation,
#            # but a man-in-the-middle attack is possible.
#            ctx = SSL.Context()
#            opts = {}
#            if ctx.load_verify_locations('parcels/osaf/framework/certstore/cacert.pem') == 1:
#                ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 9)
#                opts['ssl_context'] = ctx
#            c = httpslib.HTTPSConnection('feedback.osafoundation.org', 443, opts)
#            body = buildXML(self.frame.comments, self.frame.email,
#                            self.frame.sysInfo, self.frame.text)
#            c.request('POST', '/desktop/post/submit', body)
#            response = c.getresponse()
#            
#            if response.status != 200:
#                raise Exception('response.status=' + response.status)
#            c.close()
#        except:
#            self.frame.sendButton.SetLabel(_(u'Failed to send'))
#        else:
#            self.frame.sendButton.SetLabel(_(u'Sent'))
#            self.logReport(body, response.read())ownload was started, then return result
                if clicklog is not None:
                    mypref = self.utility.session.open_dbhandler(NTFY_MYPREFERENCES)
                    mypref.addClicklogToMyPreference(tdef.get_infohash(), clicklog)

                return result  

        except DuplicateDownloadException:
            # show nice warning dialog
            dlg = wx.MessageDialog(None,
                                   self.utility.lang.get('duplicate_download_msg'),
                                   self.utility.lang.get('duplicate_download_title'),
                                   wx.OK|wx.ICON_ERROR)
            result = dlg.ShowModal()
            dlg.Destroy()
            
            # If there is something on the cmdline, all other torrents start
            # in STOPPED state. Restart
            if cmdline:
                dlist = self.utility.session.get_downloads()
                for d in dlist:
                    if d.get_def().get_infohash() == tdef.get_infohash():
                        d.restart()
                        break
        except Exception,e:
            print_exc()
            self.onWarning(e)
Ejemplo n.º 19
0
    def startDownload(self,torrentfilename=None,destdir=None,sdef=None,tdef=None,cmdline=False,clicklog=None,name=None,vodmode=False,doemode=None,fixtorrent=False,selectedFiles=None,correctedFilename=None,hidden=False):
        if True or DEBUG:
            print >>sys.stderr,"mainframe: startDownload:",torrentfilename, destdir,sdef,tdef,vodmode,selectedFiles

        if fixtorrent and torrentfilename:
            self.fixTorrent(torrentfilename)

        #Niels: if you call startdownload with both a Swift sdef and a tdef/torrentfilename, we allow Swift to download the file in the first X seconds
        if sdef and (torrentfilename or tdef):
            monitorSwiftProgress = True
        else:
            monitorSwiftProgress = False

        try:
            if torrentfilename and tdef is None:
                tdef = TorrentDef.load(torrentfilename)

            cdef = sdef or tdef

            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            dscfg = defaultDLConfig.copy()

            cancelDownload = False
            useDefault = not dscfg.get_show_saveas()
            if not useDefault and not destdir:
                defaultname = correctedFilename
                if not correctedFilename and tdef and tdef.is_multifile_torrent():
                    defaultname = tdef.get_name_as_unicode()

                if wx.Thread_IsMain():
                    dlg = SaveAs(self, tdef, dscfg.get_dest_dir(), defaultname, os.path.join(self.utility.session.get_state_dir(), 'recent_download_history'), selectedFiles)
                    dlg.CenterOnParent()

                    if dlg.ShowModal() == wx.ID_OK:
                        #for multifile we enabled correctedFilenames, use split to remove the filename from the path
                        if tdef and tdef.is_multifile_torrent():
                            destdir, correctedFilename = os.path.split(dlg.GetPath())
                            selectedFiles = dlg.GetSelectedFiles()
                        else:
                            destdir = dlg.GetPath()
                    else:
                        cancelDownload = True
                    dlg.Destroy()
                else:
                    raise Exception("cannot create dialog, not on wx thread")

            if not cancelDownload:
                if destdir is not None:
                    dscfg.set_dest_dir(destdir)

                if correctedFilename:
                    dscfg.set_corrected_filename(correctedFilename)

                if selectedFiles and len(selectedFiles) == 1:
                    #we should filter files to see if they are all playable
                    videofiles = selectedFiles

                elif tdef and not selectedFiles:
                    videofiles = tdef.get_files(exts=videoextdefaults)

                else:
                    videofiles = []

                #disable vodmode if no videofiles
                if vodmode and len(videofiles) == 0:
                    vodmode = False

                vodmode = vodmode or cdef.get_live()

                selectedFile = None
                if vodmode:
                    print >>sys.stderr, 'MainFrame: startDownload: Starting in VOD mode'
                    if len(videofiles) == 1:
                        selectedFile = videofiles[0]
                    else:
                        selectedFile = None

                    #Swift requires swarmname to be part of the selectedfile
                    if cdef.get_def_type() == 'swift' and tdef and selectedFile:
                        swift_selectedFile = tdef.get_name_as_unicode()+"/"+selectedFile
                    else:
                        swift_selectedFile = selectedFile

                    videoplayer = VideoPlayer.getInstance()
                    result = videoplayer.start_and_play(cdef, dscfg, swift_selectedFile)

                else:
                    if selectedFiles:
                        if cdef.get_def_type() == 'swift' and tdef:
                            swift_selectedFiles = []
                            for selectedFile in selectedFiles:
                                swift_selectedFiles.append(tdef.get_name_as_unicode()+"/"+selectedFile)
                            dscfg.set_selected_files(swift_selectedFiles)

                        else:
                            dscfg.set_selected_files(selectedFiles)

                    # METADIRTODO: if swift and not .torrent call dscfg.set_swift_meta_dir() to dir with meta
                    #dscfg.set_swift_meta_dir("C:\\Users\\arno\\Desktop\\TriblerDownloads\meta")

                    print >>sys.stderr, 'MainFrame: startDownload: Starting in DL mode'
                    result = self.utility.session.start_download(cdef, dscfg, hidden=hidden)

                if result and not hidden:
                    self.show_saved(tdef)

                    if monitorSwiftProgress:
                        state_lambda = lambda ds, vodmode=vodmode, torrentfilename=torrentfilename, dscfg=dscfg, selectedFile=selectedFile, selectedFiles=selectedFiles: self.monitorSwiftProgress(ds, vodmode, torrentfilename, dscfg, selectedFile, selectedFiles)
                        result.set_state_callback(state_lambda, getpeerlist=False, delay=15.0)

                if clicklog is not None:
                    mypref = self.utility.session.open_dbhandler(NTFY_MYPREFERENCES)
                    startWorker(None, mypref.addClicklogToMyPreference, wargs= (cdef.get_id(), clicklog))

                return result

        except DuplicateDownloadException,e:
            # If there is something on the cmdline, all other torrents start
            # in STOPPED state. Restart
            if cmdline and cdef.get_def_type() == 'torrent':
                dlist = self.utility.session.get_downloads()
                for d in dlist:
                    if d.get_def().get_infohash() == cdef.get_infohash():
                        d.restart()
                        break

            if wx.Thread_IsMain():
                # show nice warning dialog
                dlg = wx.MessageDialog(None,
                                       self.utility.lang.get('duplicate_download_msg'),
                                       self.utility.lang.get('duplicate_download_title'),
                                       wx.OK|wx.ICON_ERROR)
                result = dlg.ShowModal()
                dlg.Destroy()

            else:
                print_exc()
                self.onWarning(e)
Ejemplo n.º 20
0
 def switch_to_standard_dlmode(self,ABCTorrentTemp): 
     videoplayer = VideoPlayer.getInstance() 
     videoplayer.vod_back_to_standard_dlmode(ABCTorrentTemp) 
Ejemplo n.º 21
0
    def _PostInit(self):
        # Do all init here
        self.guiUtility = GUIUtility.getInstance()
        self.utility = self.guiUtility.utility
        self.params = self.guiUtility.params
        self.utility.frame = self
        self.torrentfeed = None
        
        title = self.utility.lang.get('title') + \
                " " + \
                self.utility.lang.get('version')
        
        # Get window size and position from config file
        size, position = self.getWindowSettings()
        style = wx.DEFAULT_FRAME_STYLE | wx.CLIP_CHILDREN
        
        self.SetSize(size)
        self.SetPosition(position)
        self.SetTitle(title)
        tt = self.GetToolTip()
        if tt is not None:
            tt.SetTip('')
        
        #wx.Frame.__init__(self, None, ID, title, position, size, style = style)
        
        self.doneflag = Event()

        dragdroplist = FileDropTarget(self)
        self.SetDropTarget(dragdroplist)

        self.tbicon = None

        # Arno: see ABCPanel
        #self.abc_sb = ABCStatusBar(self,self.utility)
        #self.SetStatusBar(self.abc_sb)

        """
        # Add status bar
        statbarbox = wx.BoxSizer(wx.HORIZONTAL)
        self.sb_buttons = ABCStatusButtons(self,self.utility)
        statbarbox.Add(self.sb_buttons, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 0)
        self.abc_sb = ABCStatusBar(self,self.utility)
        statbarbox.Add(self.abc_sb, 1, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 0)
        #colSizer.Add(statbarbox, 0, wx.ALL|wx.EXPAND, 0)
        self.SetStatusBar(statbarbox)
        """
        
        
        try:
            self.SetIcon(self.utility.icon)
        except:
            pass

        # Don't update GUI as often when iconized
        self.GUIupdate = True

        # Start the scheduler before creating the ListCtrl
        #self.utility.queue  = ABCScheduler(self.utility)
        #self.window = ABCPanel(self)
        #self.abc_sb = self.window.abc_sb
        
        
        self.oldframe = None
        #self.oldframe = ABCOldFrame(-1, self.params, self.utility)
        #self.oldframe.Refresh()
        #self.oldframe.Layout()
        #self.oldframe.Show(True)
        
        self.window = self.GetChildren()[0]
        self.window.utility = self.utility
        
        """
        self.list = ABCList(self.window)
        self.list.Show(False)
        self.utility.list = self.list
        print self.window.GetName()
        self.window.list = self.list
        self.utility.window = self.window
        """
        #self.window.sb_buttons = ABCStatusButtons(self,self.utility)
        
        #self.utility.window.postponedevents = []
        
        # Menu Options
        ############################
        #menuBar = ABCMenuBar(self)
        #if sys.platform == "darwin":
        #    wx.App.SetMacExitMenuItemId(wx.ID_CLOSE)
        #self.SetMenuBar(menuBar)
        
        #self.tb = ABCToolBar(self) # new Tribler gui has no toolbar
        #self.SetToolBar(self.tb)
        
        self.buddyFrame = None
        self.fileFrame = None
        self.buddyFrame_page = 0
        self.buddyFrame_size = (800, 500)
        self.buddyFrame_pos = None
        self.fileFrame_size = (800, 500)
        self.fileFrame_pos = None
        
        # Menu Events 
        ############################

        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
#        self.Bind(wx.EVT_MENU, self.OnMenuExit, id = wx.ID_CLOSE)

        # leaving here for the time being:
        # wxMSW apparently sends the event to the App object rather than
        # the top-level Frame, but there seemed to be some possibility of
        # change
        self.Bind(wx.EVT_QUERY_END_SESSION, self.OnCloseWindow)
        self.Bind(wx.EVT_END_SESSION, self.OnCloseWindow)
        
        try:
            self.tbicon = ABCTaskBarIcon(self)
        except:
            print_exc()
        self.Bind(wx.EVT_ICONIZE, self.onIconify)
        self.Bind(wx.EVT_SET_FOCUS, self.onFocus)
        self.Bind(wx.EVT_SIZE, self.onSize)
        self.Bind(wx.EVT_MAXIMIZE, self.onSize)
        #self.Bind(wx.EVT_IDLE, self.onIdle)


        # If the user passed a torrentfile on the cmdline, load it.
        if DEBUG:
            print >>sys.stderr,"abc: wxFrame: params is",self.params

        # Init video player
        self.videoFrame = None
        feasible = return_feasible_playback_modes(self.utility.getPath())
        if PLAYBACKMODE_INTERNAL in feasible:
            # This means vlc is available
            from Tribler.Video.EmbeddedPlayer import VideoFrame
            iconpath = os.path.join(self.utility.getPath(),'Tribler','Images','tribler.ico')
            logopath = os.path.join(self.utility.getPath(),'Tribler','Images','logoTribler.png')
            self.videoFrame = VideoFrame(self,'Tribler Video',iconpath,logopath)

            #self.videores = xrc.XmlResource("Tribler/vwxGUI/MyPlayer.xrc")
            #self.videoframe = self.videores.LoadFrame(None, "MyPlayer")
            #self.videoframe.Show()
            
            videoplayer = VideoPlayer.getInstance()
            videoplayer.set_parentwindow(self.videoFrame)
        else:
            videoplayer = VideoPlayer.getInstance()
            videoplayer.set_parentwindow(self)

        
        sys.stdout.write('GUI Complete.\n')

        self.Show(True)
        
        
        # Just for debugging: add test permids and display top 5 peers from which the most is downloaded in bartercastdb
#        bartercastdb = BarterCastDBHandler.getInstance()
#        mypermid = bartercastdb.my_permid
#        
#        if DEBUG:
#            
#            top = bartercastdb.getTopNPeers(5)['top']
#    
#            print 'My Permid: ', show_permid(mypermid)
#            
#            print 'Top 5 BarterCast peers:'
#            print '======================='
#    
#            i = 1
#            for (permid, up, down) in top:
#                print '%2d: %15s  -  %10d up  %10d down' % (i, bartercastdb.getName(permid), up, down)
#                i += 1
        
        
        # Check to see if ABC is associated with torrents
        #######################################################
        if (sys.platform == 'win32'):
            if self.utility.config.Read('associate', "boolean"):
                if self.utility.regchecker and not self.utility.regchecker.testRegistry():
                    dialog = RegCheckDialog(self)
                    dialog.ShowModal()
                    dialog.Destroy()

        self.checkVersion()

        wx.CallAfter(self.startCMDLineTorrent)
Ejemplo n.º 22
0
    def startDownload(self,torrentfilename=None,destdir=None,cdef=None,cmdline=False,clicklog=None,name=None,vodmode=False,doemode=None,fixtorrent=False,selectedFiles=None,correctedFilename=None):
        if True or DEBUG:
            print >>sys.stderr,"mainframe: startDownload:",torrentfilename, destdir,cdef,vodmode,selectedFiles
        
        if fixtorrent and torrentfilename:
            self.fixTorrent(torrentfilename)
            
        #Niels: if you call startdownload with both a Swift cdef and a torrentfilename, we allow Swift to download the file in the first X seconds
        if cdef and cdef.get_def_type() == 'swift' and torrentfilename:
            monitorSwiftProgress = True
        else:
            monitorSwiftProgress = False
            
        try:
            if cdef is None:
                cdef = tdef = TorrentDef.load(torrentfilename)
            elif cdef.get_def_type() == 'torrent':
                tdef = cdef
            elif torrentfilename:
                tdef = TorrentDef.load(torrentfilename)
            else:
                tdef = None
                
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            dscfg = defaultDLConfig.copy()
            
            cancelDownload = False
            useDefault = not dscfg.get_show_saveas()
            if not useDefault and not destdir:
                defaultname = correctedFilename
                if not correctedFilename and tdef:
                    defaultname = tdef.get_name_as_unicode()
                    
                dlg = SaveAs(self, tdef, dscfg.get_dest_dir(), defaultname, os.path.join(self.utility.session.get_state_dir(), 'recent_download_history'), selectedFiles)
                dlg.CenterOnParent()
                
                if dlg.ShowModal() == wx.ID_OK:
                    #for multifile we enabled correctedFilenames, use split to remove the filename from the path
                    if tdef and tdef.is_multifile_torrent():
                        destdir, correctedFilename = os.path.split(dlg.GetPath())
                        selectedFiles = dlg.GetSelectedFiles()
                    else:
                        destdir = dlg.GetPath()
                else:
                    cancelDownload = True
                dlg.Destroy()
            
            if not cancelDownload:
                if destdir is not None:
                    dscfg.set_dest_dir(destdir)
                    
                if correctedFilename:
                    dscfg.set_corrected_filename(correctedFilename)
                
                if selectedFiles and len(selectedFiles) == 1:
                    #we should filter files to see if they are all playable
                    videofiles = selectedFiles
                    
                elif tdef and not selectedFiles:
                    videofiles = tdef.get_files(exts=videoextdefaults)
                    
                else:
                    videofiles = []
                
                #disable vodmode if no videofiles
                if vodmode and len(videofiles) == 0:
                    vodmode = False
                
                vodmode = vodmode or cdef.get_live()
                
                selectedFile = None
                if vodmode:
                    print >>sys.stderr, 'MainFrame: startDownload: Starting in VOD mode'
                    if len(videofiles) == 1:
                        selectedFile = videofiles[0]
                    else:
                        selectedFile = None
                    
                    #Swift requires swarmname to be part of the selectedfile
                    if cdef.get_def_type() == 'swift' and tdef:
                        swift_selectedFile = tdef.get_name_as_unicode()+"/"+selectedFile
                    else:
                        swift_selectedFile = selectedFile
                    
                    videoplayer = VideoPlayer.getInstance()
                    result = videoplayer.start_and_play(cdef, dscfg, swift_selectedFile)
                    
                else:
                    if selectedFiles:
                        if cdef.get_def_type() == 'swift' and tdef:
                            swift_selectedFiles = []
                            for selectedFile in selectedFiles:
                                swift_selectedFiles.append(tdef.get_name_as_unicode()+"/"+selectedFile)
                            dscfg.set_selected_files(swift_selectedFiles)
                            
                        else:
                            dscfg.set_selected_files(selectedFiles)
                    
                    print >>sys.stderr, 'MainFrame: startDownload: Starting in DL mode'
                    result = self.utility.session.start_download(cdef, dscfg)
                
                if result:
                    self.show_saved()
                    
                    if monitorSwiftProgress:
                        state_lambda = lambda ds, vodmode=vodmode, torrentfilename=torrentfilename, dscfg=dscfg, selectedFile=selectedFile: self.monitorSwiftProgress(ds, vodmode, torrentfilename, dscfg, selectedFile)
                        result.set_state_callback(state_lambda, getpeerlist=False, delay=15.0)
                        
                
                # store result because we want to store clicklog data
                # right after d#        self.frame.sendButton.Disable()
#        # Disabling the focused button disables keyboard navigation
#        # unless we set the focus to something else - let's put it
#        # on close button
#        self.frame.closeButton.SetFocus() 
#        self.frame.sendButton.SetLabel(_(u'Sending...'))
#        
#        try:
#            from M2Crypto import httpslib, SSL
#            # Try to load the CA certificates for secure SSL.
#            # If we can't load them, the data is hidden from casual observation,
#            # but a man-in-the-middle attack is possible.
#            ctx = SSL.Context()
#            opts = {}
#            if ctx.load_verify_locations('parcels/osaf/framework/certstore/cacert.pem') == 1:
#                ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 9)
#                opts['ssl_context'] = ctx
#            c = httpslib.HTTPSConnection('feedback.osafoundation.org', 443, opts)
#            body = buildXML(self.frame.comments, self.frame.email,
#                            self.frame.sysInfo, self.frame.text)
#            c.request('POST', '/desktop/post/submit', body)
#            response = c.getresponse()
#            
#            if response.status != 200:
#                raise Exception('response.status=' + response.status)
#            c.close()
#        except:
#            self.frame.sendButton.SetLabel(_(u'Failed to send'))
#        else:
#            self.frame.sendButton.SetLabel(_(u'Sent'))
#            self.logReport(body, response.read())ownload was started, then return result

                if clicklog is not None:
                    mypref = self.utility.session.open_dbhandler(NTFY_MYPREFERENCES)
                    mypref.addClicklogToMyPreference(cdef.get_id(), clicklog)

                return result  

        except DuplicateDownloadException:
            # show nice warning dialog
            dlg = wx.MessageDialog(None,
                                   self.utility.lang.get('duplicate_download_msg'),
                                   self.utility.lang.get('duplicate_download_title'),
                                   wx.OK|wx.ICON_ERROR)
            result = dlg.ShowModal()
            dlg.Destroy()
            
            # If there is something on the cmdline, all other torrents start
            # in STOPPED state. Restart
            if cmdline and cdef.get_def_type() == 'torrent':
                dlist = self.utility.session.get_downloads()
                for d in dlist:
                    if d.get_def().get_infohash() == cdef.get_infohash():
                        d.restart()
                        break
        except Exception,e:
            print_exc()
            self.onWarning(e)
Ejemplo n.º 23
0
    def startDownload(self,torrentfilename=None,destdir=None,tdef = None,cmdline=False,clicklog=None,name=None,vodmode=False,doemode=None,fixtorrent=False):

        if DEBUG:
            print >>sys.stderr,"mainframe: startDownload:",torrentfilename,destdir,tdef

        if fixtorrent and torrentfilename:
            self.fixTorrent(torrentfilename)

        try:
            if tdef is None:
                tdef = TorrentDef.load(torrentfilename)
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            dscfg = defaultDLConfig.copy()

            cancelDownload = False
            useDefault = not dscfg.get_show_saveas()
            if not useDefault and not destdir:
                dlg = wx.DirDialog(self, 'Please select a directory where to save %s.'%tdef.get_name())
                dlg.SetPath(dscfg.get_dest_dir())

                if dlg.ShowModal() == wx.ID_OK:
                    destdir = dlg.GetPath()
                else:
                    cancelDownload = True
                dlg.Destroy()

            if not cancelDownload:
                if destdir is not None:
                    dscfg.set_dest_dir(destdir)

                # ProxyService 90s Test_
                if doemode is not None:
                    dscfg.set_doe_mode(doemode)
                    dscfg.set_proxyservice_role(PROXYSERVICE_ROLE_DOE)
                # _ProxyService 90s Test

                videofiles = tdef.get_files(exts=videoextdefaults)
                if vodmode and len(videofiles) == 0:
                    vodmode = False

                if vodmode or tdef.get_live():
                    print >>sys.stderr, 'MainFrame: startDownload: Starting in VOD mode'
                    videoplayer = VideoPlayer.getInstance()
                    result = videoplayer.start_and_play(tdef,dscfg)

                    # 02/03/09 boudewijn: feedback to the user when there
                    # are no playable files in the torrent
                    if not result:
                        dlg = wx.MessageDialog(None,
                                   self.utility.lang.get("invalid_torrent_no_playable_files_msg"),
                                   self.utility.lang.get("invalid_torrent_no_playable_files_title"),
                                   wx.OK|wx.ICON_ERROR)
                        dlg.ShowModal()
                        dlg.Destroy()
                else:
                    print >>sys.stderr, 'MainFrame: startDownload: Starting in DL mode'
                    result = self.utility.session.start_download(tdef,dscfg)

                if result:
                    self.show_saved()

                # store result because we want to store clicklog data
                # right after download was started, then return result
                if clicklog is not None:
                    mypref = self.utility.session.open_dbhandler(NTFY_MYPREFERENCES)
                    mypref.addClicklogToMyPreference(tdef.get_infohash(), clicklog)

                return result

        except DuplicateDownloadException:
            # show nice warning dialog
            dlg = wx.MessageDialog(None,
                                   self.utility.lang.get('duplicate_download_msg'),
                                   self.utility.lang.get('duplicate_download_title'),
                                   wx.OK|wx.ICON_ERROR)
            result = dlg.ShowModal()
            dlg.Destroy()

            # If there is something on the cmdline, all other torrents start
            # in STOPPED state. Restart
            if cmdline:
                dlist = self.utility.session.get_downloads()
                for d in dlist:
                    if d.get_def().get_infohash() == tdef.get_infohash():
                        d.restart()
                        break
        except Exception,e:
            print_exc()
            self.onWarning(e)
Ejemplo n.º 24
0
    def _PostInit(self):
        # Do all init here
        self.guiUtility = GUIUtility.getInstance()
        self.utility = self.guiUtility.utility
        self.params = self.guiUtility.params
        self.utility.frame = self
        self.torrentfeed = None

        title = self.utility.lang.get('title') + \
                " " + \
                self.utility.lang.get('version')

        # Get window size and position from config file
        size, position = self.getWindowSettings()
        style = wx.DEFAULT_FRAME_STYLE | wx.CLIP_CHILDREN

        self.SetSize(size)
        self.SetPosition(position)
        self.SetTitle(title)
        tt = self.GetToolTip()
        if tt is not None:
            tt.SetTip('')

        #wx.Frame.__init__(self, None, ID, title, position, size, style = style)

        self.doneflag = Event()

        dragdroplist = FileDropTarget(self)
        self.SetDropTarget(dragdroplist)

        self.tbicon = None

        # Arno: see ABCPanel
        #self.abc_sb = ABCStatusBar(self,self.utility)
        #self.SetStatusBar(self.abc_sb)
        """
        # Add status bar
        statbarbox = wx.BoxSizer(wx.HORIZONTAL)
        self.sb_buttons = ABCStatusButtons(self,self.utility)
        statbarbox.Add(self.sb_buttons, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 0)
        self.abc_sb = ABCStatusBar(self,self.utility)
        statbarbox.Add(self.abc_sb, 1, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 0)
        #colSizer.Add(statbarbox, 0, wx.ALL|wx.EXPAND, 0)
        self.SetStatusBar(statbarbox)
        """

        try:
            self.SetIcon(self.utility.icon)
        except:
            pass

        # Don't update GUI as often when iconized
        self.GUIupdate = True

        # Start the scheduler before creating the ListCtrl
        #self.utility.queue  = ABCScheduler(self.utility)
        #self.window = ABCPanel(self)
        #self.abc_sb = self.window.abc_sb

        self.oldframe = None
        #self.oldframe = ABCOldFrame(-1, self.params, self.utility)
        #self.oldframe.Refresh()
        #self.oldframe.Layout()
        #self.oldframe.Show(True)

        self.window = self.GetChildren()[0]
        self.window.utility = self.utility
        """
        self.list = ABCList(self.window)
        self.list.Show(False)
        self.utility.list = self.list
        print self.window.GetName()
        self.window.list = self.list
        self.utility.window = self.window
        """
        #self.window.sb_buttons = ABCStatusButtons(self,self.utility)

        #self.utility.window.postponedevents = []

        # Menu Options
        ############################
        #menuBar = ABCMenuBar(self)
        #if sys.platform == "darwin":
        #    wx.App.SetMacExitMenuItemId(wx.ID_CLOSE)
        #self.SetMenuBar(menuBar)

        #self.tb = ABCToolBar(self) # new Tribler gui has no toolbar
        #self.SetToolBar(self.tb)

        self.buddyFrame = None
        self.fileFrame = None
        self.buddyFrame_page = 0
        self.buddyFrame_size = (800, 500)
        self.buddyFrame_pos = None
        self.fileFrame_size = (800, 500)
        self.fileFrame_pos = None

        # Menu Events
        ############################

        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        #        self.Bind(wx.EVT_MENU, self.OnMenuExit, id = wx.ID_CLOSE)

        # leaving here for the time being:
        # wxMSW apparently sends the event to the App object rather than
        # the top-level Frame, but there seemed to be some possibility of
        # change
        self.Bind(wx.EVT_QUERY_END_SESSION, self.OnCloseWindow)
        self.Bind(wx.EVT_END_SESSION, self.OnCloseWindow)

        try:
            self.tbicon = ABCTaskBarIcon(self)
        except:
            print_exc()
        self.Bind(wx.EVT_ICONIZE, self.onIconify)
        self.Bind(wx.EVT_SET_FOCUS, self.onFocus)
        self.Bind(wx.EVT_SIZE, self.onSize)
        self.Bind(wx.EVT_MAXIMIZE, self.onSize)
        #self.Bind(wx.EVT_IDLE, self.onIdle)

        # If the user passed a torrentfile on the cmdline, load it.
        if DEBUG:
            print >> sys.stderr, "abc: wxFrame: params is", self.params

        # Init video player
        self.videoFrame = None
        feasible = return_feasible_playback_modes(self.utility.getPath())
        if PLAYBACKMODE_INTERNAL in feasible:
            # This means vlc is available
            from Tribler.Video.EmbeddedPlayer import VideoFrame
            iconpath = os.path.join(self.utility.getPath(), 'Tribler',
                                    'Images', 'tribler.ico')
            logopath = os.path.join(self.utility.getPath(), 'Tribler',
                                    'Images', 'logoTribler.png')
            self.videoFrame = VideoFrame(self, 'Tribler Video', iconpath,
                                         logopath)

            #self.videores = xrc.XmlResource("Tribler/vwxGUI/MyPlayer.xrc")
            #self.videoframe = self.videores.LoadFrame(None, "MyPlayer")
            #self.videoframe.Show()

            videoplayer = VideoPlayer.getInstance()
            videoplayer.set_parentwindow(self.videoFrame)
        else:
            videoplayer = VideoPlayer.getInstance()
            videoplayer.set_parentwindow(self)

        sys.stdout.write('GUI Complete.\n')

        self.Show(True)

        # Just for debugging: add test permids and display top 5 peers from which the most is downloaded in bartercastdb
        #        bartercastdb = BarterCastDBHandler.getInstance()
        #        mypermid = bartercastdb.my_permid
        #
        #        if DEBUG:
        #
        #            top = bartercastdb.getTopNPeers(5)['top']
        #
        #            print 'My Permid: ', show_permid(mypermid)
        #
        #            print 'Top 5 BarterCast peers:'
        #            print '======================='
        #
        #            i = 1
        #            for (permid, up, down) in top:
        #                print '%2d: %15s  -  %10d up  %10d down' % (i, bartercastdb.getName(permid), up, down)
        #                i += 1

        # Check to see if ABC is associated with torrents
        #######################################################
        if (sys.platform == 'win32'):
            if self.utility.config.Read('associate', "boolean"):
                if self.utility.regchecker and not self.utility.regchecker.testRegistry(
                ):
                    dialog = RegCheckDialog(self)
                    dialog.ShowModal()
                    dialog.Destroy()

        self.checkVersion()

        wx.CallAfter(self.startCMDLineTorrent)