示例#1
0
    def tearDown(self):
        sleep(2)
        self.completed.sort()
        if self.completed != range(self.ntasks):
            if DEBUG:
                print "test failed", self.completed
            self.assert_(False)

        self.guiserver.shutdown()
        GUITaskQueue.delInstance()
示例#2
0
class TestGUITaskQueue(unittest.TestCase):

    def setUp(self):
        self.ntasks = 0
        self.completed = []
        self.guiserver = GUITaskQueue()

    def tearDown(self):
        sleep(2)
        self.completed.sort()
        if self.completed != range(self.ntasks):
            if DEBUG:
                print "test failed", self.completed
            self.assert_(False)

        self.guiserver.shutdown()
        GUITaskQueue.delInstance()

    def test_simple(self):
        self.ntasks = 1

        self.guiserver.add_task(lambda: self.task(0), 0)

    def test_more(self):
        self.ntasks = 10

        for i in range(self.ntasks):
            # lambda functions are evil, this is not the same as lambda:task(i)
            self.guiserver.add_task(self.define_task(i), 0)

    def test_delay(self):
        self.ntasks = 1

        self.guiserver.add_task(lambda: self.task(0), 3)
        if DEBUG:
            print "test: sleeping 5 secs so tasks get executed"
        sleep(5)

    def test_delay2(self):
        self.ntasks = 2

        self.guiserver.add_task(lambda: self.task(1), 3)
        self.guiserver.add_task(lambda: self.task(0), 1)
        if DEBUG:
            print "test: sleeping 5 secs so tasks get executed"
        sleep(5)

    def define_task(self, num):
        return lambda: self.task(num)

    def task(self, num):
        if DEBUG:
            print "Running task", num
        self.completed.append(num)
示例#3
0
    def __init__(self, grid, utility):
        self.session = utility.session
        
        self.peer_db = self.session.open_dbhandler(NTFY_PEERS)
        self.torrent_db = self.session.open_dbhandler(NTFY_TORRENTS)
        self.friend_db = self.session.open_dbhandler(NTFY_FRIENDS)
        
        self.state = None
        self.total_items = 0
        self.page = 0
        self.grid = grid
        self.data = []
        self.callbacks_disabled = False
        self.download_states_callback_set = False
        self.dslist = []
        
        self.torrentsearch_manager = utility.guiUtility.torrentsearch_manager
        self.torrentsearch_manager.register(self.torrent_db,self)

        self.peersearch_manager = utility.guiUtility.peersearch_manager
        self.peersearch_manager.register(self.peer_db,self.friend_db,self)
        self.guiserver = GUITaskQueue.getInstance()
        
        self.refresh_rate = 3   # how often to refresh the GUI in seconds
        
        self.cache_numbers = {}
        self.cache_ntorrent_interval = 5
        self.last_ntorrent_cache = 0
        self.cache_npeer_interval = 3
        self.last_npeer_cache = 0
示例#4
0
    def __init__(self, grid, utility):
        self.session = utility.session

        self.peer_db = self.session.open_dbhandler(NTFY_PEERS)
        self.torrent_db = self.session.open_dbhandler(NTFY_TORRENTS)
        self.friend_db = self.session.open_dbhandler(NTFY_FRIENDS)

        self.state = None
        self.total_items = 0
        self.page = 0
        self.grid = grid
        self.data = []
        self.callbacks_disabled = False
        self.download_states_callback_set = False
        self.dslist = []

        self.torrentsearch_manager = utility.guiUtility.torrentsearch_manager
        self.torrentsearch_manager.register(self.torrent_db, self)

        self.peersearch_manager = utility.guiUtility.peersearch_manager
        self.peersearch_manager.register(self.peer_db, self.friend_db, self)
        self.guiserver = GUITaskQueue.getInstance()

        self.refresh_rate = 3  # how often to refresh the GUI in seconds

        self.cache_numbers = {}
        self.cache_ntorrent_interval = 5
        self.last_ntorrent_cache = 0
        self.cache_npeer_interval = 3
        self.last_npeer_cache = 0
示例#5
0
 def __init__(self):
     if GUIDBProducer.__single:
         raise RuntimeError, "GuiDBProducer is singleton"
     
     #Lets get the reference to the shared database_thread
     from Tribler.Core.Session import Session
     if Session.has_instance():
         self.database_thread = Session.get_instance().lm.database_thread
     else:
         raise RuntimeError('Session not initialized')
     
     self.guitaskqueue = GUITaskQueue.getInstance()
     
     #Lets get a reference to utility
     from Tribler.Main.vwxGUI.GuiUtility import GUIUtility
     if GUIUtility.hasInstance():
         self.utility = GUIUtility.getInstance().utility
     else:
         Utility = namedtuple('Utility', ['abcquitting',])
         self.utility = Utility(False)
     
     self.uIds = set()
     self.uIdsLock = Lock()
     
     self.nrCallbacks = {}
示例#6
0
 def __init__(self,guiUtility):
     if TorrentManager.__single:
         raise RuntimeError, "TorrentSearchGridManager is singleton"
     TorrentManager.__single = self
     self.guiUtility = guiUtility
     
     # Contains all matches for keywords in DB, not filtered by category
     self.hits = []
     
     # Remote results for current keywords
     self.remoteHits = {}
     
     # For asking for a refresh when remote results came in
     self.gridmgr = None
     self.guiserver = GUITaskQueue.getInstance()
     
     self.searchkeywords = []
     self.rerankingStrategy = DefaultTorrentReranker()
     self.oldsearchkeywords = []
     
     self.filteredResults = 0
     
     self.bundler = Bundler()
     self.bundle_mode = None
     self.category = Category.getInstance()
    def __init__(self,guiUtility):
        if TorrentManager.__single:
            raise RuntimeError, "TorrentSearchGridManager is singleton"
        TorrentManager.__single = self
        self.guiUtility = guiUtility
        
        # Contains all matches for keywords in DB, not filtered by category
        self.hits = []
        
        # Remote results for current keywords
        self.remoteHits = {}
        
        #current progress of download states
        self.cache_progress = {}
        
        # For asking for a refresh when remote results came in
        self.gridmgr = None
        self.guiserver = GUITaskQueue.getInstance()
        
        # Gui callbacks
        self.gui_callback = []

        self.searchkeywords = {'filesMode':[], 'libraryMode':[]}
        self.rerankingStrategy = {'filesMode':DefaultTorrentReranker(), 'libraryMode':DefaultTorrentReranker()}
        self.oldsearchkeywords = {'filesMode':[], 'libraryMode':[]} # previous query
        
        self.filteredResults = 0
        self.category = Category.getInstance()
        
        # 09/10/09 boudewijn: CallLater does not accept zero as a
        # delay. the value needs to be a positive integer.
        self.user_download_choice = UserDownloadChoice.get_singleton()
示例#8
0
            def start():
                if self.combineRadio.GetValue():
                    self.progressDlg = wx.ProgressDialog("Creating new .torrents", "Please wait while Tribler is creating your .torrents.\nThis could take a while due to creating the required hashes.", maximum=max, parent=self, style = wx.PD_APP_MODAL | wx.PD_AUTO_HIDE)
                else:
                    self.progressDlg = wx.ProgressDialog("Creating new .torrents", "Please wait while Tribler is creating your .torrents.\nThis could take a while due to creating the required hashes.", maximum=max, parent=self, style = wx.PD_CAN_ABORT | wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_AUTO_HIDE)
                self.progressDlg.Pulse()
                self.progressDlg.cur = 0

                self.guiserver = GUITaskQueue.getInstance()
                self.guiserver.add_task(create_torrents)
示例#9
0
            def start():
                if self.combineRadio.GetValue():
                    self.progressDlg = wx.ProgressDialog("Creating new .torrents", "Please wait while Tribler is creating your .torrents.\nThis could take a while due to creating the required hashes.", maximum=max, parent=self, style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE)
                else:
                    self.progressDlg = wx.ProgressDialog("Creating new .torrents", "Please wait while Tribler is creating your .torrents.\nThis could take a while due to creating the required hashes.", maximum=max, parent=self, style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_AUTO_HIDE)
                self.progressDlg.Pulse()
                self.progressDlg.cur = 0

                self.guiserver = GUITaskQueue.getInstance()
                self.guiserver.add_task(create_torrents)
示例#10
0
    def __init__ (self, parent, choices = [], entrycallback = None, selectcallback = None, **therest):
        '''
            Constructor works just like wx.TextCtrl except you can pass in a list of choices. 
            You can also change the choice list at any time by calling SetChoices. 
        ''' 
        if therest.has_key('style'): 
            therest['style']=wx.TE_PROCESS_ENTER|therest['style'] 
        else:
            therest['style']= wx.TE_PROCESS_ENTER 
    
        wx.TextCtrl.__init__(self , parent , **therest)

        # we need the GUITaskQueue to offload database activity, otherwise we may lock the GUI
        self.text = ""
        self.guiserver = GUITaskQueue.getInstance()
        
        self.screenheight = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)
         
        self.dropdown = wx.PopupWindow(self)
        self.dropdown.SetBackgroundColour(wx.WHITE)
        sizer = wx.BoxSizer()
        
        self.dropdownlistbox = AutoWidthListCtrl(self.dropdown, style=wx.LC_REPORT | wx.BORDER_NONE | wx.LC_SINGLE_SEL | wx.LC_NO_HEADER) 
        self.dropdownlistbox.Bind(wx.EVT_LEFT_DOWN, self.ListClick)
        self.dropdownlistbox.Bind(wx.EVT_LEFT_DCLICK, self.ListClick)
        sizer.Add(self.dropdownlistbox, 1, wx.EXPAND|wx.ALL, 3)
        self.dropdown.SetSizer(sizer)
        
        self.SetChoices(choices)
        self.entrycallback = entrycallback
        self.selectcallback = selectcallback
        
        gp = self 
        while (gp <> None) : 
            gp.Bind (wx.EVT_MOVE , self.ControlChanged, gp)
            gp.Bind (wx.EVT_SIZE , self.ControlChanged, gp)
            gp = gp.GetParent()
            
        self.Bind (wx.EVT_KILL_FOCUS, self.ControlChanged, self) 
        self.Bind (wx.EVT_TEXT , self.EnteredText, self) 
        self.Bind (wx.EVT_KEY_DOWN , self.KeyDown, self) 
        self.Bind (wx.EVT_LEFT_DOWN , self.ClickToggleDown, self) 
        self.Bind (wx.EVT_LEFT_UP , self.ClickToggleUp, self) 
        self.dropdown.Bind (wx.EVT_LISTBOX , self.ListItemSelected, self.dropdownlistbox)
示例#11
0
    def __init__(self,
                 cols,
                 subPanelHeight,
                 orientation='horizontal',
                 viewmode='thumbnails'):
        self.initReady = False
        self.data = None
        self.detailPanel = None
        self.orientation = orientation
        self.subPanelClass = None
        self.items = 0  #number of items that are currently visible
        self.currentRows = 0
        self.sizeMode = 'auto'
        self.columnHeader = None
        self.topMargin = 5
        self.panels = []
        self.viewmode = viewmode
        self.guiUtility = GUIUtility.getInstance()
        self.utility = self.guiUtility.utility
        self.gridManager = GridManager(self, self.utility)
        pre = wx.PrePanel()
        # the Create step is done by XRC.
        self.PostCreate(pre)
        self.Bind(wx.EVT_WINDOW_CREATE, self.OnCreate)

        if type(cols) == int:
            self.cols = cols
            self.columnTypes = None
            self.subPanelHeight = subPanelHeight
        else:
            self.columnTypes = cols
            self.subPanelHeights = subPanelHeight
            if self.viewmode == 'thumbnails':
                self.cols = cols[0]
                self.subPanelHeight = self.subPanelHeights[0]
            elif self.viewmode == 'list':
                self.cols = cols[1]
                self.subPanelHeight = self.subPanelHeights[1]
            else:
                raise Exception('unknown viewmode: %s' % self.viewmode)

        self.superpeer_db = SuperPeerDBHandler.getInstance()
        self.torrentfeed = TorrentFeedThread.getInstance()
        self.guiserver = GUITaskQueue.getInstance()
 def __init__(self):
     if GUIDBProducer.__single:
         raise RuntimeError, "GuiDBProducer is singleton"
     GUIDBProducer.__single = self
     
     #Lets get the reference to the shared database_thread
     from Tribler.Core.Session import Session
     self.database_thread = Session.get_instance().lm.database_thread
     
     self.guitaskqueue = GUITaskQueue.getInstance()
     
     #Lets get a reference to utility
     from Tribler.Main.vwxGUI.GuiUtility import GUIUtility
     self.utility = GUIUtility.getInstance().utility
     
     self.uIds = set()
     self.uIdsLock = Lock()
     
     self.nrCallbacks = {}
示例#13
0
    def __init__(self):
        if GUIDBProducer.__single:
            raise RuntimeError, "GuiDBProducer is singleton"
        GUIDBProducer.__single = self

        #Lets get the reference to the shared database_thread
        from Tribler.Core.Session import Session
        self.database_thread = Session.get_instance().lm.database_thread

        self.guitaskqueue = GUITaskQueue.getInstance()

        #Lets get a reference to utility
        from Tribler.Main.vwxGUI.GuiUtility import GUIUtility
        self.utility = GUIUtility.getInstance().utility

        self.uIds = set()
        self.uIdsLock = Lock()

        self.nrCallbacks = {}
示例#14
0
    def __init__(self, database_thread):
        if GUIDBProducer.__single:
            raise RuntimeError("GuiDBProducer is singleton")

        self.database_thread = database_thread
        self.guitaskqueue = GUITaskQueue.getInstance()

        # Lets get a reference to utility
        from Tribler.Main.vwxGUI.GuiUtility import GUIUtility
        if GUIUtility.hasInstance():
            self.utility = GUIUtility.getInstance().utility
        else:
            Utility = namedtuple('Utility', ['abcquitting', ])
            self.utility = Utility(False)

        self.uIds = set()
        self.uIdsLock = Lock()

        self.nrCallbacks = {}
示例#15
0
 def __init__(self, cols, subPanelHeight, orientation='horizontal', viewmode = 'thumbnails'):
     self.initReady = False
     self.data = None
     self.detailPanel = None
     self.orientation = orientation
     self.subPanelClass = None
     self.items = 0 #number of items that are currently visible 
     self.currentRows = 0
     self.sizeMode = 'auto'
     self.columnHeader = None
     self.topMargin = 5
     self.panels = []
     self.viewmode = viewmode
     self.guiUtility = GUIUtility.getInstance()
     self.utility = self.guiUtility.utility
     self.gridManager = GridManager(self, self.utility)
     pre = wx.PrePanel()
     # the Create step is done by XRC.
     self.PostCreate(pre)
     self.Bind(wx.EVT_WINDOW_CREATE, self.OnCreate)
     
     if type(cols) == int:
         self.cols = cols
         self.columnTypes = None
         self.subPanelHeight = subPanelHeight
     else:
         self.columnTypes = cols
         self.subPanelHeights = subPanelHeight
         if self.viewmode == 'thumbnails':
             self.cols = cols[0]
             self.subPanelHeight = self.subPanelHeights[0]
         elif self.viewmode == 'list':
             self.cols = cols[1]
             self.subPanelHeight = self.subPanelHeights[1]
         else:
             raise Exception('unknown viewmode: %s' % self.viewmode)
             
         
     self.superpeer_db = SuperPeerDBHandler.getInstance()
     self.torrentfeed = TorrentFeedThread.getInstance()
     self.guiserver = GUITaskQueue.getInstance()
示例#16
0
    def __init__(self, database_thread):
        if GUIDBProducer.__single:
            raise RuntimeError("GuiDBProducer is singleton")

        self.database_thread = database_thread
        self.guitaskqueue = GUITaskQueue.getInstance()

        # Lets get a reference to utility
        from Tribler.Main.vwxGUI.GuiUtility import GUIUtility
        if GUIUtility.hasInstance():
            self.utility = GUIUtility.getInstance().utility
        else:
            Utility = namedtuple('Utility', [
                'abcquitting',
            ])
            self.utility = Utility(False)

        self.uIds = set()
        self.uIdsLock = Lock()

        self.nrCallbacks = {}
示例#17
0
 def __init__(self,guiUtility):
     if LibraryManager.__single:
         raise RuntimeError, "LibraryManager is singleton"
     LibraryManager.__single = self
     self.guiUtility = guiUtility
     
     # Contains all matches for keywords in DB, not filtered by category
     self.hits = []
     
     #current progress of download states
     self.cache_progress = {}
     
     self.rerankingStrategy = DefaultTorrentReranker()
     
     # For asking for a refresh when remote results came in
     self.gridmgr = None
     self.guiserver = GUITaskQueue.getInstance()
     
     # Gui callbacks
     self.gui_callback = []
     
     self.user_download_choice = UserDownloadChoice.get_singleton()
示例#18
0
 def __init__(self,guiUtility):
     if ChannelSearchGridManager.__single:
         raise RuntimeError, "ChannelSearchGridManager is singleton"
     ChannelSearchGridManager.__single = self
     self.guiUtility = guiUtility
     self.guiserver = GUITaskQueue.getInstance()
     
     # Contains all matches for keywords in DB, not filtered by category
     self.hits = {}
     
     self.searchmgr = None
     self.channelcast_db = None
     self.pref_db = None # Nic: for rerankers
     self.mypref_db = None
     self.search_db = None
     
     # For asking for a refresh when remote results came in
     self.gridmgr = None
     
     self.searchkeywords = []
     self.oldsearchkeywords = []
     
     self.category = Category.getInstance()
示例#19
0
    def __init__(self, parent, keyTypedFun = None):

        global TORRENTPANEL_BACKGROUND
        
        wx.Panel.__init__(self, parent, -1)
        self.guiUtility = GUIUtility.getInstance()
        self.utility = self.guiUtility.utility
        self.parent = parent
        self.guiserver = parent.guiserver
        self.triblerGrey = wx.Colour(128,128,128)
        
        #self.statusTorrent = TorrentStatus(self)
        
        self.listItem = True # library always in listmode
        self.data = None
        self.status = None
        self.rightMouse = None
        self.datacopy = None
        self.titleLength = 16 # num characters
        self.vodMode = False
        self.selected = False
        self.warningMode = False
        self.oldCategoryLabel = None
        self.torrentDetailsFrame = None
        self.metadatahandler = MetadataHandler.getInstance()
        self.addComponents()
            
        #self.Bind(wx.EVT_RIGHT_DOWN, self.rightMouseButton)             
        
        self.cache_progress = {}
        self.gui_server = GUITaskQueue.getInstance()
        
        self.SetMinSize((-1, 22))
        self.selected = False
        self.Show()
        self.Refresh()
        self.Layout()
    def __init__ (self, parent, entrycallback = None, selectcallback = None, **therest):
        '''
            Constructor works just like wx.TextCtrl
        ''' 
        if therest.has_key('style'): 
            therest['style']=wx.TE_PROCESS_ENTER|therest['style'] 
        else:
            therest['style']= wx.TE_PROCESS_ENTER 
    
        wx.TextCtrl.__init__(self , parent , **therest)

        # we need the GUITaskQueue to offload database activity, otherwise we may lock the GUI
        self.text = ""
        self.choices = []
        self.guiserver = GUITaskQueue.getInstance()
        
        self.screenheight = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)
         
        self.dropdown = wx.PopupWindow(self)
        self.dropdown.SetBackgroundColour(DEFAULT_BACKGROUND)
        sizer = wx.BoxSizer()
        
        self.dropdownlistbox = AutoWidthListCtrl(self.dropdown, style=wx.LC_REPORT | wx.BORDER_NONE | wx.LC_SINGLE_SEL | wx.LC_NO_HEADER) 
        self.dropdownlistbox.Bind(wx.EVT_LEFT_DOWN, self.ListClick)
        self.dropdownlistbox.Bind(wx.EVT_LEFT_DCLICK, self.ListClick)
        sizer.Add(self.dropdownlistbox, 1, wx.EXPAND|wx.ALL, 3)
        self.dropdown.SetSizer(sizer)
        
        self.entrycallback = entrycallback
        self.selectcallback = selectcallback
        
        self.Bind (wx.EVT_KILL_FOCUS, self.ControlChanged, self)
        self.Bind (wx.EVT_TEXT , self.EnteredText, self)
        self.Bind (wx.EVT_KEY_DOWN , self.KeyDown, self)
        
        self.dropdown.Bind(wx.EVT_LISTBOX, self.ListItemSelected, self.dropdownlistbox)
示例#21
0
    def __init__(self, parent, title, background):
        wx.Panel.__init__(self, parent)
        
        self.guiutility = GUIUtility.getInstance()
        self.guiserver = GUITaskQueue.getInstance()
        self.SetBackgroundColour(background)
     
        vSizer = wx.BoxSizer(wx.VERTICAL)

        self.header = self.CreateHeader()
        self.header.SetTitle(title)
        self.header.SetBackgroundColour(background)
        vSizer.Add(self.header, 0, wx.EXPAND)
        
        self.panel = self.CreatePanel()
        if self.panel:
            vSizer.Add(self.panel, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 1)
        
        self.footer = self.CreateFooter()
        self.footer.SetBackgroundColour(background)
        vSizer.Add(self.footer, 0, wx.EXPAND)
        
        self.SetSizer(vSizer)
        self.Layout()
 def checkNewVersion(self):
     # delegate to GUIServer
     guiserver = GUITaskQueue.getInstance()
     guiserver.add_task(self.guiserver_checkVersion, 0)
示例#23
0
 def setUp(self):
     self.ntasks = 0
     self.completed = []
     self.guiserver = GUITaskQueue()
 def checkNewVersion(self):
     # delegate to GUIServer
     guiserver = GUITaskQueue.getInstance()
     guiserver.add_task(self.guiserver_checkVersion,0)
示例#25
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
示例#26
0
 def OnOk(self, event):
     max = 1 if self.combineRadio.GetValue() else len(self.selectedPaths)
     
     if self.toChannel:
         dlg = wx.MessageDialog(self, "This will add %d new .torrents to this Channel.\nDo you want to continue?"%max, "Are you sure?", style = wx.YES_NO|wx.ICON_QUESTION)
     else:
         dlg = wx.MessageDialog(self, "This will create %d new .torrents.\nDo you want to continue?"%max, "Are you sure?", style = wx.YES_NO|wx.ICON_QUESTION)
     
     if dlg.ShowModal() == wx.ID_YES:
         dlg.Destroy()
         
         self.progressDlg = wx.ProgressDialog("Creating new .torrents", "Please wait while Tribler is creating your .torrents.\nThis could take a while due to creating the required hashes.", maximum=max, parent=self, style = wx.PD_CAN_ABORT | wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_AUTO_HIDE)
         self.progressDlg.cur = 0
         
         params = {}
         params['comment'] = self.commentList.GetValue()
         params['created by'] = '%s version: %s'%(self.guiutility.utility.lang.get('title'), self.guiutility.utility.lang.get('version'))
         
         trackers = self.trackerList.GetValue()
         trackers = [tracker for tracker in trackers.split('\n') if tracker]
         
         for tracker in trackers:
             self.trackerHistory.AddFileToHistory(tracker)
         self.trackerHistory.Save(self.config)
         self.config.Flush()
         
         params['announce'] = trackers[0]
         params['announce-list'] = [trackers]
         
         params['nodes'] = False
         params['httpseeds'] = False
         params['encoding'] = False
         params['makehash_md5'] = False
         params['makehash_crc32'] = False
         params['makehash_sha1'] = True
         params['createmerkletorrent'] = False
         params['torrentsigkeypairfilename'] = False
         params['thumb'] = False
         
         piece_length_list = [0, 2**21, 2**20, 2**19, 2**18, 2**17, 2**16, 2**15]
         params['piece length'] = piece_length_list[self.pieceChoice.GetSelection()]
         
         def do_gui():
             if self.cancelEvent.isSet():
                 self.OnCancel(event)
             else:
                 self.EndModal(wx.ID_OK)
         
         def create_torrents():
             if self.combineRadio.GetValue():
                 make_meta_file(self.selectedPaths, params, self.cancelEvent, None, self._torrentCreated)
             else:
                 for path in self.selectedPaths:
                     make_meta_file([path], params, self.cancelEvent, None, self._torrentCreated)
                     
             wx.CallAfter(do_gui)
                     
         self.guiserver = GUITaskQueue.getInstance()
         self.guiserver.add_task(create_torrents)
         
     else:
         dlg.Destroy()
示例#27
0
    def __init__(self, parent, channelonly, internalvideo, progress):
        # Do all init here
        self.guiUtility = GUIUtility.getInstance()
        self.guiUtility.frame = self
        self.utility = self.guiUtility.utility
        self.params = self.guiUtility.params
        self.utility.frame = self
        self.torrentfeed = None
        self.category = Category.getInstance()
        self.shutdown_and_upgrade_notes = None
        
        self.guiserver = GUITaskQueue.getInstance()
        
        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_DIALOG_STYLE|wx.MINIMIZE_BOX|wx.MAXIMIZE_BOX|wx.RESIZE_BORDER|wx.NO_FULL_REPAINT_ON_RESIZE|wx.CLIP_CHILDREN
            
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, position, size, style)
        if sys.platform == 'linux2':
            font = self.GetFont()
            if font.GetPointSize() > 9:
                font.SetPointSize(9)
                self.SetFont(font)
                
        self.Freeze()
        self.SetDoubleBuffered(True)
        self.SetBackgroundColour(DEFAULT_BACKGROUND)
        
        themeColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
        r, g, b = themeColour.Get(False)
        if r > 190 or g > 190 or b > 190: #Grey == 190,190,190
            self.SetForegroundColour(wx.BLACK)
            
        #Create all components        
        progress('Creating panels')
        if not channelonly:
            self.top_bg = TopSearchPanel(self)
            
            self.home = Home(self)
        
            #build channelselector panel
            self.channelselector = wx.BoxSizer(wx.VERTICAL)
            self.channelcategories = ChannelCategoriesList(self)
            quicktip = HtmlWindow(self)
            quicktip.SetBorders(2)
            self.channelcategories.SetQuicktip(quicktip)

            self.channelselector.Add(self.channelcategories, 0, wx.EXPAND)
            self.channelselector.Add(quicktip, 1, wx.EXPAND)
            self.channelselector.AddStretchSpacer()
            self.channelselector.ShowItems(False)
        
            self.searchlist = SearchList(self)
            self.searchlist.Show(False)
            
            self.channellist = ChannelList(self)
            self.channellist.Show(False)
        else:
            self.top_bg = None
            
            self.guiUtility.guiPage = 'selectedchannel'
            self.home = None
            self.channelselector = None
            self.channelcategories = None
            self.searchlist = None
            self.channellist = None
        
        self.stats = Stats(self)
        self.stats.Show(False)
        self.selectedchannellist = SelectedChannelList(self)
        self.selectedchannellist.Show(bool(channelonly))
        self.playlist = Playlist(self)
        self.playlist.Show(False)
        
        self.managechannel = ManageChannel(self)
        self.managechannel.Show(False)
        self.librarylist = LibraryList(self)
        self.librarylist.Show(False)
        
        if internalvideo:
            self.videoparentpanel = wx.Panel(self)
            self.videoparentpanel.Hide()
        else:
            self.videoparentpanel = None
        
        progress('Positioning')
        
        if not channelonly:
            #position all elements            
            vSizer = wx.BoxSizer(wx.VERTICAL)
            
            vSizer.Add(self.top_bg, 0, wx.EXPAND)
            hSizer = wx.BoxSizer(wx.HORIZONTAL)
            vSizer.Add(hSizer, 1, wx.EXPAND|wx.ALL, 5)
            
            hSizer.Add(self.home, 1, wx.EXPAND|wx.ALL, 20)
            hSizer.Add(self.stats, 1, wx.EXPAND|wx.ALL, 20)
            hSizer.Add(self.channelselector, 0, wx.EXPAND|wx.RIGHT, 5)
            hSizer.Add(self.channellist, 1, wx.EXPAND)
            hSizer.Add(self.searchlist, 1, wx.EXPAND)
            
        else:
            vSizer = wx.BoxSizer(wx.VERTICAL) 
            hSizer = wx.BoxSizer(wx.HORIZONTAL)
            vSizer.Add(hSizer, 1, wx.EXPAND|wx.ALL, 5)
            
            self.top_bg = TopSearchPanelStub()
            
        hSizer.Add(self.selectedchannellist, 1, wx.EXPAND)
        hSizer.Add(self.playlist, 1, wx.EXPAND)
        hSizer.Add(self.managechannel, 1, wx.EXPAND)
        hSizer.Add(self.librarylist, 1, wx.EXPAND)
        
        if self.videoparentpanel:
            hSizer.Add(self.videoparentpanel, 0, wx.LEFT, 5)
        
        self.SetSizer(vSizer)
        
        #set sizes
        if not channelonly:
            self.top_bg.SetMinSize((-1,70))
            self.channelselector.SetMinSize((110,-1))
            quicktip.SetMinSize((-1,300))
        
        if self.videoparentpanel:
            self.videoparentpanel.SetSize((320,500))
        
        self.SRstatusbar = SRstatusbar(self)
        self.SetStatusBar(self.SRstatusbar)
        
        if not channelonly:
            self.channelcategories.Select(1, False)
        
        def preload_data():
            if not channelonly:
                self.guiUtility.showChannelCategory('Popular', False)
            self.guiUtility.showLibrary(False)
            
        wx.CallLater(1500, preload_data)
        if channelonly:
            self.guiUtility.showChannelFromDispCid(channelonly)
            if not self.guiUtility.useExternalVideo:
                self.guiUtility.ShowPlayer(True)

        if sys.platform != 'darwin':
            dragdroplist = FileDropTarget(self)
            self.SetDropTarget(dragdroplist)
        try:
            self.SetIcon(self.utility.icon)
        except:
            pass
        
        self.tbicon = None        
        try:
            self.tbicon = ABCTaskBarIcon(self)
        except:
            print_exc()

        # Don't update GUI as often when iconized
        self.GUIupdate = True
        self.window = self.GetChildren()[0]
        self.window.utility = self.utility

        progress('Binding events')        
        # Menu Events 
        ############################
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        # 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)
        self.Bind(wx.EVT_ICONIZE, self.onIconify)
        self.Bind(wx.EVT_SIZE, self.onSize)
        self.Bind(wx.EVT_MAXIMIZE, self.onSize)
        
        findId = wx.NewId()
        quitId = wx.NewId()
        nextId = wx.NewId()
        prevId = wx.NewId()
        self.Bind(wx.EVT_MENU, self.OnFind, id = findId)
        self.Bind(wx.EVT_MENU, lambda event: self.Close(), id = quitId)
        self.Bind(wx.EVT_MENU, self.OnNext, id = nextId)
        self.Bind(wx.EVT_MENU, self.OnPrev, id = prevId)
        
        accelerators = [(wx.ACCEL_CTRL, ord('f'), findId)]
        accelerators.append((wx.ACCEL_CTRL, wx.WXK_TAB, nextId))
        accelerators.append((wx.ACCEL_CTRL|wx.ACCEL_SHIFT, wx.WXK_TAB, prevId))
        if sys.platform == 'linux2':
            accelerators.append((wx.ACCEL_CTRL, ord('q'), quitId))
            accelerators.append((wx.ACCEL_CTRL, ord('/'), findId))
        self.SetAcceleratorTable(wx.AcceleratorTable(accelerators))

        # Init video player
        sys.stdout.write('GUI Complete.\n')
        self.Thaw()
        self.ready = True
        
        # Just for debugging: add test permids and display top 5 peers from which the most is downloaded in bartercastdb
#        bartercastdb = self.utility.session.open_dbhandler(NTFY_BARTERCAST)
#        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
        
        
        def post():
            self.checkVersion()
            self.startCMDLineTorrent()

        # If the user passed a torrentfile on the cmdline, load it.
        wx.CallAfter(post)
示例#28
0
    def OnOk(self, event):
        #            if self.specifyNames.GetValue():
        #                dlg = wx.Dialog(self, -1, 'Please correct the names for the torrents.', size=(750,450))
        #                sizer = wx.BoxSizer(wx.VERTICAL)
        #                header = wx.StaticText(dlg, -1, 'Please modify the names for the .torrents.')
        #
        #                _set_font(header, fontweight=wx.FONTWEIGHT_BOLD)
        #                sizer.Add(header, 0, wx.EXPAND|wx.BOTTOM, 3)
        #
        #                flexSizer =  wx.FlexGridSizer(2,2,3,3)
        #                controls = []
        #                for name in names:
        #                    flexSizer.Add(wx.StaticText(dlg, -1, name), 0, wx.ALIGN_CENTER_VERTICAL)
        #                    control = wx.TextCtrl(dlg,-1, name)
        #                    control.SetMinSize((300,-1))
        #                    flexSizer.Add(control, 1, wx.EXPAND)
        #                    controls.append(control)
        #
        #                sizer.Add(flexSizer, 1, wx.EXPAND|wx.BOTTOM, 3)
        #
        #                cancel = wx.Button(dlg, wx.ID_CANCEL)
        #                ok = wx.Button(dlg, wx.ID_OK)
        #
        #                bSizer = wx.StdDialogButtonSizer()
        #                bSizer.AddButton(cancel)
        #                bSizer.AddButton(ok)
        #                bSizer.Realize()
        #                sizer.Add(bSizer, 0, wx.EXPAND|wx.BOTTOM, 3)
        #
        #                bsizer = wx.BoxSizer()
        #                bsizer.Add(sizer, 1, wx.EXPAND|wx.ALL, 10)
        #                dlg.SetSizerAndFit(bsizer)
        #
        #                if dlg.ShowModal() == wx.ID_OK:
        #                    for i, control in enumerate(controls):
        #                        names[i] = control.GetValue()
        #                    dlg.Destroy()
        #                else:
        #                    dlg.Destroy()
        #                    return

        max = 1 if self.combineRadio.GetValue() else len(self.selectedPaths)
        if self.toChannel:
            dlg = wx.MessageDialog(
                self,
                "This will add %d new .torrents to this Channel.\nDo you want to continue?" % max,
                "Are you sure?",
                style=wx.YES_NO | wx.ICON_QUESTION,
            )
        else:
            dlg = wx.MessageDialog(
                self,
                "This will create %d new .torrents.\nDo you want to continue?" % max,
                "Are you sure?",
                style=wx.YES_NO | wx.ICON_QUESTION,
            )

        if dlg.ShowModal() == wx.ID_YES:
            dlg.Destroy()

            self.progressDlg = wx.ProgressDialog(
                "Creating new .torrents",
                "Please wait while Tribler is creating your .torrents.\nThis could take a while due to creating the required hashes.",
                maximum=max,
                parent=self,
                style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_AUTO_HIDE,
            )
            self.progressDlg.cur = 0

            params = {}
            params["comment"] = self.commentList.GetValue()
            params["created by"] = "%s version: %s" % (
                self.guiutility.utility.lang.get("title"),
                self.guiutility.utility.lang.get("version"),
            )

            trackers = self.trackerList.GetValue()
            trackers = [tracker for tracker in trackers.split("\n") if tracker]

            for tracker in trackers:
                self.trackerHistory.AddFileToHistory(tracker)
            self.trackerHistory.Save(self.config)
            self.config.Flush()

            params["announce"] = trackers[0]
            params["announce-list"] = [trackers]

            params["nodes"] = False
            params["httpseeds"] = False
            params["encoding"] = False
            params["makehash_md5"] = False
            params["makehash_crc32"] = False
            params["makehash_sha1"] = True
            params["createmerkletorrent"] = False
            params["torrentsigkeypairfilename"] = False
            params["thumb"] = False

            piece_length_list = [0, 2 ** 21, 2 ** 20, 2 ** 19, 2 ** 18, 2 ** 17, 2 ** 16, 2 ** 15]
            params["piece length"] = piece_length_list[self.pieceChoice.GetSelection()]

            def do_gui():
                if self.cancelEvent.isSet():
                    self.OnCancel(event)
                else:
                    self.EndModal(wx.ID_OK)

            def create_torrents():
                if self.combineRadio.GetValue():
                    params["name"] = self.specifiedName.GetValue()
                    make_meta_file(self.selectedPaths, params, self.cancelEvent, None, self._torrentCreated)
                else:
                    for i, path in enumerate(self.selectedPaths):
                        make_meta_file([path], params, self.cancelEvent, None, self._torrentCreated)

                wx.CallAfter(do_gui)

            self.guiserver = GUITaskQueue.getInstance()
            self.guiserver.add_task(create_torrents)

        else:
            dlg.Destroy()
示例#29
0
 def OnUpgrade(self, event=None):
     self.setActivity(NTFY_ACT_NEW_VERSION)
     guiserver = GUITaskQueue.getInstance()
     guiserver.add_task(self.upgradeCallback, 10.0)
示例#30
0
 def checkVersion(self):
     guiserver = GUITaskQueue.getInstance()
     guiserver.add_task(self._checkVersion,10.0)
示例#31
0
 def OnUpgrade(self, event=None):
     self.setActivity(NTFY_ACT_NEW_VERSION)
     guiserver = GUITaskQueue.getInstance()
     guiserver.add_task(self.upgradeCallback,10.0)
示例#32
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
        self.category = Category.getInstance()
        self.shutdown_and_upgrade_notes = None

        self.guiserver = GUITaskQueue.getInstance()
        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('')

        self.SRstatusbar = SRstatusbar(self)
        self.SetStatusBar(self.SRstatusbar)

        if sys.platform != 'darwin':
            dragdroplist = FileDropTarget(self)
            self.SetDropTarget(dragdroplist)

        self.tbicon = None

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

        # Don't update GUI as often when iconized
        self.GUIupdate = True
        self.oldframe = None
        self.window = self.GetChildren()[0]
        self.window.utility = self.utility

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

        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        # 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)


        findId = wx.NewId()
        quitId = wx.NewId()
        self.Bind(wx.EVT_MENU, self.OnFind, id = findId)
        self.Bind(wx.EVT_MENU, lambda event: self.Close(), id = quitId)

        accelerators = [(wx.ACCEL_CTRL, ord('f'), findId)]
        if sys.platform == 'linux2':
            accelerators.append((wx.ACCEL_CTRL, ord('q'), quitId))
            accelerators.append((wx.ACCEL_CTRL, ord('/'), findId))
        self.SetAcceleratorTable(wx.AcceleratorTable(accelerators))

        try:
            self.tbicon = ABCTaskBarIcon(self)
        except:
            print_exc()
        self.Bind(wx.EVT_ICONIZE, self.onIconify)
        self.Bind(wx.EVT_SIZE, self.onSize)
        self.Bind(wx.EVT_MAXIMIZE, self.onSize)

        # Init video player
        sys.stdout.write('GUI Complete.\n')

        self.Show(True)
        self.ready = True

        # Just for debugging: add test permids and display top 5 peers from which the most is downloaded in bartercastdb
#        bartercastdb = self.utility.session.open_dbhandler(NTFY_BARTERCAST)
#        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

        self.checkVersion()

        # If the user passed a torrentfile on the cmdline, load it.
        wx.CallAfter(self.startCMDLineTorrent)

        # ProxyService 90s Test_
        from Tribler.Core.Session import Session
        session = Session.get_instance()
        session.uch.notify(NTFY_GUI_STARTED, NTFY_INSERT, None, None)
示例#33
0
    def __init__(self, parent, channelonly, internalvideo, progress):
        # Do all init here
        self.ready = False
        self.guiUtility = GUIUtility.getInstance()
        self.guiUtility.frame = self
        self.utility = self.guiUtility.utility
        self.params = self.guiUtility.params
        self.utility.frame = self
        self.torrentfeed = None
        self.category = Category.getInstance()
        self.shutdown_and_upgrade_notes = None

        self.guiserver = GUITaskQueue.getInstance()

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

        # Get window size and (sash) position from config file
        size, position, sashpos = self.getWindowSettings()
        style = wx.DEFAULT_DIALOG_STYLE | wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN

        wx.Frame.__init__(self, parent, wx.ID_ANY, title, position, size, style)
        if sys.platform == 'linux2':
            font = self.GetFont()
            if font.GetPointSize() > 9:
                font.SetPointSize(9)
                self.SetFont(font)

        self.Freeze()
        self.SetDoubleBuffered(True)
        self.SetBackgroundColour(DEFAULT_BACKGROUND)

        themeColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
        r, g, b = themeColour.Get(False)
        if r > 190 or g > 190 or b > 190:  # Grey == 190,190,190
            self.SetForegroundColour(wx.BLACK)

        if internalvideo:
            self.videoparentpanel = wx.Panel(self)
            self.videoparentpanel.Hide()
        else:
            self.videoparentpanel = None

        # Create all components
        progress('Creating panels')
        if not channelonly:
            self.actlist = ActivitiesList(self)
            self.top_bg = TopSearchPanel(self)
            self.home = Home(self)

            self.splitter = wx.SplitterWindow(self, style=wx.SP_NOBORDER)
            self.splitter.SetMinimumPaneSize(1)
            self.splitter.SetForegroundColour(self.GetForegroundColour())
            self.splitter_top_window = wx.Panel(self.splitter, style=wx.NO_BORDER)
            self.splitter_top_window.SetForegroundColour(self.GetForegroundColour())
            self.splitter_top = wx.BoxSizer(wx.HORIZONTAL)
            self.splitter_top_window.SetSizer(self.splitter_top)
            self.splitter_bottom_window = wx.Panel(self.splitter)
            self.splitter_bottom_window.SetMinSize((-1, 25))
            self.splitter_bottom_window.SetForegroundColour(self.GetForegroundColour())
            self.splitter_bottom_window.OnChange = lambda: self.splitter_bottom.Layout()
            self.splitter_bottom_window.parent_list = self.splitter_bottom_window
            self.splitter_bottom = wx.BoxSizer(wx.HORIZONTAL)
            self.splitter_bottom_window.SetSizer(self.splitter_bottom)
            self.splitter.SetSashGravity(0.8)
            self.splitter.SplitHorizontally(self.splitter_top_window, self.splitter_bottom_window, sashpos)
            self.splitter.Show(False)
            # Reset the sash position after the splitter has been made visible

            def OnShowSplitter(event):
                wx.CallAfter(self.splitter.SetSashPosition, sashpos)
                self.splitter.Unbind(wx.EVT_SHOW)
                event.Skip()
            self.splitter.Bind(wx.EVT_SHOW, OnShowSplitter)

            self.searchlist = SearchList(self.splitter_top_window)
            self.searchlist.Show(False)
            self.librarylist = LibraryList(self.splitter_top_window)
            self.librarylist.Show(False)
            self.channellist = ChannelList(self.splitter_top_window)
            self.channellist.Show(False)
            self.selectedchannellist = SelectedChannelList(self.splitter_top_window)
            self.selectedchannellist.Show(False)
            self.playlist = Playlist(self.splitter_top_window)
            self.playlist.Show(False)
        else:
            self.actlist = None
            self.top_bg = None

            self.guiUtility.guiPage = 'selectedchannel'
            self.home = None
            self.searchlist = None
            self.librarylist = LibraryList(self)
            self.librarylist.Show(False)
            self.channellist = None
            self.selectedchannellist = SelectedChannelList(self)
            self.selectedchannellist.Show(True)
            self.playlist = Playlist(self)
            self.playlist.Show(False)

        self.stats = Stats(self)
        self.stats.Show(False)
        self.managechannel = ManageChannel(self)
        self.managechannel.Show(False)

        progress('Positioning')

        if not channelonly:
            # position all elements
            vSizer = wx.BoxSizer(wx.VERTICAL)

            vSizer.Add(self.top_bg, 0, wx.EXPAND)

            hSizer = wx.BoxSizer(wx.HORIZONTAL)
            vSizer.Add(hSizer, 1, wx.EXPAND)

            hSizer.Add(self.actlist, 0, wx.EXPAND)
            separator = wx.Panel(self, size=(1, -1))
            separator.SetBackgroundColour(SEPARATOR_GREY)
            hSizer.Add(separator, 0, wx.EXPAND)
            hSizer.Add(self.home, 1, wx.EXPAND)
            hSizer.Add(self.stats, 1, wx.EXPAND)
            hSizer.Add(self.splitter, 1, wx.EXPAND)
        else:
            vSizer = wx.BoxSizer(wx.VERTICAL)
            hSizer = wx.BoxSizer(wx.HORIZONTAL)
            vSizer.Add(hSizer, 1, wx.EXPAND | wx.ALL, 5)

            self.top_bg = TopSearchPanelStub()

        hSizer.Add(self.managechannel, 1, wx.EXPAND)

        if self.videoparentpanel:
            hSizer.Add(self.videoparentpanel, 1, wx.EXPAND)

        self.SetSizer(vSizer)

        # set sizes
        if not channelonly:
            self.top_bg.SetMinSize((-1, 45))
            self.actlist.SetMinSize((200, -1))

        self.SRstatusbar = SRstatusbar(self)
        self.SetStatusBar(self.SRstatusbar)

        def preload_data():
            if not channelonly:
                self.guiUtility.showChannelCategory('All', False)
            self.guiUtility.showLibrary(False)
        startWorker(None, preload_data, delay=1.5, workerType="guiTaskQueue")

        if channelonly:
            self.guiUtility.showChannelFromDispCid(channelonly)
            if internalvideo:
                self.guiUtility.ShowPlayer()

        if sys.platform != 'darwin':
            dragdroplist = FileDropTarget(self)
            self.SetDropTarget(dragdroplist)
        try:
            self.SetIcon(self.utility.icon)
        except:
            pass

        self.tbicon = None
        try:
            self.tbicon = ABCTaskBarIcon(self)
        except:
            print_exc()

        # Don't update GUI as often when iconized
        self.GUIupdate = True
        self.window = self.GetChildren()[0]
        self.window.utility = self.utility

        progress('Binding events')
        # Menu Events
        #
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        # 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)
        self.Bind(wx.EVT_ICONIZE, self.onIconify)
        self.Bind(wx.EVT_SIZE, self.onSize)
        self.Bind(wx.EVT_MAXIMIZE, self.onSize)

        findId = wx.NewId()
        quitId = wx.NewId()
        nextId = wx.NewId()
        prevId = wx.NewId()
        dispId = wx.NewId()
        self.Bind(wx.EVT_MENU, self.OnFind, id=findId)
        self.Bind(wx.EVT_MENU, lambda event: self.Close(), id=quitId)
        self.Bind(wx.EVT_MENU, self.OnNext, id=nextId)
        self.Bind(wx.EVT_MENU, self.OnPrev, id=prevId)
        self.Bind(wx.EVT_MENU, lambda evt: self.guiUtility.ShowPage('stats'), id=dispId)

        accelerators = [(wx.ACCEL_CTRL, ord('f'), findId)]
        accelerators.append((wx.ACCEL_CTRL, ord('d'), dispId))
        accelerators.append((wx.ACCEL_CTRL, wx.WXK_TAB, nextId))
        accelerators.append((wx.ACCEL_CTRL | wx.ACCEL_SHIFT, wx.WXK_TAB, prevId))

        if sys.platform == 'linux2':
            accelerators.append((wx.ACCEL_CTRL, ord('q'), quitId))
            accelerators.append((wx.ACCEL_CTRL, ord('/'), findId))
        self.SetAcceleratorTable(wx.AcceleratorTable(accelerators))

        # Init video player
        sys.stdout.write('GUI Complete.\n')
        self.Thaw()
        self.ready = True

        def post():
            self.checkVersion()
            self.startCMDLineTorrent()

        # If the user passed a torrentfile on the cmdline, load it.
        wx.CallAfter(post)
示例#34
0
 def checkVersion(self):
     guiserver = GUITaskQueue.getInstance()
     guiserver.add_task(self._checkVersion, 10.0)