def start(self): """Do the rest of the setup before turning control over to the reactor""" self._setup_environment() self._load_settings() self._load_data() self._create_applications() #in case this was the first run: self.bbApp.settings.fileName = os.path.join(Globals.USER_DATA_DIR, BitBlinder.BitBlinderSettings.defaultFile) GlobalEvents.throw_event("settings_changed") #must be done after settings are loaded self._start_psyco() #check for updates for the program: Updater.get().start() #start the bank bankStartupDeferred = self.bankApp.start() bankStartupDeferred.addCallback(self._on_bank_ready) bankStartupDeferred.addErrback(log_ex, "Bank failed to start!") #the rest of the startup code needs to run after the reactor has started: Scheduler.schedule_once(0.0, self._on_reactor_started)
def start(self): """Do the rest of the setup before turning control over to the reactor""" self._setup_environment() self._load_settings() self._load_data() self._create_applications() #in case this was the first run: self.bbApp.settings.fileName = os.path.join( Globals.USER_DATA_DIR, BitBlinder.BitBlinderSettings.defaultFile) GlobalEvents.throw_event("settings_changed") #must be done after settings are loaded self._start_psyco() #check for updates for the program: Updater.get().start() #start the bank bankStartupDeferred = self.bankApp.start() bankStartupDeferred.addCallback(self._on_bank_ready) bankStartupDeferred.addErrback(log_ex, "Bank failed to start!") #the rest of the startup code needs to run after the reactor has started: Scheduler.schedule_once(0.0, self._on_reactor_started)
def buildProtocol(self, addr): protocolInstance = protocol.ClientFactory.buildProtocol(self, addr) if self.protocolInstance: raise Exception("Hey, you're only supposed to build one protocol with this factory!") self.protocolInstance = protocolInstance self.protocolInstance.responseReceived = False Scheduler.schedule_once(TIMEOUT, self.on_timeout) return self.protocolInstance
def buildProtocol(self, addr): protocolInstance = protocol.ClientFactory.buildProtocol(self, addr) if self.protocolInstance: raise Exception( "Hey, you're only supposed to build one protocol with this factory!" ) self.protocolInstance = protocolInstance self.protocolInstance.responseReceived = False Scheduler.schedule_once(TIMEOUT, self.on_timeout) return self.protocolInstance
def response(progress): if progress >= 85: if not self.isReady: self.isReady = True self.torApp.on_ready() return #TODO: handle the case where we get here with <80% progress. What then? Can it even happen? elif progress >= 80: #start a thread to periodically try launching circuits to random routers: self.startup_circuits = [] Scheduler.schedule_repeat(2, self.try_new_circuit)
def _check_welcome_dialog(self, triggeringApp): if not self.torApp.is_ready() or not self.bankApp.is_ready(): return if not self.torApp.settings.promptedAboutRelay: self.welcomeDialog = WelcomeDialog.WelcomeDialog(self) self.torApp.settings.promptedAboutRelay = True self.torApp.settings.save() #TODO: remove this hack--need to schedule a _raise later so that the window doesnt get hidden by other stuff that happens when Tor launches def raise_later(): if self.welcomeDialog: self.welcomeDialog.raise_() Scheduler.schedule_once(2.0, raise_later)
def show_msgbox(self, text, title="Notice", cb=None, buttons=None, args=None, width=200, link=None): text = "%s: %s" % (title, text) if buttons != None: text += "\nDefaulted to %s" % (buttons[0]) if link != None: text += "\nLink: %s" % (link) log_msg(text, 2) if cb: if not args: args = [] args.insert(0, 0) args.insert(0, None) Scheduler.schedule_once(0.1, cb, *args)
def start(self): """Delete the old logs and open the new ones""" if ProgramState.PY2EXE: #these redirect output, to avoid writing to the Main.exe.log (default py2exe behavior) #we want to avoid that because it pops a dialog about errors, and we definitely want to fail silently when demoing the app... sys.stdout = open(os.path.join(Globals.LOG_FOLDER, 'stdout.out'), "w") sys.stderr = open(os.path.join(Globals.LOG_FOLDER, 'stderr.out'), "w") #remove the old tor logs: Files.delete_file(os.path.join(Globals.LOG_FOLDER, 'tor.out'), True) #open up the debug logs and create the testfile: self.start_logs(["main", "errors", "automated", "pysocks", "tor_conn"], "main", Globals.LOG_FOLDER) #rotate the logs every half an hour, so that they can have lots of info, but not fill someone's hard drive... Scheduler.schedule_repeat(30 * 60, self.rotate_logs)
def start_connections(self, list): peers_added = 0 #add to our current list except duplicates: for peer in list: if self.to_connect.count(peer) == 0: if self.prev_connected.count(peer) == 0: self.never_connected.append(peer) peers_added += 1 else: self.to_connect.append(peer) peers_added += 1 log_msg( "Added %s to our list of peers, now %s long." % (peers_added, len(self.to_connect)), 2, "tracker") #without this, the peers would be each get connected to twice on the very first update if they fail if self.lastPeerCycleTime == 0: self.lastPeerCycleTime = time.time() #for testing: sometimes handy to print out peers so I can make sure we can connect to them later #f = open("peer_list.txt", "wb") #for x in list: # dns, id, encrypted = x # #log_msg("%s %s (%s)" % (encrypted, dns, id)) # f.write("%s:%s\n" % (dns[0], dns[1])) #f.close() #make sure we're starting connections from that list: if not self.startConnectionsEvent: self.startConnectionsEvent = Scheduler.schedule_repeat( 1.0, self._start_connection_from_queue) self._start_connection_from_queue()
def start_connections(self, list): peers_added = 0 #add to our current list except duplicates: for peer in list: if self.to_connect.count(peer) == 0: if self.prev_connected.count(peer) == 0: self.never_connected.append(peer) peers_added += 1 else: self.to_connect.append(peer) peers_added += 1 log_msg("Added %s to our list of peers, now %s long." % (peers_added, len(self.to_connect)), 2, "tracker") #without this, the peers would be each get connected to twice on the very first update if they fail if self.lastPeerCycleTime == 0: self.lastPeerCycleTime = time.time() #for testing: sometimes handy to print out peers so I can make sure we can connect to them later #f = open("peer_list.txt", "wb") #for x in list: # dns, id, encrypted = x # #log_msg("%s %s (%s)" % (encrypted, dns, id)) # f.write("%s:%s\n" % (dns[0], dns[1])) #f.close() #make sure we're starting connections from that list: if not self.startConnectionsEvent: self.startConnectionsEvent = Scheduler.schedule_repeat(1.0, self._start_connection_from_queue) self._start_connection_from_queue()
def send_setup_message(self): """Send the setup messages from each PaymentStream""" if not self.setupStarted: log_msg("circ=%d: Sending PAR setup message" % (self.circ.id), 3, "par") self.setupStarted = True self.inflightReadTokens += PaymentMessageHandler.START_READ_TOKENS self.inflightWriteTokens += PaymentMessageHandler.START_WRITE_TOKENS for paymentStream in self.paymentStreams.values(): paymentStream.send_setup() #schedule a timeout so we dont wait forever: def par_setup_timeout(): if not self.setupDone: #END_CIRC_REASON_TIMEOUT if not self.circ.is_done(): self.circ.close(10) Scheduler.schedule_once(PaymentStream.PAR_TIMEOUT, par_setup_timeout)
def _on_bank_ready(self, result): """Called when the bank has finished starting. Alerts the applications to any startup arguments that were passed in, which will likely cause them to actually start.""" if result != True: log_msg("Bank failed to start correctly!", 0) return result #handle the starting arguments: Startup.handle_args(ProgramState.STARTING_DIR, sys.argv[1:]) GlobalEvents.throw_event("startup") #if this is the first run, save all the settings files: if self.bbApp.isFirstRun: for app in [self.bbApp, self.btApp, self.torApp, self.ffApp]: if app: app.settings.save() self.coreSettings.save() #schedule update function: def do_update(): BWHistory.update_all() return True ProgramState.DO_UPDATES = True self.updateEvent = Scheduler.schedule_repeat( Globals.INTERVAL_BETWEEN_UPDATES, do_update) return result
def _on_bank_ready(self, result): """Called when the bank has finished starting. Alerts the applications to any startup arguments that were passed in, which will likely cause them to actually start.""" if result != True: log_msg("Bank failed to start correctly!", 0) return result #handle the starting arguments: Startup.handle_args(ProgramState.STARTING_DIR, sys.argv[1:]) GlobalEvents.throw_event("startup") #if this is the first run, save all the settings files: if self.bbApp.isFirstRun: for app in [self.bbApp, self.btApp, self.torApp, self.ffApp]: if app: app.settings.save() self.coreSettings.save() #schedule update function: def do_update(): BWHistory.update_all() return True ProgramState.DO_UPDATES = True self.updateEvent = Scheduler.schedule_repeat(Globals.INTERVAL_BETWEEN_UPDATES, do_update) return result
def send_payment_request(self, readTokens, writeTokens): """Called by a Circuit object when it wants to actually make a payment @param readTokens: the number of read tokens to pay for at each hop in the circuit @type readTokens: int @param writeTokens: the number of read tokens to pay for at each hop in the circuit @type writeTokens: int""" assert (readTokens + writeTokens) / Globals.CELLS_PER_PAYMENT, "tried to pay for bad number of cells" #make sure our setup is done: if not self.setupDone: #have we even started? if not self.setupStarted: self.send_setup_message() self.queuedReadTokens += readTokens self.queuedWriteTokens += writeTokens return #dont bother trying to send payments for circuits that are already closed if self.circ.is_done(): return #send the payments deferreds = [] for paymentStream in self.paymentStreams.values(): deferreds.append(paymentStream.send_payment(readTokens, writeTokens)) paymentsDoneDeferred = DeferredList(deferreds) paymentsDoneDeferred.addErrback(self.generic_error_handler) addTokensDeferred = Deferred() self.inflightReadTokens += readTokens self.inflightWriteTokens += writeTokens #timeout in case the payment fails. We will close the circuit in this case. event = Scheduler.schedule_once(PaymentStream.PAR_TIMEOUT, self.all_receipts_received, None, addTokensDeferred, readTokens, writeTokens, None) paymentsDoneDeferred.addCallback(self.all_receipts_received, addTokensDeferred, readTokens, writeTokens, event) addTokensDeferred.addCallback(self._add_tokens_callback, readTokens, writeTokens) addTokensDeferred.addErrback(self.generic_error_handler)
def _start_test(self, widget=None): self.torApp.start_server() for box in (self.relayBox, self.dirBox, self.dhtBox): box.apply_value() self.torApp.settings.on_apply(self.torApp, "") self._cancel_test_update() self.testUpdateEvent = Scheduler.schedule_repeat(0.1, self._test_update) #update the title to reflect the fact that we are currently testing self._on_test_started()
def handle_stream(self, stream): """Attach a Stream to an appropriate Circuit. Builds a new Circuit if necessary. @param stream: the stream to attach @type stream: Stream @return: True on success, False otherwise. Will close the stream if False is returned.""" stream.handleAttempts += 1 if stream.handleAttempts > 2: #7 = END_STREAM_REASON_TIMEOUT (failed to connect in a reasonable amount of time) stream.close(7) log_msg("Tried to attach stream too many times, stopping.", 2, "stream") return False host = stream.targetHost port = stream.targetPort #record in our port history: if port not in self.portHistory: self.portHistory[port] = 0 self.portHistory[port] += 1 #find the best circuit, or failing that, build one: best = self.find_or_build_best_circuit(host, port, stream.ignoreCircuits) #if there is no such circuit: if not best: #3 = END_STREAM_REASON_CONNECTREFUSED (we couldnt figure out where to connect) stream.close(3) return False #actually attach the stream to the circuit if not best.attach(stream): #1 -- REASON_MISC (catch-all for unlisted reasons) stream.close(1) log_msg( "Stream=%d failed to attach to Circuit=%d" % (stream.id, best.id), 1, "stream") return False #if the circuit is not yet open, put a 15 second timeout on it: if not best.status in ("LAUNCHED", "PRELAUNCH"): def circuit_timeout(circ): if circ.status in ("LAUNCHED", "PRELAUNCH") and circ.is_open(): circ.close() Scheduler.schedule_once(15.0, circuit_timeout, best) return True
def _start_test(self, widget=None): self.torApp.start_server() for box in (self.relayBox, self.dirBox, self.dhtBox): box.apply_value() self.torApp.settings.on_apply(self.torApp, "") self._cancel_test_update() self.testUpdateEvent = Scheduler.schedule_repeat( 0.1, self._test_update) #update the title to reflect the fact that we are currently testing self._on_test_started()
def on_new_info(self, balance, interval, expiresCurrent, expiresNext): """Called when we learn about new ACoin interval information @param balance: new bank balance @type balance: int @param interval: current ACoin interval @type interval: int @param expiresCurrent: how many seconds until this interval expires @type expiresCurrent: int @param expiresNext: how many seconds until the next interval also expires @type expiresNext: int""" #if we just learned about a new interval: if interval > self.currentACoinInterval: curTime = time.time() expiresCurrent += curTime expiresNext += curTime log_msg("Learned about new interval: %s" % (interval), 4) #make sure we dont have any expiring ACoins: if self.ACoins.has_key(self.currentACoinInterval - 1): del self.ACoins[self.currentACoinInterval - 1] self.currentACoinInterval = interval self.curIntervalExpiration = expiresCurrent self.nextAcoinIntervalExpiration = expiresNext self.APPROX_INTERVAL_LEN = expiresNext - expiresCurrent self.beginDepositACoinTime = expiresCurrent - ( 0.1 * self.APPROX_INTERVAL_LEN) self.beginDepositACoinTime -= random.random() * ( 0.3 * self.APPROX_INTERVAL_LEN) self.sendOldACoinCutoff = expiresCurrent - ( 0.1 * self.APPROX_INTERVAL_LEN) needNewACoinTime = self.sendOldACoinCutoff - ( random.random() * 0.1 * self.APPROX_INTERVAL_LEN) - curTime if needNewACoinTime > 0: Scheduler.schedule_once(needNewACoinTime, self.check_next_acoins) self.intervalLearningDelay = random.random() * ( 0.25 * self.APPROX_INTERVAL_LEN) log_msg("\nACoin send cutoff: %s\nACoin accept cutoff: %s\nCur interval ends at: %s\nLearning about next interval at: %s" \ % tuple([time.asctime(time.gmtime(t)) for t in (self.sendOldACoinCutoff, self.beginDepositACoinTime, expiresCurrent, expiresCurrent+self.intervalLearningDelay)]), 4) self.on_new_balance_from_bank(balance)
def handle_stream(self, stream): """Attach a Stream to an appropriate Circuit. Builds a new Circuit if necessary. @param stream: the stream to attach @type stream: Stream @return: True on success, False otherwise. Will close the stream if False is returned.""" stream.handleAttempts += 1 if stream.handleAttempts > 2: #7 = END_STREAM_REASON_TIMEOUT (failed to connect in a reasonable amount of time) stream.close(7) log_msg("Tried to attach stream too many times, stopping.", 2, "stream") return False host = stream.targetHost port = stream.targetPort #record in our port history: if port not in self.portHistory: self.portHistory[port] = 0 self.portHistory[port] += 1 #find the best circuit, or failing that, build one: best = self.find_or_build_best_circuit(host, port, stream.ignoreCircuits) #if there is no such circuit: if not best: #3 = END_STREAM_REASON_CONNECTREFUSED (we couldnt figure out where to connect) stream.close(3) return False #actually attach the stream to the circuit if not best.attach(stream): #1 -- REASON_MISC (catch-all for unlisted reasons) stream.close(1) log_msg("Stream=%d failed to attach to Circuit=%d" % (stream.id, best.id), 1, "stream") return False #if the circuit is not yet open, put a 15 second timeout on it: if not best.status in ("LAUNCHED", "PRELAUNCH"): def circuit_timeout(circ): if circ.status in ("LAUNCHED", "PRELAUNCH") and circ.is_open(): circ.close() Scheduler.schedule_once(15.0, circuit_timeout, best) return True
def _subprocess_finished(self, result, p): if result == True: self.remove_process(p) if p == self.polipoProc: self.polipoProc = None self.stop() else: if len(self.processes) == 1 and self.polipoProc: #lets check if any firefoxes start up in the next few seconds, in case this is the reboot: if not self.checkFFEvent: self.checkFFEvent = Scheduler.schedule_once(2.0, self._check_for_firefoxes) if len(self.processes) <= 0: self._all_subprocesses_done() elif result != False: log_ex(result, "Failed while waiting for subprocess")
def stop(self, timeout=10.0): """Dump all ACoins immediately. @param timeout: how long to wait while depositing ACoins @returns: a Deferred to be triggered when done or if the attempt timed out.""" if self.shutdownDeferred: return self.shutdownDeferred #cancel any bank messages in progress self.messageQueue = [] #since we wont be able to send the deposit anyway... if not self.isLoggedIn: if self.is_starting(): #notify anyone waiting on the startup deferred: self.loginInProgress = False d = self.startupDeferred self.startupDeferred = None d.callback(False) return defer.succeed(True) #create the deferred self.shutdownDeferred = defer.Deferred() #schedule the timeout self.shutdownTimeoutEvent = Scheduler.schedule_once( timeout, self._shutdown_timeout) #move all ACoins over to be in deposit progress coinsToDeposit = [] for key, coins in self.ACoins.iteritems(): coinsToDeposit += coins self.ACoins = {} self.depositingACoins += coinsToDeposit if not self.acoinDepositInProgress: coinsToDeposit = self.depositingACoins #save ACoins self.coinsChanged = True self.save_coins() #send the message to the bank bankD = defer.Deferred() self.send_message( ACoinDepositFactory.ACoinDepositFactory(self, coinsToDeposit, bankD)) #on success, trigger the deferred bankD.addCallback(self._shutdown_success) #deal with failure by trying again bankD.addErrback(self._shutdown_failure) self._trigger_event("stopped") return self.shutdownDeferred
def add_task(self, func, delay = 0, id = None): assert float(delay) >= 0 eventId = self.curEventId self.curEventId += 1 if not self.idMapping.has_key(id): self.idMapping[id] = set() self.idMapping[id].add(eventId) def wrapperFunc(func=func, id=id, eventId=eventId): if self.idMapping.has_key(id) and eventId in self.idMapping[id]: self.idMapping[id].remove(eventId) if len(self.idMapping[id]) <= 0: del self.idMapping[id] if self.events.has_key(id) and self.events[id].has_key(eventId): del self.events[id][eventId] if len(self.events[id]) <= 0: del self.events[id] func() if not self.events.has_key(id): self.events[id] = {} self.events[id][eventId] = Scheduler.schedule_once(delay, wrapperFunc)
def send_payment_request(self, readTokens, writeTokens): """Called by a Circuit object when it wants to actually make a payment @param readTokens: the number of read tokens to pay for at each hop in the circuit @type readTokens: int @param writeTokens: the number of read tokens to pay for at each hop in the circuit @type writeTokens: int""" assert ( readTokens + writeTokens ) / Globals.CELLS_PER_PAYMENT, "tried to pay for bad number of cells" #make sure our setup is done: if not self.setupDone: #have we even started? if not self.setupStarted: self.send_setup_message() self.queuedReadTokens += readTokens self.queuedWriteTokens += writeTokens return #dont bother trying to send payments for circuits that are already closed if self.circ.is_done(): return #send the payments deferreds = [] for paymentStream in self.paymentStreams.values(): deferreds.append( paymentStream.send_payment(readTokens, writeTokens)) paymentsDoneDeferred = DeferredList(deferreds) paymentsDoneDeferred.addErrback(self.generic_error_handler) addTokensDeferred = Deferred() self.inflightReadTokens += readTokens self.inflightWriteTokens += writeTokens #timeout in case the payment fails. We will close the circuit in this case. event = Scheduler.schedule_once(PaymentStream.PAR_TIMEOUT, self.all_receipts_received, None, addTokensDeferred, readTokens, writeTokens, None) paymentsDoneDeferred.addCallback(self.all_receipts_received, addTokensDeferred, readTokens, writeTokens, event) addTokensDeferred.addCallback(self._add_tokens_callback, readTokens, writeTokens) addTokensDeferred.addErrback(self.generic_error_handler)
def _check_apps(self): if not self.programCheckEvent: self.programCheckEvent = Scheduler.schedule_repeat(1.0, self._check_apps) #program still running? if self.currentApp and self.currentApp.poll() == None: log_msg("Waiting for UAC app to finish...", 1) return True #are there any more to launch? if len(self.launchList) > 0: #launch the next one: cmd, nextDeferred = self.launchList.pop(0) log_msg("Launching next UAC app: %s" % (cmd), 1) self.currentApp = LaunchProcess.LaunchProcess(cmd) process = Process.Process(self.currentApp.pid) process.d.chainDeferred(nextDeferred) return True #nothing else to launch: else: log_msg("No more UAC apps to launch.", 1) self.programCheckEvent = None return False
def add_task(self, func, delay=0, id=None): assert float(delay) >= 0 eventId = self.curEventId self.curEventId += 1 if not self.idMapping.has_key(id): self.idMapping[id] = set() self.idMapping[id].add(eventId) def wrapperFunc(func=func, id=id, eventId=eventId): if self.idMapping.has_key(id) and eventId in self.idMapping[id]: self.idMapping[id].remove(eventId) if len(self.idMapping[id]) <= 0: del self.idMapping[id] if self.events.has_key(id) and self.events[id].has_key(eventId): del self.events[id][eventId] if len(self.events[id]) <= 0: del self.events[id] func() if not self.events.has_key(id): self.events[id] = {} self.events[id][eventId] = Scheduler.schedule_once(delay, wrapperFunc)
def do_expose_event(self, event): #schedule the draw event if this is the first time we've ever been exposed if not self.shouldDraw: self.shouldDraw = True Scheduler.schedule_repeat(1.0, self.draw) self.visible_cb() #Create the cairo context self.cr = self.window.cairo_create() #Restrict Cairo to the exposed area; avoid extra work self.cr.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) self.cr.clip() width, height = self.window.get_size() cr = self.cr cr.set_source_rgb(*self.cFill) cr.rectangle(0, 0, width, height) cr.fill() #figure out the scale mapping between values and pixels: maxYVal = self.maxVal maxValueText, maxValueUnits = Format.bytes_per_second(maxYVal).split(" ") x_bearing, y_bearing, w, h = cr.text_extents(maxValueText)[:4] xStart = w + self.PADDING_LEFT + self.PADDING_AXIS xEnd = width - self.PADDING_RIGHT xStepSize = float(xEnd - xStart) / float(self.NUM_VALUES) x_bearing, y_bearing, w, h = cr.text_extents("100MB/s")[:4] bottomY = height - (self.PADDING_BOTTOM + h + self.PADDING_AXIS) yScale = float(bottomY - self.PADDING_TOP) / float(maxYVal) #shade enclosed rectangle white cr.set_source_rgb(self.cInnerShade[0], self.cInnerShade[1], self.cInnerShade[2]) cr.rectangle(xStart, self.PADDING_TOP, width-self.PADDING_RIGHT-xStart, bottomY-self.PADDING_TOP) cr.fill() #labels cr.set_line_width(0.6) cr.set_font_size(self.FONT_SIZE) #vertical lines: numLines = self.NUM_VERT_LINES cr.set_source_rgb(self.cLines[0], self.cLines[1], self.cLines[2]) if self.xMiddleTics: numLines = (numLines * (self.xMiddleTics+1)) for i in range(0, numLines + 1): if self.xMiddleTics: if i % (1+self.xMiddleTics) == 0: cr.set_line_width(0.6) else: cr.set_line_width(0.2) s = (self.NUM_VALUES / numLines) * i #should be a dark color... x = xStart + int(xStepSize * s) cr.move_to(x, self.PADDING_TOP) cr.line_to(x, bottomY) cr.stroke() x_bearing, y_bearing, w, h = cr.text_extents("Time (1 second step)")[:4] yPos = bottomY + self.PADDING_AXIS + h - self.lineWidth #make left label: cr.move_to(xStart, yPos) cr.show_text("Time (1 second step)") #middle label: x_bearing, y_bearing, w, h = cr.text_extents("Grid: 10 seconds")[:4] cr.move_to((xStart+xEnd)/2 - w/2, yPos) cr.show_text("Grid: 10 seconds") #make right label: x_bearing, y_bearing, w, h = cr.text_extents("Now")[:4] cr.move_to(xEnd-w, yPos) cr.show_text("Now") #horizontal lines: cr.set_source_rgb(self.cLines[0], self.cLines[1], self.cLines[2]) numLines = self.NUM_HORIZ_LINES if self.yMiddleTics: numLines = (numLines * (self.yMiddleTics+1)) j = 0 for i in range(0,maxYVal+1,maxYVal/numLines): if self.yMiddleTics: if j % (1+self.yMiddleTics) == 0: cr.set_line_width(0.6) else: cr.set_line_width(0.2) j += 1 #should be a dark color... y = bottomY - int(yScale * i) cr.move_to(xEnd, y) cr.line_to(xStart, y) cr.stroke() #make top label: x_bearing, y_bearing, w, h = cr.text_extents("0")[:4] cr.move_to(self.PADDING_LEFT, self.PADDING_TOP+h) cr.show_text(maxValueText) #middle label: self.cr.rotate(-1*math.pi / 2.0) x_bearing, y_bearing, w, h = cr.text_extents(maxValueUnits)[:4] cr.move_to(-1 * height / 2.0 - w/2 + self.PADDING_TOP, self.PADDING_LEFT + h + 2) cr.show_text(maxValueUnits) self.cr.rotate(math.pi / 2.0) #make bottom label: x_bearing, y_bearing, w, h = cr.text_extents("0")[:4] cr.move_to(xStart-self.PADDING_AXIS-w, bottomY) cr.show_text("0") #draw the data lines on the graph: for sourceVals in (self.dataSource.bytesRead, self.dataSource.bytesWritten): # Set properties for the line (different colors for read and written) if sourceVals == self.dataSource.bytesWritten: cr.set_source_rgb(self.cWritten[0], self.cWritten[1], self.cWritten[2]) else: cr.set_source_rgb(self.cRead[0], self.cRead[1], self.cRead[2]) cr.set_line_width(self.lineWidth) #for every bw value, vals = sourceVals[len(sourceVals)-self.NUM_VALUES:] for i in range(0, len(vals)-1): #draw a line segment: startX = xStart + int(xStepSize * i) endX = xStart + int(xStepSize * (i+1)) y1 = bottomY - (vals[i] * yScale) y2 = bottomY - (vals[i+1] * yScale) cr.move_to(startX, y1) cr.line_to(endX, y2) #Apply the ink cr.stroke() #update the maximum y value and scale for next time: newMax = 0 for v in vals: if v > newMax: newMax = v #double the scale until we contain the max value: while newMax > self.maxVal: self.maxVal *= 2 else: if newMax < self.maxVal / 2: self.scale_too_big += 1 else: self.scale_too_big = 0 #if the scale has been too big for more than 5 ticks, make it smaller if self.scale_too_big > 5: #dont go below the original axis value: if self.maxVal > 32 * 1024: self.maxVal /= 2
def _schedule_next_test(self): self.nextScheduledTest = Scheduler.schedule_once( self.SECONDS_BETWEEN_TESTS, self._start_probe)
def do_expose_event(self, event): #schedule the draw event if this is the first time we've ever been exposed if not self.shouldDraw: self.shouldDraw = True Scheduler.schedule_repeat(1.0, self.draw) self.visible_cb() #Create the cairo context self.cr = self.window.cairo_create() #Restrict Cairo to the exposed area; avoid extra work self.cr.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) self.cr.clip() width, height = self.window.get_size() cr = self.cr cr.set_source_rgb(*self.cFill) cr.rectangle(0, 0, width, height) cr.fill() #figure out the scale mapping between values and pixels: maxYVal = self.maxVal maxValueText, maxValueUnits = Format.bytes_per_second(maxYVal).split( " ") x_bearing, y_bearing, w, h = cr.text_extents(maxValueText)[:4] xStart = w + self.PADDING_LEFT + self.PADDING_AXIS xEnd = width - self.PADDING_RIGHT xStepSize = float(xEnd - xStart) / float(self.NUM_VALUES) x_bearing, y_bearing, w, h = cr.text_extents("100MB/s")[:4] bottomY = height - (self.PADDING_BOTTOM + h + self.PADDING_AXIS) yScale = float(bottomY - self.PADDING_TOP) / float(maxYVal) #shade enclosed rectangle white cr.set_source_rgb(self.cInnerShade[0], self.cInnerShade[1], self.cInnerShade[2]) cr.rectangle(xStart, self.PADDING_TOP, width - self.PADDING_RIGHT - xStart, bottomY - self.PADDING_TOP) cr.fill() #labels cr.set_line_width(0.6) cr.set_font_size(self.FONT_SIZE) #vertical lines: numLines = self.NUM_VERT_LINES cr.set_source_rgb(self.cLines[0], self.cLines[1], self.cLines[2]) if self.xMiddleTics: numLines = (numLines * (self.xMiddleTics + 1)) for i in range(0, numLines + 1): if self.xMiddleTics: if i % (1 + self.xMiddleTics) == 0: cr.set_line_width(0.6) else: cr.set_line_width(0.2) s = (self.NUM_VALUES / numLines) * i #should be a dark color... x = xStart + int(xStepSize * s) cr.move_to(x, self.PADDING_TOP) cr.line_to(x, bottomY) cr.stroke() x_bearing, y_bearing, w, h = cr.text_extents( "Time (1 second step)")[:4] yPos = bottomY + self.PADDING_AXIS + h - self.lineWidth #make left label: cr.move_to(xStart, yPos) cr.show_text("Time (1 second step)") #middle label: x_bearing, y_bearing, w, h = cr.text_extents("Grid: 10 seconds")[:4] cr.move_to((xStart + xEnd) / 2 - w / 2, yPos) cr.show_text("Grid: 10 seconds") #make right label: x_bearing, y_bearing, w, h = cr.text_extents("Now")[:4] cr.move_to(xEnd - w, yPos) cr.show_text("Now") #horizontal lines: cr.set_source_rgb(self.cLines[0], self.cLines[1], self.cLines[2]) numLines = self.NUM_HORIZ_LINES if self.yMiddleTics: numLines = (numLines * (self.yMiddleTics + 1)) j = 0 for i in range(0, maxYVal + 1, maxYVal / numLines): if self.yMiddleTics: if j % (1 + self.yMiddleTics) == 0: cr.set_line_width(0.6) else: cr.set_line_width(0.2) j += 1 #should be a dark color... y = bottomY - int(yScale * i) cr.move_to(xEnd, y) cr.line_to(xStart, y) cr.stroke() #make top label: x_bearing, y_bearing, w, h = cr.text_extents("0")[:4] cr.move_to(self.PADDING_LEFT, self.PADDING_TOP + h) cr.show_text(maxValueText) #middle label: self.cr.rotate(-1 * math.pi / 2.0) x_bearing, y_bearing, w, h = cr.text_extents(maxValueUnits)[:4] cr.move_to(-1 * height / 2.0 - w / 2 + self.PADDING_TOP, self.PADDING_LEFT + h + 2) cr.show_text(maxValueUnits) self.cr.rotate(math.pi / 2.0) #make bottom label: x_bearing, y_bearing, w, h = cr.text_extents("0")[:4] cr.move_to(xStart - self.PADDING_AXIS - w, bottomY) cr.show_text("0") #draw the data lines on the graph: for sourceVals in (self.dataSource.bytesRead, self.dataSource.bytesWritten): # Set properties for the line (different colors for read and written) if sourceVals == self.dataSource.bytesWritten: cr.set_source_rgb(self.cWritten[0], self.cWritten[1], self.cWritten[2]) else: cr.set_source_rgb(self.cRead[0], self.cRead[1], self.cRead[2]) cr.set_line_width(self.lineWidth) #for every bw value, vals = sourceVals[len(sourceVals) - self.NUM_VALUES:] for i in range(0, len(vals) - 1): #draw a line segment: startX = xStart + int(xStepSize * i) endX = xStart + int(xStepSize * (i + 1)) y1 = bottomY - (vals[i] * yScale) y2 = bottomY - (vals[i + 1] * yScale) cr.move_to(startX, y1) cr.line_to(endX, y2) #Apply the ink cr.stroke() #update the maximum y value and scale for next time: newMax = 0 for v in vals: if v > newMax: newMax = v #double the scale until we contain the max value: while newMax > self.maxVal: self.maxVal *= 2 else: if newMax < self.maxVal / 2: self.scale_too_big += 1 else: self.scale_too_big = 0 #if the scale has been too big for more than 5 ticks, make it smaller if self.scale_too_big > 5: #dont go below the original axis value: if self.maxVal > 32 * 1024: self.maxVal /= 2
def connectionMade(self): self.bytesLeft = 2 * 1024 * 1024 self.transport.write(struct.pack("!I", self.bytesLeft)) self.sendEvent = Scheduler.schedule_repeat(0.1, self.send_more, 1024 * 10)
def _schedule_timeout(self, result=None): Scheduler.schedule_once(self.timeout, self.failure, TimeoutError())
else: log_msg("no gui controller yet to prompt_about_port", 2) return successFunc() def add_updater(obj): def update(): if ProgramState.DO_UPDATES: try: obj.on_update() except Exception, error: log_ex(error, "During update for %s" % (obj)) return True Scheduler.schedule_repeat(Globals.INTERVAL_BETWEEN_UPDATES, update) def get_image_file(imageName): """Given the name of an image, return the filename for the image data""" return os.path.join(Globals.DATA_DIR, unicode(imageName)) def create_error_archive(description): logs = [ "main.out", "errors.out", "stderr.out", "tor.out", "tor_conn.out", "tor_conn.out.old", "log.out.old" ] zipFile = zipfile.ZipFile(Globals.BUG_REPORT_NAME, "w") MAX_SIZE = 2 * 1024L * 1024L for log in logs:
def request_failed(self, error, httpDownloadInstance=None): self.downloadingUpdate = False log_ex(error, "Error while downloading update", [DownloadSizeError]) #lets try the full installer instead then Scheduler.schedule_once(30 * 60, self.check_for_updates)
def hash_failed(self, error): self.downloadingUpdate = False log_ex(error, "Error while verifying update") #lets just try again in half an hour or something Scheduler.schedule_once(30 * 60, self.check_for_updates)
def icon_menu_cb(self, status_icon, button, activate_time): """creates a drop down menu on the system tray icon when right clicked hopefully pay attention: both the popup menu and the menu list are passed to the trigger, which adds to both with new menuitems""" if self.popupMenu: self.popupMenu.destroy() self.popupMenu = gtk.Menu() self.allMenus = [] #note, popupMenu and menus are changed externally.... self._trigger_event("popup", self.popupMenu, self.allMenus) self.popupMenu.show() self.popupMenu.popup(None, None, None, button, activate_time) # self.popupMenu.connect("selection-done", self._recursive_menu_activate) def on_click(menu, event, popupMenu): if popupMenu != self.popupMenu: return log_msg("clicked %s %s" % (event.x, event.y), 4) if self.bestWidget: self.bestWidget.emit("activate") else: children = menu.get_children() if len(children) > 0: children[0].emit("activate") self._hide_popup_menu() return True # def debugprint(widget, eventName): # log_msg(eventName) for menuItem in self.popupMenu.get_children(): # for eventName in ("activate", "activate-item"): # menuItem.connect(eventName, debugprint, eventName) submenu = menuItem.get_submenu() if submenu: self.popupMenu.window.set_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.ENTER_NOTIFY_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.EXPOSURE_MASK | gtk.gdk.STRUCTURE_MASK) submenu.connect('button_press_event', on_click, self.popupMenu) # for eventName in ("activate-current", "selection-done"): # submenu.connect(eventName, debugprint, eventName) # self.popupMenu.window.set_events(gtk.gdk.BUTTON_PRESS_MASK) # for eventName in ("activate-current", "selection-done"): # self.popupMenu.connect(eventName, debugprint, "parent"+eventName) # self.popupMenu.connect('button_press_event', on_click) self.bestWidget = None self.isHoveringOverMenu = False self.lastHoveredOverMenu = time.time() # self.popupMenu.window.raise_() # self.popupMenu.window.set_accept_focus(True) ## self.popupMenu.window.focus() # self.popupMenu.window.set_modal_hint(True) #need to kill the popup when the mouse leaves... menus was populated in the triggered events self.allMenus.append(self.popupMenu) for menu in self.allMenus: menu.connect("enter_notify_event", self._on_hover_over_menu) menu.connect("leave_notify_event", self._on_leave_menu) if menu != self.popupMenu: for child in menu.get_children(): child.connect("enter_notify_event", self._on_hover_over_widget) child.connect("leave_notify_event", self._on_leave_widget) Scheduler.schedule_repeat(0.1, self._fade_out_window)
def __init__(self, config, Output, isAnonymous): try: self.config = config self.Output = Output self.torrent_dir = config['torrent_dir'] self.torrent_cache = {} self.file_cache = {} self.blocked_files = {} self.scan_period = config['parse_dir_interval'] self.stats_period = config['display_interval'] self.torrent_list = [] self.downloads = {} self.counter = 0 self.doneflag = Event() self.hashcheck_queue = [] self.hashcheck_current = None self.rawserver = JashRawServer() upnp_type = UPnP_test(config['upnp_nat_access']) self.listen_port = None while True: try: self.listen_port = self.rawserver.find_and_bind( config['minport'], config['maxport'], config['bind'], ipv6_socket_style=config['ipv6_binds_v4'], upnp=upnp_type, randomizer=config['random_port']) break except socketerror, e: if upnp_type and e == UPnP_ERROR: log_msg('WARNING: COULD NOT FORWARD VIA UPnP', 0) upnp_type = 0 continue self.failed("Couldn't listen - " + str(e)) return self.dht = None if isAnonymous: self.dht = dht.Proxy.DHTProxy( BitTorrent.BitTorrentClient.get()) else: if self.listen_port: self.dht = dht.Node.LocalDHTNode(self.listen_port, config['dht_file_name']) self.ratelimiter = RateLimiter(self.rawserver.add_task, config['upload_unit_size']) self.ratelimiter.set_upload_rate(config['max_upload_rate']) self.handler = MultiHandler(self.rawserver, self.doneflag, config) seed(createPeerID()) #self.rawserver.add_task(self.scan, 0) if self.scan_period: self.scan() self.scanEvent = Scheduler.schedule_repeat( self.scan_period, self.scan) else: self.scanEvent = None
def connectionMade(self): self.bytesLeft = 2 * 1024 * 1024 self.transport.write(struct.pack("!I", self.bytesLeft)) self.sendEvent = Scheduler.schedule_repeat( 0.1, self.send_more, 1024 * 10)
def start(self): self.check_for_updates() Scheduler.schedule_repeat(60 * 60 * 12, self.check_for_updates)
if controller: controller.prompt_about_port(portNum, successFunc) else: log_msg("no gui controller yet to prompt_about_port", 2) return successFunc() def add_updater(obj): def update(): if ProgramState.DO_UPDATES: try: obj.on_update() except Exception, error: log_ex(error, "During update for %s" % (obj)) return True Scheduler.schedule_repeat(Globals.INTERVAL_BETWEEN_UPDATES, update) def get_image_file(imageName): """Given the name of an image, return the filename for the image data""" return os.path.join(Globals.DATA_DIR, unicode(imageName)) def create_error_archive(description): logs = ["main.out", "errors.out", "stderr.out", "tor.out", "tor_conn.out", "tor_conn.out.old", "log.out.old"] zipFile = zipfile.ZipFile(Globals.BUG_REPORT_NAME, "w") MAX_SIZE = 2 * 1024L * 1024L for log in logs: #write the file log with name log logName = os.path.join(Globals.LOG_FOLDER, log) if Files.file_exists(logName): fileSize = os.path.getsize(logName) if fileSize > MAX_SIZE:
def _schedule_next_test(self): self.nextScheduledTest = Scheduler.schedule_once(self.SECONDS_BETWEEN_TESTS, self._start_probe)
if acoin.is_fresh(self.currentACoinInterval): addFunc(acoin) else: log_msg("Dropped an expired acoin from %s interval because we are at %s." % \ (acoin.interval,self.currentACoinInterval), 1) f.close() assert not self.ACoins, "must not load coins more than once?" read(self.ACOIN_FILE_NAME, self.add_acoin) assert not self.depositingACoins, "cannot deposit coins while loading?" read(self.DEPOSITED_FILE_NAME, self.depositingACoins.append) except Exception, e: log_ex(e, "Failed to load coins from disk") #schedule the event to save the coins, now that they are loaded #TODO: make this save way less often, this is just for debugging self.updateEvent = Scheduler.schedule_repeat(10, self.update_coins) def save_coins(self): """This function is called periodically. It checks if any coins have been added or removed from our collections, and if so, stores them back to disk.""" #if there have been any changes to our coins recently: if self.coinsChanged: #TODO: properly deal with various filesystem errors--permissions, etc :-/ try: def write(unicodeFileName, coins): fileName = System.encode_for_filesystem(unicodeFileName) #do not overwrite existing until we're sure the whole file has been output newFileName = fileName + ".new" f = open(newFileName, "wb") msg = ""