Ejemplo n.º 1
0
    def OnInit(self):
        HOST, PORT = socket.gethostname(), 61955
        argvs = sys.argv

        instance_name = u"%s-%s" % (self.GetAppName(), wx.GetUserId())
        self.instance = wx.SingleInstanceChecker(instance_name)
        if self.instance.IsAnotherRunning():
            if len(argvs) >= 2:
                self.client(HOST, PORT, argvs)
            wx.Exit()
        else:
            server = self.start_server(HOST, PORT)

        # タスクトレイ
        self.tb_ico = wx.TaskBarIcon()
        self.tb_ico.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTbiLeftDClick)
        self.tb_ico.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.OnTbiRightUp)
        self.ico = wx.Icon("homu.ico", wx.BITMAP_TYPE_ICO)
        self.tb_ico.SetIcon(self.ico, u"homuhomu")

        # タスクトレイ用メニューの作成
        self.menu = wx.Menu()
        self.menu.Append(1, u"Exit(&X)")
        wx.EVT_MENU(self.menu, 1, self.OnClose)

        self.Frm = wx.Frame(None,
                            -1,
                            "homuLauncher",
                            size=(400, 60),
                            pos=(400, 400))
        self.TxtCtr = wx.TextCtrl(self.Frm, -1)
        self.Frm.Show()
        return 1
Ejemplo n.º 2
0
def start(apptype, exec_dir):
    appname = "freestream"
    single_instance_checker = wx.SingleInstanceChecker(appname + '-' + wx.GetUserId())
    if single_instance_checker.IsAnotherRunning():
        print >> sys.stderr, 'appwrapper: already running, exit'
        if get_default_api_version(apptype, exec_dir) < 2:
            send_startup_event()
        os._exit(0)
    globalConfig.set_value('apptype', apptype)
    globalConfig.set_mode('client_wx')
    wrapper = AppWrapper()
    try:
        bgapp = run_bgapp(wrapper, appname, VERSION)
    except Exception as e:
        print >> sys.stderr, 'Fatal error while starting:', str(e)
        print_exc()
        os._exit(0)

    wrapper.set_bgapp(bgapp)
    bgapp.debug_systray = bgapp.debug_level & 1024 != 0
    freestream.Player.systray.DEBUG = bgapp.debug_systray
    freestream.Player.systray.SHOW_DEBUG_LEVEL = bgapp.debug_systray
    freestream.Player.systray.DEBUG_PIECES = bgapp.debug_level & 128 != 0
    freestream.Player.systray.DEBUG_VIDEOSTATUS = bgapp.debug_level & 2048 != 0
    freestream.Player.systray.DEBUG_PROXY_BUF = bgapp.debug_level & 4096 != 0
    wrapper.MainLoop()
    if not ALLOW_MULTIPLE:
        del single_instance_checker
    stop_bgapp(bgapp)
Ejemplo n.º 3
0
    def init():
        """initialize the thread server

        Returns:
            [type] -- [description]
        """

        logging.debug(f'Initializing ipc')

        container = CallbackContainer()
        # print(f"Container: {container}")  # FIXME: delete this
        # print(f"Container: {type(container)}")  # FIXME: delete this
        # print(f"Container: {container.__doc__}")  # FIXME: delete this
        message = '\n'.join(sys.argv[1:])
        name = r'\\.\pipe\FeedNotifier_%s' % wx.GetUserId()

        # if client(name, message):
        #    print('ipc::init:win32 - Existen "message" y "name"')
        #    print('Salimos de ipc::init()::linux')
        #    return None, message
        # else:
        #    print('ipc::init:win32 - No existen "message" y "name"')
        #    print('Salimos de ipc::init()::linux')
        #    # jump to util.py
        #    util.start_thread(server, name, container)
        #
        #    return container, message

        logging.debug(f'Initialized ipc')
Ejemplo n.º 4
0
 def OnInit(self):
     '''
     Provides the additional initalisation needed for the application.
     '''
     self.SetupTanslation()
     self.checker = wx.SingleInstanceChecker(".Geocacher_" + wx.GetUserId())
     if self.checker.IsAnotherRunning():
         dlg = wx.MessageDialog(
             None,
             message=
             _("Geocacher is already running, please switch to that instance."
               ),
             caption=_("Geocacher Already Running"),
             style=wx.CANCEL | wx.ICON_HAND)
         dlg.ShowModal()
         return False
     else:
         from geocacher.widgets.mainWindow import MainWindow
         dirName = os.path.dirname(os.path.abspath(__file__))
         imageName = os.path.join(dirName, 'gfx', 'splash.png')
         image = wx.Image(imageName, wx.BITMAP_TYPE_PNG)
         bmp = image.ConvertToBitmap()
         wx.SplashScreen(bmp,
                         wx.SPLASH_CENTER_ON_SCREEN | wx.SPLASH_TIMEOUT,
                         5000, None, wx.ID_ANY)
         wx.Yield()
         frame = MainWindow(None, -1)
         self.SetTopWindow(frame)
         frame.Show(True)
         return True
Ejemplo n.º 5
0
    def lock_file(self):
        '''Handle the mc1.Lock object. Public objects:
        lock = mfc1.Lock
        lockstate = Status of the lock file.
                    '' = No status.
                    'written' = Lock file is written
                    'deleted' = Lock file is deleted
                    'exit' = Program exit

        '''
        userid = wx.GetUserId()
        wxpath = wx.StandardPaths.Get()
        userdir = wxpath.GetDocumentsDir()
        self.lock = Lock(path=userdir, userid=userid)
        self.lockstate = ''
        if self.lock.one_instance('mindfulclock1'):
            # One instance.
            self.lock.write_lock()
            self.lockstate = 'written'
        else:
            # More than one instance.
            if self.start_question():
                # Start the clock.
                self.lock.write_lock()
                self.lockstate = 'written'
            else:
                # Exit the program.
                self.lockstate = 'exit'
Ejemplo n.º 6
0
 def __init__(self, *args, **kwargs):
     super(SingleInstApp, self).__init__(*args, **kwargs)
     self.splash = None
     
     # Setup (note this will happen after subclass OnInit)
     instid = u"%s-%s" % (self.GetAppName(), wx.GetUserId())
     print "instid", instid
     self._checker = wx.SingleInstanceChecker(instid)
     if self.IsOnlyInstance():
         # First instance so start IPC server
         try:
             self._ipc = IpcServer(self, instid, 27115)
             self._ipc.start()
         except socket.error:
             pass
         
         # Open a window
         self.ShowSplash()
         #self.DoOpenNewWindow()
     else:
         # Another instance so just send a message to
         # the instance that is already running.
         cmd = u"OpenWindow.%s.%s" % (instid, GetArgFile())
         if not SendMessage(cmd, port=27115):
             print u"Failed to send message!"
Ejemplo n.º 7
0
    def SingleInstance(self):
        self.name = 'TimeSync-%s' % wx.GetUserId()
        self.instance = wx.SingleInstanceChecker(self.name)

        if self.instance.IsAnotherRunning():
            wx.MessageBox('TimeSync is already running!',
                          'TimeSync already running')
            return True
Ejemplo n.º 8
0
 def init():
     container = CallbackContainer()
     message = '\n'.join(sys.argv[1:])
     name = r'\\.\pipe\FeedNotifier_%s' % wx.GetUserId()
     if client(name, message):
         return None, message
     else:
         util.start_thread(server, name, container)
         return container, message
Ejemplo n.º 9
0
    def ensure_single_instance(self, name):
        """Check to see if this is the only instance."""

        self.name = "%s-%s" % (self.single_instance, wx.GetUserId())
        self.instance = wx.SingleInstanceChecker(self.name)
        if self.instance.IsAnotherRunning():
            # wx.MessageBox("Only one instance allowed!", "ERROR", wx.OK | wx.ICON_ERROR)
            return False
        return True
Ejemplo n.º 10
0
    def __init__(self, *args, **kargs):
        """Initialize that main app and its attributes
        @postcondition: application is created and ready to be run in mainloop

        """
        wx.App.__init__(self, *args, **kargs)
        events.AppEventHandlerMixin.__init__(self)

        self.SetAppName(ed_glob.PROG_NAME)

        # Attributes
        self.profile_updated = InitConfig()
        self._log = dev_tool.DEBUGP
        self._lock = False
        self._windows = dict()

        if ed_glob.SINGLE:
            # Setup the instance checker
            instance_name = u"%s-%s" % (self.GetAppName(), wx.GetUserId())
            self._instance = wx.SingleInstanceChecker(instance_name)
            if self._instance.IsAnotherRunning():
                try:
                    opts, args = getopt.getopt(sys.argv[1:], "dhv",
                                               ['debug', 'help', 'version'])
                except getopt.GetoptError, msg:
                    self._log("[app][err] %s" % str(msg))
                    args = list()

                if not len(args):
                    args.append(APP_CMD_OPEN_WINDOW)

                rval = ed_ipc.SendCommands(args,
                                           profiler.Profile_Get('SESSION_KEY'))
                # If sending the command failed then let the editor startup
                # a new instance
                if not rval:
                    self._isfirst = True
            else:
                self._log("[app][info] Starting Ipc server...")
                # Set the session key and save it to the users profile so
                # that other instances can access the server
                key = unicode(base64.b64encode(os.urandom(8), 'zZ'))
                key = wx.GetUserName() + key
                profiler.Profile_Set('SESSION_KEY', key)
                profiler.Profile_Set('ISBINARY', hasattr(sys, 'frozen'))
                path = profiler.Profile_Get('MYPROFILE')
                profiler.Profile().Write(path)
                try:
                    self._server = ed_ipc.EdIpcServer(
                        self, profiler.Profile_Get('SESSION_KEY'))
                    self._server.start()
                except Exception, msg:
                    self._log("[app][err] Failed to start ipc server")
                    self._log("[app][err] %s" % str(msg))
                    self._server = None
                self._isfirst = True
Ejemplo n.º 11
0
    def __init__(self, basename):
        super(SingleInstanceChecker, self).__init__()

        self._logger = logging.getLogger(self.__class__.__name__)

        if sys.platform != 'linux2':
            self._wx_instance_name = "tribler-" + wx.GetUserId()
            self._wx_checker = wx.SingleInstanceChecker(self._wx_instance_name)

        self._basename = basename
Ejemplo n.º 12
0
    def ensure_single_instance(self, single_instance):
        """Check to see if this is the only instance."""

        if single_instance is not None and isinstance(single_instance, str):
            self.name = "%s-%s" % (self.single_instance, wx.GetUserId())
            self.instance = wx.SingleInstanceChecker(self.name)
            if self.instance.IsAnotherRunning():
                self.instance_okay = False

        return self.instance_okay
Ejemplo n.º 13
0
    def MainLoop(self):
        single_instance_name = 'fr0st-%s' % wx.GetUserId()
        single_instance = wx.SingleInstanceChecker(single_instance_name)

        if single_instance.IsAnotherRunning():
            ErrorMessage(None, "Another instance of fr0st is already running. "
                         "Multiple instances are not supported.")
            return

        self.MainWindow = MainWindow(None, wx.ID_ANY)
        wx.App.MainLoop(self)
Ejemplo n.º 14
0
    def OnInit(self):
        self.name = "TydApp-%s" % wx.GetUserId()
        self.instance = wx.SingleInstanceChecker(self.name)
        if self.instance.IsAnotherRunning():
            wx.MessageBox(u'已经运行一个程序啦', u'出错提示')
            return False

        frame = TydMainFrame(None, -1, u'统一桌面')
        frame.Show(True)
        frame.Centre()
        return True
Ejemplo n.º 15
0
    def OnInit(self, *args, **kwargs):
        self.name = "TrayIcon-{}".format(wx.GetUserId())
        self.instance = wx.SingleInstanceChecker(self.name)

        if self.instance.IsAnotherRunning():
            wx.MessageBox('Another instance is running', 'ERROR')
            return False

        TaskBarIcon()

        return super(App, self).OnInit(*args, **kwargs)
Ejemplo n.º 16
0
    def OnInit(self):
        #         self.locale = wx.Locale(locale)
        #         print("LOCALE_DECIMAL_POINT", self.locale.GetInfo(wx.LOCALE_DECIMAL_POINT, wx.LOCALE_CAT_NUMBER))
        self.locale = wx.Locale(
            wx.LANGUAGE_ENGLISH)  # !!! obligé pour certains PC ???
        #         print("LOCALE_DECIMAL_POINT", self.locale.GetInfo(wx.LOCALE_DECIMAL_POINT, wx.LOCALE_CAT_NUMBER))
        #         self.locale = wx.Locale(wx.LANGUAGE_FRENCH) # Sans ça, il y a des erreurs sur certains PC ...
        #         print("LOCALE_DECIMAL_POINT", self.locale.GetInfo(wx.LOCALE_DECIMAL_POINT, wx.LOCALE_CAT_NUMBER))

        # Problème avec les PNG ??? Suppression des warning
        #  --> bug dans la version wx4 : les warnings plantent : il faut changer self.locale
        # https://github.com/wxWidgets/Phoenix/issues/769
        wx.Log.SetLogLevel(
            0
        )  # ?? Pour éviter le plantage de wxpython 3.0 avec Win XP pro ???

        self.name = "pySéquence-%s" % wx.GetUserId()
        self.instance = wx.SingleInstanceChecker(self.name)

        if self.instance.IsAnotherRunning():
            # Another instance so just send a message to
            # the instance that is already running.
            _, fichier = GetArgs()
            #             wx.MessageBox(fichier, "Fichier")
            if os.path.isfile(fichier):
                cmd = "OpenWindow.%s.%s" % (self.name, fichier)
                #                 wx.MessageBox(cmd, "Message")
                if not SendMessage(cmd, port=self.PORT):
                    print("Failed to send message!")
#                     wx.MessageBox(fichier, "Failed to send message!")
            else:
                wx.MessageBox("pySéquence semble être déjà lancé !",
                              "pySéquence")

            return False

        else:
            # First instance so start IPC server
            try:
                self._ipc = IpcServer(self, self.name, self.PORT)
                self._ipc.start()
            except socket.error:
                print("Erreur création serveur")
            except:
                pass

            self.splash = MySplashScreen(self)
            self.splash.Show()

            AddRTCHandlers()

            #            frame = SingleAppFrame(None, "SingleApp")
            #            frame.Show()
            return True
Ejemplo n.º 17
0
Archivo: dtk.py Proyecto: mitxi21/dtk
 def OnInit(self):
     """
     wx.App init function that returns False if the app is already running.
     """
     self.name = "SingleApp-%s".format(wx.GetUserId())
     self.instance = wx.SingleInstanceChecker(self.name)
     if self.instance.IsAnotherRunning():
         wx.MessageBox("An instance of the application is already running",
                       "Error", wx.OK | wx.ICON_WARNING)
         return False
     return True
Ejemplo n.º 18
0
    def OnInit(self):
        """Initialize the Editor
        @note: this gets called before __init__
        @postcondition: custom artprovider and plugins are loaded

        """
        self.SetAppName(ed_glob.PROG_NAME)

        self._log = dev_tool.DEBUGP
        self._log("[app][info] Editra is Initializing")

        self._isfirst = False  # Is the first instance
        self._instance = None

        if ed_glob.SINGLE:
            # Setup the instance checker
            instance_name = u"%s-%s" % (self.GetAppName(), wx.GetUserId())
            self._instance = wx.SingleInstanceChecker(instance_name)
            if self._instance.IsAnotherRunning():
                try:
                    opts, args = getopt.getopt(sys.argv[1:], "dhv",
                                               ['debug', 'help', 'version'])
                except getopt.GetoptError, msg:
                    self._log("[app][err] %s" % str(msg))
                    args = list()

                if not len(args):
                    args.append(APP_CMD_OPEN_WINDOW)

                rval = ed_ipc.SendCommands(args,
                                           profiler.Profile_Get('SESSION_KEY'))
                # If sending the command failed then let the editor startup
                # a new instance
                if not rval:
                    self._isfirst = True
            else:
                self._log("[app][info] Starting Ipc server...")
                # Set the session key and save it to the users profile so
                # that other instances can access the server
                key = unicode(base64.b64encode(os.urandom(8), 'zZ'))
                key = wx.GetUserName() + key
                profiler.Profile_Set('SESSION_KEY', key)
                profiler.Profile_Set('ISBINARY', hasattr(sys, 'frozen'))
                path = profiler.Profile_Get('MYPROFILE')
                profiler.Profile().Write(path)
                try:
                    self._server = ed_ipc.EdIpcServer(
                        self, profiler.Profile_Get('SESSION_KEY'))
                    self._server.start()
                except Exception, msg:
                    self._log("[app][err] Failed to start ipc server")
                    self._log("[app][err] %s" % str(msg))
                    self._server = None
                self._isfirst = True
Ejemplo n.º 19
0
        def OnInit(self):
            self.name = "SingleApp-%s" % wx.GetUserId()
            self.instance = wx.SingleInstanceChecker(self.name)

            if self.instance.IsAnotherRunning():
                wx.MessageBox("已经有一个潮生活发票助手程序在运行了!", "Do not Panic")
                return False
            else:
                the_frame = ChaoShengHuo(None, -1)
                the_frame.Show(True)
                return True
Ejemplo n.º 20
0
 def OnInit(self):
     ##获取实例名称
     self.name = "%s-%s" % (self.GetAppName(), wx.GetUserId())
     ##要检测的实例
     self.instance = wx.SingleInstanceChecker(self.name)
     ##查看实例是否已经运行,如果已经运行则初始化失败退出
     if self.instance.IsAnotherRunning():
         wx.MessageBox(u"Web Publisher,已经在运行了!", u"提示")
         return False
     MySplash = MySplashScreen()
     MySplash.Show()
     return True
Ejemplo n.º 21
0
    def __init__(self, unique=True):
        userid = wx.GetUserId()

        self.pidfile = my_env.tempfilepath("pid_%s" % userid)
        self.commfilepath = my_env.tempfilepath("comm_%s" % userid)
        self.update_interval = 1  # Timeout for commfile check

        if unique:
            # Reading pid file and check if running
            self._alone = not my_env.get_running_pidfile(self.pidfile)
            if self._alone:
                self._write_pid()
Ejemplo n.º 22
0
 def test_utilsSomeOtherStuff(self):
     wx.GetBatteryState()
     wx.GetPowerType()
     wx.GetKeyState(wx.WXK_F1)
     wx.GetMousePosition()
     wx.GetMouseState()
     wx.EnableTopLevelWindows(True)
     wx.FindWindowAtPoint((1, 1))
     wx.NewId()
     wx.RegisterId(12345)
     wx.GetUserName()
     wx.GetUserId()
     wx.GetOsDescription()
Ejemplo n.º 23
0
 def OnInit(self):
     ##获取实例名称
     self.name = "%s-%s" % (self.GetAppName(), wx.GetUserId())
     ##要检测的实例
     self.instance = wx.SingleInstanceChecker(self.name)
     ##查看实例是否已经运行,如果已经运行则初始化失败退出
     if self.instance.IsAnotherRunning():
         wx.MessageBox(u"PMManager 进程监控管理器,已经在运行了!", u"提示")
         return False
     ##检测有没有数据文件,如果没有创建一个空白数据文件
     CheckDataFileExists(gen._filedata)
     MySplash = MySplashScreen()
     MySplash.Show()
     return True
Ejemplo n.º 24
0
def run_bgapp(appname, params=None):
    if params is None:
        params = [""]

    if len(sys.argv) > 1:
        params = sys.argv[1:]

    # Create single instance semaphore
    # Arno: On Linux and wxPython-2.8.1.1 the SingleInstanceChecker appears
    # to mess up stderr, i.e., I get IOErrors when writing to it via print_exc()
    #
    if sys.platform != 'linux2':
        single_instance_checker = wx.SingleInstanceChecker(appname + "-" +
                                                           wx.GetUserId())
    else:
        single_instance_checker = LinuxSingleInstanceChecker(appname)

    #print "[StartUpDebug]---------------- 1", time()-start_time
    if not ALLOW_MULTIPLE and single_instance_checker.IsAnotherRunning():
        if params[0] != "":
            torrentfilename = params[0]
            i2ic = Instance2InstanceClient(I2I_LISTENPORT, 'START',
                                           torrentfilename)
            time.sleep(1)
            return

    arg0 = sys.argv[0].lower()
    if arg0.endswith('.exe'):
        installdir = os.path.abspath(os.path.dirname(sys.argv[0]))
    else:
        installdir = os.getcwd()

    # Launch first single instance
    app = BackgroundApp(0, appname, params, single_instance_checker,
                        installdir, I2I_LISTENPORT, BG_LISTENPORT)

    status = Status.get_status_holder("LivingLab")
    s = app.s  #Session.get_instance()
    id = encodestring(s.get_permid()).replace("\n", "")
    reporter = LivingLabReporter.LivingLabPeriodicReporter(
        "Living lab CS reporter", 300, id)  # Report every 5 minutes
    status.add_reporter(reporter)

    app.MainLoop()

    print >> sys.stderr, "Sleeping seconds to let other threads finish"
    time.sleep(2)

    if not ALLOW_MULTIPLE:
        del single_instance_checker
Ejemplo n.º 25
0
    def OnInit(self):
        #wx.App.__init__(self)

        self.SetAppName("Write++")
        self.checker = wx.SingleInstanceChecker(
            "write++-%s" % wx.GetUserId(),
            wx.StandardPaths.Get().GetTempDir())
        self.server = None
        if "--multiple" not in options:
            if not self.checker.IsAnotherRunning():
                self.server = ipc.IPCServer(self)
                if not self.server.socket:
                    self.server = None
            elif ipc.transmit(sys.argv[1:]):
                sys.exit(0)

        if not hasattr(sys, "frozen"):
            self.cwd = os.path.dirname(__file__)
        else:
            self.cwd = os.path.dirname(sys.argv[0])
        if "--datadir" in options:
            self.userdatadir = options["--datadir"]
            if not os.path.isabs(self.userdatadir):
                self.userdatadir = os.path.join(self.cwd, self.userdatadir)
        elif os.path.isfile(os.path.join(self.cwd, "portable.ini")):
            self.userdatadir = self.cwd
        else:
            self.userdatadir = wx.StandardPaths.Get().GetUserDataDir()
        if not os.path.isdir(self.userdatadir):
            os.makedirs(self.userdatadir)

        self.config = FileConfig(self)
        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH_US)
        localedir = os.path.join(self.cwd, "locale")
        self.locale.AddCatalogLookupPathPrefix(localedir)
        language = self.locale.GetCanonicalName()
        if os.path.isfile(
                os.path.join(localedir, language, "LC_MESSAGES",
                             "write++.mo")):
            self.locale.AddCatalog(language)
        self.settings = self.config.Load()
        self.version = _version

        self.helper = helper.HelpSystem(self)
        self.plugins = plugins.PluginManager(self)
        self.printer = printing.Printer(self)

        return True
Ejemplo n.º 26
0
 def __init__(self, *args, **kwargs):
     super(SingleInstApp, self).__init__(*args, **kwargs)
     # Setup (note this will happen after subclass OnInit)
     instid = "%s-%s" % (self.GetAppName(), wx.GetUserId())
     self._checker = wx.SingleInstanceChecker(instid)
     if self.IsOnlyInstance():
         # First instance so start IPC server
         self._ipc = IpcServer(self, instid, 27115)
         self._ipc.start()
         # Open a window
         self.DoOpenNewWindow()
     else:
         # Another instance so just send a message to
         # the instance that is already running.
         cmd = "OpenWindow.%s" % instid
         if not SendMessage(cmd, port=27115):
             print "Failed to send message!"
Ejemplo n.º 27
0
    def OnInit(self):

        # Make sure only one instance is running
        self.name = "SingleApp-%s" % wx.GetUserId()
        self.instance = wx.SingleInstanceChecker(self.name)
        if self.instance.IsAnotherRunning():
            wx.MessageBox("Another instance of Gimel Studio is running.",
                          "ERROR")
            return False

        # Splash screen
        #splash = StartupSplashScreen()
        #splash.CenterOnScreen(wx.BOTH)
        frame = ApplicationFrame()
        frame.Show()

        return True
Ejemplo n.º 28
0
    def __init__(self, appname, *args, **kws):
        appname = '%s-%s' % (appname, wx.GetUserId())
        mgr = InstanceChecker(appname, 'localhost',
                              InstanceChecker.default_port)
        self.instance_checker = mgr

        try:
            should_quit = self._check_and_raise_other()
            if should_quit:
                log('instance already running. quitting!')
                self._do_quit()
        except Exception:
            print_exc()

        # wx.App's __init__ calls OnInit, which may spawn frames, so
        # we do this last
        wx.App.__init__(self, *args, **kws)
Ejemplo n.º 29
0
    def run(self):

        # instance_name = None

        while True:

            app = wx.App(False)

            instance_name = "%s-%s" % (app.GetAppName(), wx.GetUserId())
            instance_checker = wx.SingleInstanceChecker(
                instance_name, self.working_path)
            if instance_checker.IsAnotherRunning():
                dlg = wx.MessageDialog(
                    None, u"SwitchHosts! 已经在运行了或上次没有正常退出,要重新打开吗?",
                    u"SwitchHosts!", wx.YES_NO | wx.ICON_QUESTION)
                ret_code = dlg.ShowModal()
                if ret_code != wx.ID_YES:
                    dlg.Destroy()
                    return

                dlg.Destroy()

            frame = MainFrame(
                mainjob=self,
                instance_name=instance_name,
                size=(640, 480),
                version=self.VERSION,
                working_path=self.working_path,
                taskbar_icon=self.taskbar_icon,
            )
            self.restart = False
            self.taskbar_icon = None

            self.app = app
            self.frame = frame
            self.bindEvents()

            frame.Centre()
            frame.Show()
            app.MainLoop()
            app.Destroy()

            time.sleep(0.1)
            if not self.restart:
                break
Ejemplo n.º 30
0
def run_bgapp(appname, params=None):
    if params is None:
        params = [""]

    if len(sys.argv) > 1:
        params = sys.argv[1:]

    # Create single instance semaphore
    # Arno: On Linux and wxPython-2.8.1.1 the SingleInstanceChecker appears
    # to mess up stderr, i.e., I get IOErrors when writing to it via print_exc()
    #
    if sys.platform != 'linux2':
        single_instance_checker = wx.SingleInstanceChecker(appname + "-" +
                                                           wx.GetUserId())
    else:
        single_instance_checker = LinuxSingleInstanceChecker(appname)

    #print "[StartUpDebug]---------------- 1", time()-start_time
    if not ALLOW_MULTIPLE and single_instance_checker.IsAnotherRunning():
        if params[0] != "":
            torrentfilename = params[0]
            i2ic = Instance2InstanceClient(I2I_LISTENPORT, 'START',
                                           torrentfilename)
            time.sleep(1)
            return

    arg0 = sys.argv[0].lower()
    if arg0.endswith('.exe'):
        installdir = os.path.abspath(os.path.dirname(sys.argv[0]))
    else:
        installdir = os.getcwd()

    # Launch first single instance
    app = BackgroundApp(0, appname, params, single_instance_checker,
                        installdir, I2I_LISTENPORT, BG_LISTENPORT)
    app.MainLoop()

    print >> sys.stderr, "Sleeping seconds to let other threads finish"
    time.sleep(2)

    if not ALLOW_MULTIPLE:
        del single_instance_checker

    # Ultimate catchall for hanging popen2's and what not
    os._exit(0)