def quit(self): if self.hasQuit: return self.hasQuit = True import curtheme curtheme.unload() for w in self.widgets: if w.isVisible(): w.hide() # wait for for done or kill all threads from PySide.QtCore import QThreadPool if QThreadPool.globalInstance().activeThreadCount(): dwarn("warning: wait for active threads") QThreadPool.globalInstance().waitForDone(config.QT_THREAD_TIMEOUT) dprint("leave qthread pool") dprint("send quit signal to qApp") qApp = QCoreApplication.instance() # Make sure settings.sync is the last signal conneced with aboutToQuit #qApp.aboutToQuit.connect(self.settings.sync) skevents.runlater(qApp.quit)
def testSlowJobs(self): for i in range(3): task = Task() QThreadPool.globalInstance().start(task) time.sleep(1) # Sleep 1 second QThreadPool.globalInstance().waitForDone()
def quit(self): if self.hasQuit: return self.hasQuit = True dprint("schedule to kill all python instances in a few seconds") skevents.runlater(lambda: os.system("tskill pythonw & tskill python"), config.QT_QUIT_TIMEOUT + config.QT_THREAD_TIMEOUT) # wait for for done or kill all threads from PySide.QtCore import QThreadPool if QThreadPool.globalInstance().activeThreadCount(): dwarn("warning: wait for active threads") QThreadPool.globalInstance().waitForDone(config.QT_THREAD_TIMEOUT) dprint("leave qthread pool") dprint("send quit signal to qApp") qApp = QCoreApplication.instance() # Make sure settings.sync is the last signal conneced with aboutToQuit #qApp.aboutToQuit.connect(self.settings.sync) skevents.runlater(qApp.quit)
def __loadInitialFieldValues(self): runnable = ProgressRunnable2(self.gui.getInfiniteProgressDialog()) runnable.setDialogMessage("Loading...") runnable.setRunMethod(self.manager.getObsServerList, reachable=True) runnable.finished[object].connect(self.__loadServerList) if not self.__isNewProject(): runnable.finished.connect(self.__loadKnownProjectValues) QThreadPool.globalInstance().start(runnable)
def execute(self, id_, data=None): """Generate the relation graph.""" if not data: data = self.read(id_) self.executed.emit('dependency', id_, data) worker = GraphWorker(id_, data, lambda: self._execute(id_, data)) worker.result_ready.connect(self._process_result) worker.exception_raised.connect(self._handle_exception) QThreadPool.globalInstance().start(worker)
def runOnGlobalInstance(self, wait=False): """ Run this ProgressRunnable on the global QThreadPool instance. If `wait` is True, process the UI events while waiting for the ProgressRunnable to finish. """ QThreadPool.globalInstance().start(self) if wait: # self.__finishedCalled is made True by the setHasFinished() # method, which is called from try/finally blocks so guaranteed # to be called even if there are exceptions. while not self.__finishedCalled: sleep(0.01) QApplication.processEvents()
def run(self): L.d("running") self.stopvar = False rex = re.compile(".*\[(\d{7})\]$") imdb_db = imdb.IMDb() db = get_user_db() tp = QThreadPool.globalInstance() writer = IndexWriter() count = 0 it = QDirIterator(self.media_path, QDirIterator.Subdirectories) while it.hasNext(): dir = it.next() try: directory = unicode(dir) match = rex.match(directory) if match: count += 1 imdb_id = match.group(1) movie = db.get_doc(imdb_id) if movie: L.d("%s already in db - skipping" % imdb_id) else: j = Job(imdb_db, imdb_id, self) j.obj.finished.connect(writer.index_movie, Qt.QueuedConnection) tp.start(j) except: pass print count self.exec_()
def on_configDialog_accepted(self): progress = self.gui.getInfiniteProgressDialog() runnable = ProgressRunnable2() runnable.setProgressDialog(progress) if self.__oldRepoAlias is None: runnable.setDialogMessage( "Importing repository in project file system...") runnable.setRunMethod(self.manager.addRepo, self.__projectAlias, repoUrl=self.getRepoUrl(), alias=self.getRepoAlias()) else: runnable.setDialogMessage("Modifying repository...") runnable.setRunMethod(self.manager.modifyRepo, self.__projectAlias, self.__oldRepoAlias, newUrl=self.getRepoUrl(), newAlias=self.getRepoAlias()) runnable.caughtException.connect(self.gui.popupErrorCallback) QThreadPool.globalInstance().start(runnable)
def importFromProject(self): """ Run this method in order to add the repository of another OBS project. """ projects = self.manager.getLocalProjectList() selectedProject, accepted = QInputDialog.getItem( self.mainWindow, "Select project", "Project to import repository from:", projects, editable=False) if not accepted: return progress = self.gui.getInfiniteProgressDialog() runnable = ProgressRunnable2() runnable.setProgressDialog(progress) runnable.setDialogMessage("Importing repository...") runnable.setRunMethod(self.manager.addRepo, self.__projectAlias, fromProject=selectedProject) runnable.caughtException.connect(self.gui.popupErrorCallback) QThreadPool.globalInstance().start(runnable)
def on_configDialog_accepted(self): if self.__isNewProject(): runnable = ProgressRunnable2(self.gui.getInfiniteProgressDialog()) runnable.setDialogMessage("Importing project...") runnable.caughtException.connect(self.gui.popupErrorCallback) runnable.setRunMethod( self.manager.addProject, self.getCurrentServerAlias(), self.getCurrentProjectObsName(), self.getCurrentTarget(), self.getCurrentArch(), projectLocalName=self.getCurrentProjectLocalName()) def emitFinished(): self.finished.emit(True) runnable.finished.connect(emitFinished) QThreadPool.globalInstance().start(runnable) else: # Currently we can't relocate a project. # self.manager.setProjectParameter(self.getCurrentProjectLocalName(), # "projectObsName", # self.getCurrentProjectObsName()) # self.manager.setProjectParameter(self.getCurrentProjectLocalName(), # "obsServer", # self.getCurrentServerAlias()) # self.manager.setProjectParameter(self.getCurrentProjectLocalName(), # u"projectTarget", # self.getCurrentTarget()) # self.manager.setProjectParameter(self.getCurrentProjectLocalName(), # u"projectArchitecture", # self.getCurrentArch()) self.manager.setProjectParameter(self.getCurrentProjectLocalName(), u"title", self.getCurrentTitle()) self.manager.setProjectParameter(self.getCurrentProjectLocalName(), u"description", self.getCurrentDescription()) self.finished.emit(True)
def deleteRepo(self): """ Run this method to remove a repository from the project file system. """ repos = self.manager.getChRootRepositories(self.__projectAlias) if repos is None or len(repos) < 1: return selectedAlias, accepted = QInputDialog.getItem( self.mainWindow, "Select repository", "Project repository to delete:", repos.keys(), editable=False) if not accepted: return progress = self.gui.getInfiniteProgressDialog() runnable = ProgressRunnable2() runnable.setProgressDialog(progress) runnable.setDialogMessage("Deleting repository...") runnable.setRunMethod(self.manager.deleteRepo, self.__projectAlias, selectedAlias) runnable.caughtException.connect(self.gui.popupErrorCallback) QThreadPool.globalInstance().start(runnable)
def startSimu(self): self.log("=== SIMULATIONS START ===") self.logText.clear() self.startTime = datetime.now() self.simulations = [] #self.nextPrate = 0 self.gapPrate = self.gapPrateOption.getValue() self.sameSimuTimes = self.sameSimuTimesOption.getValue() #self.nextSimu = 0 self.blockUi() self.simulationsDone = 0 #output = self.pathOption.getValue() + dateToFilename(d) + '_results.txt' pRate = 0 self.simulationsTotal = 0 # print 'sameSimuTimes: %d'%self.sameSimuTimes # print 'gapPrate: %d'%self.gapPrate while pRate <= 100: simu = 0 self.options['prate'] = pRate while simu<self.sameSimuTimes: waf = WafThread(self.options, self.pathOption.getValue(), self.scenarioOption.getName()) waf.setAutoDelete(True) waf.simuDone.connect(self.wafDone) self.simulations.append(waf) QThreadPool.globalInstance().start(waf) self.simulationsTotal += 1 simu += 1 pRate += self.gapPrate runningSimulations = 'Running %d Simulations...' % self.simulationsTotal self.startButton.setText(runningSimulations) self.log(runningSimulations) self.progressBar.setRange(0,self.simulationsTotal) self.progressBar.setValue(0) # 300 seconds per task average roughTime = self.simulationsTotal*self.resultsWidget.averageSimulationTime/QThreadPool.globalInstance().maxThreadCount() self.infoLabel.setText('Rough time estimation: %s' % formatTimeLeft(roughTime))
caughtException.traceback = traceback_ results.append((arg, 1)) finally: if caughtException is not None: self.setHasCaughtException(caughtException) self.setHasProgressed() except: print sys.exc_info() finally: self.setHasFinished(results) self.deleteLater() self.run = run QThreadPool.globalInstance().setExpiryTimeout(0) def firstArgLast(func): """ Return a function which will call 'func' with first argument as last argument. """ def swappedArgsFunc(*args, **kwargs): newArgs = list(args[1:]) newArgs.append(args[0]) return func(*newArgs, **kwargs) return swappedArgsFunc
def _shutdown(self): tp = QThreadPool.globalInstance() L.d("waiting for threadpool to be done...") tp.waitForDone() self.quit()
else: j = Job(imdb_db, imdb_id, self) j.obj.finished.connect(writer.index_movie, Qt.QueuedConnection) tp.start(j) except: pass print count self.exec_() def set_stopped(self): L.d("setting stopvar") self.stopvar = True QTimer.singleShot(10, self._shutdown) def _shutdown(self): tp = QThreadPool.globalInstance() L.d("waiting for threadpool to be done...") tp.waitForDone() self.quit() if __name__ == "__main__": app = QApplication(sys.argv) tp = QThreadPool.globalInstance() tp.setMaxThreadCount(8) t = IndexThread("/tmp/mv/") t.start() sys.exit(app.exec_())
def stop_thread_func(): runnable = StopRunnable() QThreadPool.globalInstance().start(runnable)
def handleTargetIndexChanged(self): task = ProgressRunnable2() task.setRunMethod(self.__loadArchPossibilities) QThreadPool.globalInstance().start(task)
def stop_thread_func(self, ui): runnable = Ui_Form.StopRunnable(ui) QThreadPool.globalInstance().start(runnable)
try: result = "%3.3d\t%f" % (int(r['settings']['prate']),float(r['results']['timeToReachDest'])) except TypeError, e: result = 'PYTHON ERROR: %s | File: %s' % (e, outputPath) print result print r else: result = 'ERROR: No timeToReachDest (%s)' % outputPath self.startButton.setText('%d simulations left...' % simulationsLeft) self.log(result) # with open(self.resultFile, 'a') as summary: # summary.write('%s | %s\n' % (datetime.now(), result)) # summary.close() self.progressBar.setValue(self.simulationsDone) if self.simulationsDone==self.simulationsTotal: QThreadPool.globalInstance().waitForDone() del self.simulations[:] self.releaseUi() if self.actionWhenDone.currentIndex()==1: self.saveSettings() from time import sleep print 'shutdown in 20 seconds...' sleep(20) os.system('sudo halt') elif self.actionWhenDone.currentIndex()==2: self.startSimu() else: # calculate estimated time left # percentage_done = 1.0*self.simulationsDone/self.simulationsTotal # done_in = (datetime.now()-self.startTime).seconds # timeLeft = done_in*((1.0/percentage_done)-1.0)
def main(): # Use UTF-8 encoding for Qt from PySide.QtCore import QTextCodec #sys_codec = QTextCodec.codecForLocale() u8codec = QTextCodec.codecForName("UTF-8") QTextCodec.setCodecForCStrings(u8codec) QTextCodec.setCodecForTr(u8codec) import config from sakurakit import skdebug #skdebug.DEBUG = config.APP_DEBUG or '--debug' in sys.argv skdebug.DEBUG = '--debug' in sys.argv print "browser: debug = %s" % skdebug.DEBUG from sakurakit.skdebug import dprint, dwarn dprint("enter") if '--help' in sys.argv: print_help() dprint("leave: help") return dprint("python = %s" % sys.executable) #dprint("rootdir = %s" % rootdir) #dprint("mecabrc = %s" % mecabrc_path) from sakurakit import skos if skos.WIN: dprint("set app id") from sakurakit import skwin skwin.set_app_id("org.sakurakit.browser") import rc for it in ( rc.DIR_CACHE_DATA, rc.DIR_CACHE_HISTORY, rc.DIR_CACHE_NETMAN, rc.DIR_CACHE_WEBKIT, ): if not os.path.exists(it): try: os.makedirs(it) except OSError: dwarn("warning: failed to create directory: %s" % it) dprint("init opencc") from opencc import opencc opencc.setdicpaths(config.OPENCC_DICS) dprint("create app") import app a = app.Application(sys.argv) dprint("load translations") a.loadTranslations() # Take the ownership of sakurakit translation from sakurakit import sktr sktr.manager().setParent(a) dprint("load settings") import settings ss = settings.global_() ss.setParent(a) reader = settings.reader() #reader.setParent(a) # reader does NOT have a app parent dprint("update settings") ss_version = ss.version() if ss_version != config.VERSION_TIMESTAMP: dprint("app update detected, migrate settings") if ss_version: from sakurakit import skfileio if ss_version <= 1417339268: for it in ( #rc.DIR_CACHE_DATA, rc.DIR_CACHE_HISTORY, rc.DIR_CACHE_NETMAN, rc.DIR_CACHE_WEBKIT, ): if os.path.exists(it): skfileio.removetree(it) try: os.makedirs(it) except OSError: dwarn("warning: failed to create directory: %s" % it) if ss_version <= 1396371158: skfileio.removefile(rc.COOKIES_LOCATION) ss.setVersion(config.VERSION_TIMESTAMP) ss.sync() if reader.isCursorThemeEnabled(): dprint("load cursor theme") import curtheme curtheme.load() from sakurakit import skpaths skpaths.append_paths(( #reader.localeEmulatorLocation(), reader.jbeijingLocation(), reader.ezTransLocation(), reader.atlasLocation(), os.path.join(reader.lecLocation(), r"Nova\JaEn") if reader.lecLocation() else "", os.path.join(reader.dreyeLocation(), r"DreyeMT\SDK\bin") if reader.dreyeLocation() else "", )) path = reader.fastaitLocation() if path: path = os.path.join(path, "GTS") if os.path.exists(path): from sakurakit import skfileio dllpaths = skfileio.listdirs(path) if dllpaths: skpaths.append_paths(dllpaths) dprint("set max thread count") from PySide.QtCore import QThreadPool if QThreadPool.globalInstance().maxThreadCount() < config.QT_THREAD_COUNT: QThreadPool.globalInstance().setMaxThreadCount(config.QT_THREAD_COUNT) dprint("load web settings") import webrc webrc.update_web_settings() if reader.isMainlandChina(): dprint("set up proxy") from google import googletts googletts.setapi(config.PROXY_GOOGLE_TTS) import googleman googleman.setapi(config.PROXY_GOOGLE_TRANS) dprint("create main object") import main m = main.MainObject() m.run(a.arguments()) dprint("exec") sys.exit(a.exec_())
def main(): """ @return int """ import os, sys from PySide.QtCore import QTextCodec # Use UTF-8 encoding for Qt #sys_codec = QTextCodec.codecForLocale() u8codec = QTextCodec.codecForName("UTF-8") QTextCodec.setCodecForCStrings(u8codec) QTextCodec.setCodecForTr(u8codec) debug = '--debug' in sys.argv # bool print >> sys.stderr, "reader: debug = %s" % debug from sakurakit import skdebug #skdebug.DEBUG = config.APP_DEBUG or '--debug' in sys.argv skdebug.DEBUG = debug import config config.APP_DEBUG = debug from sakurakit.skdebug import dprint, dwarn dprint("enter") if '--help' in sys.argv: print_help() dprint("exit: help") #sys.exit(os.EX_USAGE) return 0 # Singleton # - Through mutex # See: http://code.activestate.com/recipes/474070-creating-a-single-instance-application/ # See: http://code.google.com/p/python-windows-tiler/source/browse/singleinstance.py # - Through file # See: http://stackoverflow.com/questions/380870/python-single-instance-of-program dprint("check single instance") from lockfile import lockfile app_mutex = lockfile.SingleProcessMutex() single_app = app_mutex.tryLock() if not single_app: dprint("multiple instances are running") dprint("python = %s" % sys.executable) #dprint("rootdir = %s" % rootdir) #dprint("mecabrc = %s" % mecabrc_path) from sakurakit import skos # Must be set before any GUI is showing up # http://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7 if skos.WIN: dprint("set app id") from sakurakit import skwin skwin.set_app_id("org.sakurakit.reader") # Detect user language import settings ss = settings.global_() uilang = ss.uiLanguage() if not uilang: uilang = guess_language() ss.setValue('Language', uilang) lang = ss.userLanguage() if not lang: lang = guess_language() ss.setValue('UserLanguage', lang) dprint("user language = %s" % lang) # Warm-up shiboken dlls #if os.name == 'nt': # dprint("load shiboken plugins") # import pytexscript # import pytexthook #Switch to OpenGL engine #from Qt5.QtWidgets import QApplication #QApplication.setGraphicsSystem("opengl") #dprint("elevate process priviledges") #from sakurakit import skos #if skos.WIN: # from sakurakit import skwin # skwin.enable_drop_event() dprint("init dic locations") from opencc import opencc opencc.setdicpaths(config.OPENCC_DICS) from hanviet import hanviet hanviet.setdicpaths(config.HANVIET_DICS) from hanjaconv import hanjaconv hanjaconv.setdicdir(config.HANJA_DIC_PATH) from pinyinconv import pinyinconv pinyinconv.setdicpath(config.PINYIN_DIC_PATH) dprint("create app") import app a = app.Application(sys.argv) #dprint("os default font:", a.font()) #a.setFont(config.FONT_DEFAULT) #dprint("current default font:", a.font()) # Fix the encoding issue for the current directory #from PySide.QtCore import QDir #QDir.setCurrent(a.applicationDirPath()) if not single_app: from rpcman import RpcClient dprint("send metacall") r = RpcClient() r.start() if r.waitForConnected(): r.activate() a.processEvents() else: dprint("warning: cannot connect to the server") dwarn("leave: multiple instance") #sys.exit(os.EX_UNAVAILABLE) return 0 # Must come after QApplication is created dprint("load fonts") from PySide.QtGui import QFontDatabase for path in config.FONT_LOCATIONS.itervalues(): if os.path.exists(path): for root, dirs, files in os.walk(path): FONT_EXTS = frozenset(('.otf', '.ttf', '.ttc')) for f in files: if os.path.splitext(f.lower())[1] in FONT_EXTS: p = os.path.join(root, f) index = QFontDatabase.addApplicationFont(p) if index >= 0: dprint( QFontDatabase.applicationFontFamilies(index)) else: dwarn("failed to load font %s" % f) ff = config.ui_font(ss.uiLanguage()) if ff: a.setFontFamily(ff) #ff = ss.applicationFontFamily() #if ff: # dprint("font family = %s" % ff) # a.setFontFamily(ff) #ss.applicationFontFamilyChanged.connect(a.setFontFamily) dprint("load translation") a.loadTranslations() dprint("autosync settings") ss.autoSync() # Load before qapplication is created opt_splash = '--nosplash' not in sys.argv if opt_splash: dprint("show splash") from splashscreen import StartupSplashScreen splash = StartupSplashScreen() splash.show() a.processEvents() # process event to make it show #dprint("cache fonts") #import fonts #fonts.test() # Take the ownership of sakurakit translation dprint("take the ownership of translations") from sakurakit import sktr sktr.manager().setParent(a) import mytr mytr.manager().setParent(a) mytr.my.setParent(a) # There should be at least one existing window (rootWindow), or sth is wrong #a.setQuitOnLastWindowClosed(False) #dprint("check unicode codec") #from sakurakit.skunicode import qunicode #ustr = qunicode("あのね", 'utf8') #assert ustr, "failed to load text code plugin from qt.conf" #dprint('init directories') #from PySide.QtCore import QDir import rc from sakurakit import skfileio dprint("remove broken caches") for it in rc.DIR_APP_TMP, : if os.path.exists(it): skfileio.removetree(it) map( skfileio.makedirs, ( rc.DIR_YAML_SUB, rc.DIR_XML_COMMENT, rc.DIR_XML_VOICE, rc.DIR_XML_REF, #rc.DIR_DICT_MECAB, # not used rc.DIR_CACHE_AVATAR, rc.DIR_CACHE_AWS, rc.DIR_CACHE_DATA, rc.DIR_CACHE_IMAGE, rc.DIR_CACHE_DMM, rc.DIR_CACHE_TOKUTEN, rc.DIR_CACHE_FREEM, rc.DIR_CACHE_STEAM, rc.DIR_CACHE_MELON, rc.DIR_CACHE_GETCHU, rc.DIR_CACHE_GYUTTO, rc.DIR_CACHE_DIGIKET, rc.DIR_CACHE_DLSITE, rc.DIR_CACHE_HOLYSEAL, rc.DIR_CACHE_SCAPE, rc.DIR_CACHE_TRAILERS, rc.DIR_CACHE_WEB, rc.DIR_CACHE_SYNC, rc.DIR_TMP_OCR, rc.DIR_TMP_TERM, # not needed, though rc.DIR_TMP_TTS, )) if skos.WIN: from sakurakit import skwin for it in rc.DIR_APP_LIBRARY, rc.DIR_APP_CACHE: if os.path.exists(it): skwin.set_file_readonly(it) dprint("load settings") ss.setParent(a) dprint("append library path") from sakurakit import skpaths skpaths.append_paths(( # TransCAT must be initialized BEFORE JBeijing, or the translation will fail ss.transcatLocation(), ss.jbeijingLocation(), ss.ezTransLocation(), ss.atlasLocation(), ss.zunkoLocation(), ss.localeEmulatorLocation(), ss.ntleasLocation(), os.path.join(ss.dreyeLocation(), r"DreyeMT\SDK\bin") if ss.dreyeLocation() else "", )) path = ss.lecLocation() if path: skpaths.append_paths(( os.path.join(path, r"Nova\JaEn"), os.path.join(path, r"PARS\EnRU"), )) path = ss.fastaitLocation() if path: path = os.path.join(path, 'GTS') if os.path.exists(path): dllpaths = skfileio.listdirs(path) if dllpaths: skpaths.append_paths(dllpaths) if sys.getrecursionlimit() < config.PY_RECURSION_LIMIT: dprint("increase recursion limit") sys.setrecursionlimit(config.PY_RECURSION_LIMIT) dprint("reduce socket timeout") import socket socket.setdefaulttimeout(config.PY_SOCKET_TIMEOUT) #import threading #if threading.stack_size() < config.PY_STACK_SIZE: # dprint("increase stack size") # threading.stack_size(config.PY_STACK_SIZE) # On unix: # stackoverflow.com/questions/5061582/setting-stacksize-in-a-python-script #import resource #resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1)) dprint("config python site-packages") # Disable requests SSL certificate warning # https://github.com/kennethreitz/requests/issues/2214 import requests requests.packages.urllib3.disable_warnings() # Disable HTTP request session # See: http://docs.python-requests.org/en/latest/user/advanced/#keep-alive # See: http://stackoverflow.com/questions/10115126/python-requests-close-http-connection #import requests #s = requests.session() #s.config['keep_alive'] = False import numpy numpy.seterr(all='ignore') # ignore overflow warning dprint("update settings") ss_version = ss.version() if ss_version != config.VERSION_TIMESTAMP: dprint("app update detected, migrate settings") if ss_version: migrate(ss_version) from sakurakit import skdatetime ss.setUpdateTime(skdatetime.current_unixtime()) ss.setVersion(config.VERSION_TIMESTAMP) ss.sync() if not ss.userName() or not ss.userId(): dprint("set user credential to guest") # Must be consistent with dataman.GUEST ss.setValue('UserId', 4) ss.setValue('UserName', 'guest') ss.setValue('UserPassword', 'guest') ss.setValue('UserGender', '') ss.setValue('UserAvatar', '') ss.setValue('UserColor', '') if ss.isCursorThemeEnabled(): dprint("load cursor theme") import curtheme curtheme.load() # Disable RBMT if CaboCha or UniDic is disabled #if ss.isTranslationSyntaxEnabled() and not ( # ss.isCaboChaEnabled() and ss.meCabDictionary() == 'unidic'): # ss.setTranslationSyntaxEnabled(False) #dprint("set max thread count") from PySide.QtCore import QThreadPool currentThreadCount = QThreadPool.globalInstance().maxThreadCount() if currentThreadCount < config.QT_THREAD_COUNT: dprint("increase thread pool capacity: %s -> %s" % (currentThreadCount, config.QT_THREAD_COUNT)) QThreadPool.globalInstance().setMaxThreadCount(config.QT_THREAD_COUNT) dprint("register qml plugins") import qmlplugin dprint("query system metrics") import sysinfo dprint("create main object") import main m = main.MainObject(a) m.init() if opt_splash: dprint("schedule to finish splash") splash.finishLater(1500) # hide after 1.5 seconds from functools import partial from sakurakit import skevents skevents.runlater(partial(m.run, a.arguments()), 50) #m.run(a.arguments()) #import netman #netman.manager().queryComments(gameId=183) #import hashutil #print hashutil.md5sum('/Users/jichi/tmp/t.cpp') dprint("exec") returnCode = a.exec_() # FIXME: Cannot normally exit # Shiboken 1.2 hang on exit! # All destructors are Invoked! dprint("unlock the mutex") app_mutex.unlock() import defs if returnCode == defs.EXIT_RESTART: skos.restart_my_process(['-B']) # -B: force disabling *.pyc and *.pyo else: #sys.exit(returnCode) #if skos.WIN: # prevent hanging on windows/mac skos.kill_my_process()
def handleObsNameEditingFinished(self): if self.__projectObsNameEdited: self.__projectObsNameEdited = False task = ProgressRunnable2() task.setRunMethod(self.__loadTargetPossibilities) QThreadPool.globalInstance().start(task)
def refresh(self): value = QThreadPool.globalInstance().activeThreadCount() if self.activeThreadCount != value: self.activeThreadCount = value self.q.threadCountChanged.emit(value)
def main(): # Use UTF-8 encoding for Qt from PySide.QtCore import QTextCodec #sys_codec = QTextCodec.codecForLocale() u8codec = QTextCodec.codecForName("UTF-8") QTextCodec.setCodecForCStrings(u8codec) QTextCodec.setCodecForTr(u8codec) import config from sakurakit import skdebug #skdebug.DEBUG = config.APP_DEBUG or '--debug' in sys.argv skdebug.DEBUG = '--debug' in sys.argv print "installer: debug = %s" % skdebug.DEBUG from sakurakit.skdebug import dprint, dwarn dprint("enter") if '--help' in sys.argv: print_help() dprint("leave: help") return # Singleton #dprint("check single instance") #from sakurakit import skipc #inst = skipc.SingleInstance() #single_app = inst.passed #if not single_app: # dprint("multiple instances are running") # sys.exit(-1) dprint("python = %s" % sys.executable) #dprint("rootdir = %s" % rootdir) #dprint("mecabrc = %s" % mecabrc_path) dprint("create app") import app a = app.Application(sys.argv) dprint("load translations") a.loadTranslations() # Take the ownership of sakurakit translation from sakurakit import sktr sktr.manager().setParent(a) dprint("load settings") import settings ss = settings.global_() ss.setParent(a) dprint("update settings") if ss.version() != config.VERSION_TIMESTAMP: dprint("app update detected, migrate settings") ss.setVersion(config.VERSION_TIMESTAMP) ss.sync() dprint("set max thread count") from PySide.QtCore import QThreadPool if QThreadPool.globalInstance().maxThreadCount() < config.QT_THREAD_COUNT: QThreadPool.globalInstance().setMaxThreadCount(config.QT_THREAD_COUNT) dprint("create main object") import main m = main.MainObject() m.run(a.arguments()) #import netman #netman.manager().queryComments(gameId=183) #import hashman #print hashman.md5sum('/Users/jichi/tmp/t.cpp') dprint("exec") sys.exit(a.exec_())
def start_thread_func(ui): runnable = StartRunnable(ui) QThreadPool.globalInstance().start(runnable)