def __init__(self, parent, lrf_stream, logger, opts): QThread.__init__(self, parent) self.stream, self.logger, self.opts = lrf_stream, logger, opts self.aborted = False self.lrf = None self.document = None self.exception = None
def __init__(self, parent): QThread.__init__(self, parent) self.keep_going = True self.current_command = None self.out_queue = Queue() self.address = arbitrary_address('AF_PIPE' if iswindows else 'AF_UNIX') self.auth_key = os.urandom(32) if iswindows and self.address[1] == ':': self.address = self.address[2:] self.listener = Listener(address=self.address, authkey=self.auth_key, backlog=4) self.env = { 'CALIBRE_SIMPLE_WORKER': 'calibre.utils.pyconsole.interpreter:main', 'CALIBRE_WORKER_ADDRESS': hexlify(cPickle.dumps(self.listener.address, -1)), 'CALIBRE_WORKER_KEY': hexlify(self.auth_key) } self.process = Process(self.env) self.output_file_buf = self.process(redirect_output=False) self.conn = self.listener.accept() self.start()
def start_sync(self): self.log_btn.show() self.log.setRowCount(0) self.log.show() self.worker_thread = QThread(self) book_ids = self.valid_book_ids if self.limits['total_books']: book_ids = book_ids[:self.limits['total_books']] self.total = len(book_ids) self.worker = UploadManager( self.db, self.logger, book_ids, self.sync_selected_radio.isChecked() and self.reupload_checkbox.isChecked()) self.worker.finished.connect(self.finish_sync) self.worker.finished.connect(self.worker_thread.quit) self.worker.progress.connect(self.update_progress) self.worker.uploadProgress.connect(self.update_upload_progress) self.worker.started.connect(self.log_start) self.worker.skipped.connect(self.log_skip) self.worker.failed.connect(self.log_fail) self.worker.uploaded.connect(self.log_upload) self.worker.updated.connect(self.log_update) self.worker.aborted.connect(self.abort) self.worker.moveToThread(self.worker_thread) self.worker_thread.started.connect(self.worker.start) self.worker_thread.start()
def __init__(self, parent, db, root, single, tdir=None): QThread.__init__(self, parent) self.db = db self.path = root self.tdir = tdir self.single_book_per_directory = single self.canceled = False
def __init__(self, party_1, party_2, number_of_pairs, random_source, cancellation_event, key_manager, console_signal, key_directory, parent, key_length=1000000): QThread.__init__(self, parent) self._party_1 = party_1 self._party_2 = party_2 self._number_of_pairs = int(number_of_pairs) self._random_source = random_source # Select appropriate random function. if self._random_source == '/dev/random (slow!)': self._random_function = self._dev_random else: self._random_function = self._os_urandom # Attach cancel button signal to cancel function. self._cancellation_event = cancellation_event self._km = key_manager self._cs = console_signal self._key_directory = key_directory self._parent = parent self._key_length = key_length self._VERSION = self._km.VERSION
def on_pushButton_login_released(self): QThread.msleep(200) login_type = self.login() if login_type != 0: print("登录成功") try: self.dialog_text("登录成功", "登录提示") if login_type == UILogin.WIN_EXTERN_ADMINI: self.win_ad = UIAdmini(self.win_main, ano=self.username.text(), pushbutton=self) self.win_ad.show() elif login_type == UILogin.WIN_EXTERN_SALEMAN: self.win_smMenu = UISMMenu(self.win_main, 0, 0, 1, 2, sMno=self.username.text(), pushButton=self) self.win_smMenu.show() except TypeError: print("This Win is NO exist") except AttributeError: print("win Errow") finally: self.close() else: print("登录失败") QThread.msleep(200)
def __init__(self, parent_ui, nff_publish): QThread.__init__(self) self.ui = parent_ui try: context = zmq.Context() self.publish_socket = context.socket(zmq.PUB) self.publish_socket.bind(nff_publish) except: print("ERROR: Cannot connect to sockets!") sys.exit() # Try to open the text file with all of the packets to send and exit # if it fails to open. try: infile = open('nff-packets.txt', 'r') except: print('Error: couldn\'t open nff-packets.txt') return # Read all of the packets and store the total number to keep track of progress. self.all_lines = infile.readlines() self.num_lines = len(self.all_lines) # init UI self.ui.nff_sim_progress_bar.setValue(0) self.console = self.ui.nff_console
def startScan(self, ipRanges, portsStr, threadNumber, timeout): timeout = 3 if not timeout else int(timeout) addresses = None parser_args = {'port_field': portsStr, 'address_field': ipRanges} fields = self.parser.parse_fields(*get_converted_arguments( self.parser.parse_fields, parser_args, convert_table)) self.scanner = CoreModel(timeout) if CoreModel.INDEPENDENT_THREAD_MANAGEMENT: addresses = self.parser.get_all_addresses(ipRanges) self.ip_generator = PlugAddressGenerator(addresses, ports) threadNumber = 1 else: self.ip_generator = IpGenerator() self.ip_generator.set_parsed_fields(*get_converted_arguments( self.ip_generator.set_parsed_fields, fields, convert_table)) threadNumber = int(threadNumber) print("thread %i number set" % threadNumber) for i in range(threadNumber): print(i) scan_worker = ScanWorker(self.ip_generator, self.scanner, self.storage) scan_thread = QThread() scan_worker.log_signal.connect(self.log_text) scan_worker.moveToThread(scan_thread) scan_worker.exit_signal.connect(scan_thread.exit) scan_worker.exit_signal.connect(self.on_worker_exit) scan_thread.started.connect(scan_worker.work) self.threads.append((scan_worker, scan_thread)) for thread in self.threads: scan_worker, scan_thread = thread print("starting") scan_thread.start() self.changeThreadLabel(threadNumber)
def __init__(self, plugin_id, address, socket): QThread.__init__(self) self.plugin_id = plugin_id self.address = address self.udp_socket = socket self.finished.connect(self.quit) self.wait = QWaitCondition() self.mutex = QMutex()
def __init__(self, gui, field, get_date_range=False): QThread.__init__(self, gui) self.annotation_map = [] self.cdb = gui.current_db self.get_date_range = get_date_range self.newest_annotation = 0 self.oldest_annotation = mktime(datetime.today().timetuple()) self.field = field
def __init__(self, case_path, loop, delay): QThread.__init__(self) self.case_path = case_path.split("/test/") self.rootPath = self.case_path[0] self.record = time.strftime("%Y-%m-%d_%H-%M-%S") self.spath = self.rootPath + "/report/" + "test_" + self.record self.jsonFile = "project.json" self.loop = loop self.delay = delay
class MainWindow(QMainWindow): signal_stop_worker = pyqtSignal() def __init__(self): super(MainWindow, self).__init__() self.top: int = 400 self.left: int = 400 self.width: int = 600 self.height: int = 500 self.setGeometry(self.top, self.left, self.width, self.height) self.layout = QVBoxLayout() self.btn_start = QPushButton() self.btn_start.clicked.connect(self.start_manager) self.btn_start.setText("Start") self.btn_stop = QPushButton() self.btn_stop.clicked.connect(self.stop_manager) self.btn_stop.setText("Stop") self.status_label = QLabel() self.layout.addWidget(self.btn_start) self.layout.addWidget(self.btn_stop) self.layout.addWidget(self.status_label) self.central_widget = QWidget() self.central_widget.setLayout(self.layout) self.setCentralWidget(self.central_widget) self.manager_thread = None self.manager_worker = None @pyqtSlot(ManagerStatus) def manager_status_change(self, status): self.status_label.setText(status.value) def stop_manager(self): self.signal_stop_worker.emit() def start_manager(self): self.manager_thread = QThread() env = { 'DOCKER_CERT_PATH': '', 'DOCKER_HOST': 'tcp://10.0.0.17:2375', 'DOCKER_TLS_VERIFY': '' } self.manager_worker = Manager(env=env) self.manager_thread.setObjectName("Manager Thread") self.manager_worker.signals().status_change.connect( self.manager_status_change) self.signal_stop_worker.connect(self.manager_worker.abort) self.manager_worker.moveToThread(self.manager_thread) self.manager_thread.started.connect(self.manager_worker.run) self.manager_thread.start()
def __init__(self, import_path, key_manager, console_signal, key_directory, parent): QThread.__init__(self, parent) self._import_path = import_path self._km = key_manager self._console_signal = console_signal self._key_directory = key_directory self._parent = parent self._total_key_count = 0 self._successful_key_count = 0 self._unsuccessful_key_count = 0
def __init__(self, parent=None): QThread.__init__(self, parent=parent) self.threshold = 70 self.arq_predicao = "IAs\\shape_predictor_68_face_landmarks.dat" self.detector = dlib.get_frontal_face_detector() self.predicao = dlib.shape_predictor(self.arq_predicao) self.judite = MensagemFalada() self.analisePERCLOS = AnalisePERCLOS() arquivoCalibracao = ArquivoCalibracao() self.valorMaximo, self.valorMinimo, self.nome = arquivoCalibracao.abrirArquivoCalibracao()
def run(self): while True: # Делаем какие-то действия и проверки, и вызываем сигнал about_update, # чтобы сообщить о новой версии # ... # if ...: self.about_update.emit('Доступна новая версия 2.1.1') # 6 hours QThread.sleep(6 * 60 * 60)
def must_use_qt(headless=True): ''' This function should be called if you want to use Qt for some non-GUI task like rendering HTML/SVG or using a headless browser. It will raise a RuntimeError if using Qt is not possible, which will happen if the current thread is not the main GUI thread. On linux, it uses a special QPA headless plugin, so that the X server does not need to be running. ''' global gui_thread ensure_app(headless=headless) if gui_thread is None: gui_thread = QThread.currentThread() if gui_thread is not QThread.currentThread(): raise RuntimeError('Cannot use Qt in non GUI thread')
def on_start_button_clicked(self): """ 点击开始按钮 """ try: self.start_button.setEnabled(False) self.Tstart_button.setEnabled(False) self.LtranslationButton.setEnabled(False) self.RtranslationButton.setEnabled(False) self.reset_button.setEnabled(False) self.parameter = "长度:{}mm,平移速度{}mm/s,旋转速度{}Hz".format(self.Capillary_length_box.value(), self.Velocity_box.value(), self.rotate_spinBox.value()) displacement = self.Capillary_length_box.value() * 100 # displacement平移距离,单位10um,300mm=30000*10um if displacement < 0: direction = "1" # 左移 elif displacement > 0: direction = "3" # 右移 #demo = bytes(demo_s, encoding="utf8") #self.A.ser.write(demo) QThread.msleep(500) velocity2 = self.Velocity_box.value() * 100 # 平移速度 time_S = 1000 / velocity2 #print(displacement) #print(time_S) self.thread = Thread_start_button() self.thread.setIdentity(direction,displacement, int(time_S),self.A) self.thread._signal2.connect(self.progress_bar_control) self.thread._signal.connect(self.start_button_end) self.thread.start() self.textEdit2.setText("加工线程开启") localtime = time.localtime(time.time()) time_s = time.strftime("%Y-%m-%d %H:%M:%S", localtime) s_r = "时间:{}参数({})开始执行\n".format(time_s, self.parameter) self.logW(s_r) except: self.start_button.setEnabled(True) self.Tstart_button.setEnabled(True) self.LtranslationButton.setEnabled(True) self.RtranslationButton.setEnabled(True) self.reset_button.setEnabled(True) self.textEdit.setText("开始加工失败") localtime = time.localtime(time.time()) time_s = time.strftime("%Y-%m-%d %H:%M:%S", localtime) s_r = "时间:{}参数({})加工执行失败\n".format(time_s, self.parameter) self.logW(s_r)
def __init__(self): QThread.__init__(self) self.qscm = QtSlamClient(server_adress=('127.0.0.1', 2207)) self.th = QThread() self.qscm.connect() self.qscm.moveToThread(self.th) self.qscm.start() self.semaphore_image = True self.semaphore_trajectory = True self.response_data = ' ' self.qscm.image_response[bytes].connect(self.semaphore_image_off) self.qscm.trajectory_response[bytes].connect( self.semaphore_trajectory_off)
def __init__(self, parent_ui, input_addr, output_addr): QThread.__init__(self) self.ui = parent_ui context = zmq.Context() self.input_socket = context.socket(zmq.SUB) self.input_socket.connect(input_addr) self.input_socket.setsockopt_string(zmq.SUBSCRIBE, "") self.output_socket = context.socket(zmq.PUB) self.output_socket.bind(output_addr) self.processor = TelemetryProcessor()
def __init__(self, parent=None, nome="", framesCalibragem=100, threshold=70): QThread.__init__(self, parent=parent) self.framesCalibragem = framesCalibragem self.threshold = threshold self.usuario = nome self.arq_predicao = "IAs\\shape_predictor_68_face_landmarks.dat" self.detector = dlib.get_frontal_face_detector() self.predicao = dlib.shape_predictor(self.arq_predicao) self.judite = MensagemFalada() self.analisePERCLOS = AnalisePERCLOS()
def start_manager(self): self.manager_thread = QThread() env = { 'DOCKER_CERT_PATH': '', 'DOCKER_HOST': 'tcp://10.0.0.17:2375', 'DOCKER_TLS_VERIFY': '' } self.manager_worker = Manager(env=env) self.manager_thread.setObjectName("Manager Thread") self.manager_worker.signals().status_change.connect( self.manager_status_change) self.signal_stop_worker.connect(self.manager_worker.abort) self.manager_worker.moveToThread(self.manager_thread) self.manager_thread.started.connect(self.manager_worker.run) self.manager_thread.start()
def rock(server_address): app = QApplication(sys.argv) ex = WebView(server_address) # ex.metaObject().invokeMethod(ex,'test_function',Qt.QueuedConnection) return ex, app, QThread.currentThread()
def must_use_qt(): ''' This function should be called if you want to use Qt for some non-GUI task like rendering HTML/SVG or using a headless browser. It will raise a RuntimeError if using Qt is not possible, which will happen if the current thread is not the main GUI thread. On linux, it uses a special QPA headless plugin, so that the X server does not need to be running. ''' global gui_thread, _store_app if _store_app is None and QApplication.instance() is None: args = sys.argv[:1] if islinux or isbsd: args += ['-platformpluginpath', sys.extensions_location, '-platform', 'headless'] _store_app = QApplication(args) if gui_thread is None: gui_thread = QThread.currentThread() if gui_thread is not QThread.currentThread(): raise RuntimeError('Cannot use Qt in non GUI thread')
def __init__(self, updater): super().__init__(QEvent.User) self._updater = updater self._result = None self._semaphore = QSemaphore(1) if QCoreApplication.instance().thread() != QThread.currentThread(): self._semaphore.acquire()
def __init__(self,parent = None): super(Compress,self).__init__(parent) self.createList() self._process = QProcess(self) self._thread = QThread() self.moveToThread(self._thread) self._thread.start() self._fileName = "" self._outPath = "" self.startRunning.connect(self.startCompress) self._process.readyReadStandardOutput.connect(self.readMsg) self._process.readyReadStandardError.connect(self.readError) self._process.finished.connect(self.finished)
def __init__(self, parent, db, device, annotation_map, done_callback): QThread.__init__(self, parent) self.errors = {} self.db = db self.keep_going = True self.pd = ProgressDialog(_('Merging user annotations into database'), '', 0, len(annotation_map), parent=parent) self.device = device self.annotation_map = annotation_map self.done_callback = done_callback self.pd.canceled_signal.connect(self.canceled) self.pd.setModal(True) self.pd.show() self.update_progress.connect(self.pd.set_value, type=Qt.QueuedConnection) self.update_done.connect(self.pd.hide, type=Qt.QueuedConnection)
def using_q_thread(): app = QCoreApplication([]) thread = MainApp() th = QThread() thread.finished.connect(app.exit) thread.moveToThread(th) thread.start() sys.exit(app.exec_())
def __init__(self, party_1, party_2, all_keys, console_signal, key_directory, main_export_directory, parent): QThread.__init__(self, parent) self._party_1 = party_1 self._party_2 = party_2 self._parent = parent self._keys = all_keys self._console_signal = console_signal self._main_export_directory = main_export_directory self._key_directory = key_directory self._timestamp = '{0:.7f}'.format(time.time()) self._export_package_dir = os.path.join(self._main_export_directory, self._timestamp) os.makedirs(self._export_package_dir) self._keys_to_copy = [] self._keys_copied_count = 0 self._keys_missed_count = 0
def start(self): if self.sync_selected_radio.isChecked( ) and self.reupload_checkbox.isChecked(): reply = QMessageBox.question( self, 'BookFusion Sync', 'Re-uploading book files can potentially result in previous highlights or bookmarks no longer working.\n\nPreviously uploaded files will be overwritten. Are you sure you want to re-upload?', QMessageBox.No | QMessageBox.Yes, QMessageBox.Yes) if reply != QMessageBox.Yes: return self.worker = None self.valid_book_ids = None self.book_log_map = {} self.book_progress_map = {} if self.sync_selected_radio.isChecked(): book_ids = list(self.selected_book_ids) else: book_ids = list(self.db.all_book_ids()) self.logger.info('Start sync: sync_selected={}; book_ids={}'.format( self.sync_selected_radio.isChecked(), book_ids)) self.in_progress = True self.total = len(book_ids) self.update_progress(None) self.start_btn.hide() self.cancel_btn.show() self.config_btn.setEnabled(False) self.sync_all_radio.setEnabled(False) self.sync_selected_radio.setEnabled(False) self.worker_thread = QThread(self) self.worker = CheckWorker(self.db, self.logger, book_ids) self.worker.finished.connect(self.finish_check) self.worker.finished.connect(self.worker_thread.quit) self.worker.progress.connect(self.update_progress) self.worker.limitsAvailable.connect(self.apply_limits) self.worker.resultsAvailable.connect(self.apply_results) self.worker.aborted.connect(self.abort) self.worker.moveToThread(self.worker_thread) self.worker_thread.started.connect(self.worker.start) self.worker_thread.start()
def __init__(self, serial1=Bearing_Serial('COM1', 9600, 'modbus'), serial2=Bearing_Serial('COM2', 9600, 'serial')): super(Read_Thread, self).__init__() self._thread = QThread() self.moveToThread(self._thread) self._serial1 = serial1 self._serial2 = serial2 self._stop = 0
def must_use_qt(): ''' This function should be called if you want to use Qt for some non-GUI task like rendering HTML/SVG or using a headless browser. It will raise a RuntimeError if using Qt is not possible, which will happen if the current thread is not the main GUI thread. On linux, it uses a special QPA headless plugin, so that the X server does not need to be running. ''' global gui_thread, _store_app if _store_app is None and QApplication.instance() is None: args = sys.argv[:1] if islinux or isbsd: args += [ '-platformpluginpath', sys.extensions_location, '-platform', 'headless' ] _store_app = QApplication(args) if gui_thread is None: gui_thread = QThread.currentThread() if gui_thread is not QThread.currentThread(): raise RuntimeError('Cannot use Qt in non GUI thread')
def __init__(self, args, force_calibre_style=False, override_program_name=None, headless=False, color_prefs=gprefs): self.file_event_hook = None if override_program_name: args = [override_program_name] + args[1:] if headless: if not args: args = sys.argv[:1] args.extend(['-platformpluginpath', sys.extensions_location, '-platform', 'headless']) qargs = [i.encode('utf-8') if isinstance(i, unicode) else i for i in args] self.pi = plugins['progress_indicator'][0] QApplication.__init__(self, qargs) self.setup_styles(force_calibre_style) f = QFont(QApplication.font()) if (f.family(), f.pointSize()) == ('Sans Serif', 9): # Hard coded Qt settings, no user preference detected f.setPointSize(10) QApplication.setFont(f) f = QFontInfo(f) self.original_font = (f.family(), f.pointSize(), f.weight(), f.italic(), 100) if not self.using_calibre_style and self.style().objectName() == 'fusion': # Since Qt is using the fusion style anyway, specialize it self.load_calibre_style() fi = gprefs['font'] if fi is not None: font = QFont(*(fi[:4])) s = gprefs.get('font_stretch', None) if s is not None: font.setStretch(s) QApplication.setFont(font) dl = QLocale(get_lang()) if unicode(dl.bcp47Name()) != u'C': QLocale.setDefault(dl) global gui_thread, qt_app gui_thread = QThread.currentThread() self._translator = None self.load_translations() qt_app = self self._file_open_paths = [] self._file_open_lock = RLock() if not isosx: # OS X uses a native color dialog that does not support custom # colors self.color_prefs = color_prefs self.read_custom_colors() self.lastWindowClosed.connect(self.save_custom_colors) if isxp: error_dialog(None, _('Windows XP not supported'), '<p>' + _( 'calibre versions newer than 2.0 do not run on Windows XP. This is' ' because the graphics toolkit calibre uses (Qt 5) crashes a lot' ' on Windows XP. We suggest you stay with <a href="%s">calibre 1.48</a>' ' which works well on Windows XP.') % 'http://download.calibre-ebook.com/1.48.0/', show=True) raise SystemExit(1)
def detect_ncpus(): """Detects the number of effective CPUs in the system""" if iswindows: import win32api ans = win32api.GetSystemInfo()[5] else: import multiprocessing ans = -1 try: ans = multiprocessing.cpu_count() except Exception: from PyQt5.Qt import QThread ans = QThread.idealThreadCount() return max(1, ans)
def __init__(self, func, queued=True, parent=None): global gui_thread if gui_thread is None: gui_thread = QThread.currentThread() if not is_gui_thread(): raise ValueError( 'You can only create a FunctionDispatcher in the GUI thread') QObject.__init__(self, parent) self.func = func typ = Qt.QueuedConnection if not queued: typ = Qt.AutoConnection if queued is None else Qt.DirectConnection self.dispatch_signal.connect(self.dispatch, type=typ) self.q = Queue.Queue() self.lock = threading.Lock()
def _initServer(self): self.message("Server - initServer / threadId=" + str(int(QThread.currentThreadId()))) try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as exc: raise ServerException("Socket creation failed: {0}".format(exc)); try: # Bind socket to ip 127.0.0.1 on port 1234 self.socket.bind(('127.0.0.1', 1234)); except socket.error as exc: self.socket.close(); raise ServerException("Socket bind failed: {0}".format(exc)); self.message("Server - Bind successfull") # Accept 1 connection self.socket.listen(5);
def __init__(self, args, force_calibre_style=False, override_program_name=None, headless=False): self.file_event_hook = None if override_program_name: args = [override_program_name] + args[1:] if headless: if not args: args = sys.argv[:1] args.extend(['-platformpluginpath', sys.extensions_location, '-platform', 'headless']) qargs = [i.encode('utf-8') if isinstance(i, unicode) else i for i in args] self.pi = plugins['progress_indicator'][0] self.setup_styles(force_calibre_style) QApplication.__init__(self, qargs) f = QFont(QApplication.font()) if (f.family(), f.pointSize()) == ('Sans Serif', 9): # Hard coded Qt settings, no user preference detected f.setPointSize(10) QApplication.setFont(f) f = QFontInfo(f) self.original_font = (f.family(), f.pointSize(), f.weight(), f.italic(), 100) if not self.using_calibre_style and self.style().objectName() == 'fusion': # Since Qt is using the fusion style anyway, specialize it self.load_calibre_style() fi = gprefs['font'] if fi is not None: font = QFont(*(fi[:4])) s = gprefs.get('font_stretch', None) if s is not None: font.setStretch(s) QApplication.setFont(font) dl = QLocale(get_lang()) if unicode(dl.bcp47Name()) != u'C': QLocale.setDefault(dl) global gui_thread, qt_app gui_thread = QThread.currentThread() self._translator = None self.load_translations() qt_app = self self._file_open_paths = [] self._file_open_lock = RLock()
def is_gui_thread(): global gui_thread return gui_thread is QThread.currentThread()
def __init__(self, parent): QThread.__init__(self, parent) self.cdb = parent.opts.gui.current_db self.title_map = None self.uuid_map = None
import sys from PyQt5.QtWidgets import QApplication from ServerUi.serverdialog import ServerDialog from PyQt5.Qt import QDialog, QThread if __name__ == '__main__': print("main: threadId="+str(int(QThread.currentThreadId()))) app = QApplication(sys.argv) window = QDialog() w = ServerDialog() w.show() sys.exit(app.exec_())
def _serverLoop(self): threads = [] threadId = 0 connection = None; raddr = None; while True: try: # Wait for connection connection = self.socket.accept(); raddr = connection[1]; except socket.error as exc: self.socket.close(); self.message("Server - Join threads") for t in threads: t.wait() quitMutex.lock() quitCopy = self.quit quitMutex.unlock() # If the exception was intentional do not reraise it. if quitCopy==True and exc.errno==10004: break; raise ServerException("Socket accept failed: {0}".format(exc)); self.message("Server - Incoming Connection by %s / threadId=%s" % (str(raddr), str(int(QThread.currentThreadId())))) newthread = ClientConnection(connection, self.message, threadId) newthread.start(QThread.HighPriority) threads.append(newthread) threadId = threadId + 1 self.message("Server - Stop")
def __init__(self, parent): QThread.__init__(self, parent)
def __init__(self, args, force_calibre_style=False, override_program_name=None, headless=False, color_prefs=gprefs): self.file_event_hook = None if override_program_name: args = [override_program_name] + args[1:] if headless: if not args: args = sys.argv[:1] args.extend(['-platformpluginpath', sys.extensions_location, '-platform', 'headless']) self.headless = headless qargs = [i.encode('utf-8') if isinstance(i, unicode) else i for i in args] self.pi = plugins['progress_indicator'][0] QApplication.__init__(self, qargs) if islinux or isbsd: self.setAttribute(Qt.AA_DontUseNativeMenuBar, 'CALIBRE_NO_NATIVE_MENUBAR' in os.environ) self.setup_styles(force_calibre_style) f = QFont(QApplication.font()) if (f.family(), f.pointSize()) == ('Sans Serif', 9): # Hard coded Qt settings, no user preference detected f.setPointSize(10) QApplication.setFont(f) f = QFontInfo(f) self.original_font = (f.family(), f.pointSize(), f.weight(), f.italic(), 100) if not self.using_calibre_style and self.style().objectName() == 'fusion': # Since Qt is using the fusion style anyway, specialize it self.load_calibre_style() fi = gprefs['font'] if fi is not None: font = QFont(*(fi[:4])) s = gprefs.get('font_stretch', None) if s is not None: font.setStretch(s) QApplication.setFont(font) dl = QLocale(get_lang()) if unicode(dl.bcp47Name()) != u'C': QLocale.setDefault(dl) global gui_thread, qt_app gui_thread = QThread.currentThread() self._translator = None self.load_translations() qt_app = self self._file_open_paths = [] self._file_open_lock = RLock() if not isosx: # OS X uses a native color dialog that does not support custom # colors self.color_prefs = color_prefs self.read_custom_colors() self.lastWindowClosed.connect(self.save_custom_colors) if isxp: error_dialog(None, _('Windows XP not supported'), '<p>' + _( 'calibre versions newer than 2.0 do not run on Windows XP. This is' ' because the graphics toolkit calibre uses (Qt 5) crashes a lot' ' on Windows XP. We suggest you stay with <a href="%s">calibre 1.48</a>' ' which works well on Windows XP.') % 'http://download.calibre-ebook.com/1.48.0/', show=True) raise SystemExit(1) if iswindows: # On windows the highlighted colors for inactive widgets are the # same as non highlighted colors. This is a regression from Qt 4. # https://bugreports.qt-project.org/browse/QTBUG-41060 p = self.palette() for role in (p.Highlight, p.HighlightedText, p.Base, p.AlternateBase): p.setColor(p.Inactive, role, p.color(p.Active, role)) self.setPalette(p) # Prevent text copied to the clipboard from being lost on quit due to # Qt 5 bug: https://bugreports.qt-project.org/browse/QTBUG-41125 self.aboutToQuit.connect(self.flush_clipboard)
def stopServerClicked(self): self.message("ServerDialog.stopServerClicked - Start / threadId="+str(int(QThread.currentThreadId()))) self.worker.stopServer();
def qtThreadId(self): return(format(int(QThread.currentThreadId()),"02x"))
def __init__(self, parent=None): QThread.__init__(self, parent) self.canceled = False self.cancel_callback = lambda : self.canceled self.folders = set([]) self.books = []
def __init__(self, host="0.0.0.0", port=9919): QThread.__init__(self) self.host = host self.port = port