Exemplo n.º 1
0
def run(GUIConfigFile=None):
    defaultHwrServer = 'localhost:hwr'
    userHomeDir = os.path.expanduser(
        "~")  #path to user's home dir. (works on Win2K, XP, Unix, Mac...)

    parser = OptionParser(usage='usage: %prog <GUI definition file> [options]')
    parser.add_option('',
                      '--logFile',
                      action='store',
                      type='string',
                      help='Log file',
                      dest='logFile',
                      metavar='FILE',
                      default='')
    parser.add_option('',
                      '--logLevel',
                      action='store',
                      type='string',
                      help='Log level',
                      dest='logLevel',
                      default='INFO')
    parser.add_option(
        '',
        '--bricksDirs',
        action='store',
        type='string',
        help=
        'Additional directories for bricks search path (you can also use the CUSTOM_BRICKS_PATH environment variable)',
        dest='bricksDirs',
        metavar='dir1' + os.path.pathsep + 'dir2...dirN',
        default='')
    parser.add_option(
        '',
        '--hardwareRepository',
        action='store',
        type='string',
        help=
        'Hardware Repository Server host:port (default to %s) (you can also use HARDWARE_REPOSITORY_SERVER the environment variable)'
        % defaultHwrServer,
        metavar='HOST:PORT',
        dest='hardwareRepositoryServer',
        default='')
    parser.add_option(
        '',
        '--hardwareObjectsDirs',
        action='store',
        type='string',
        help=
        'Additional directories for Hardware Objects search path (you can also use the CUSTOM_HARDWARE_OBJECTS_PATH environment variable)',
        dest='hardwareObjectsDirs',
        metavar='dir1' + os.path.pathsep + 'dir2...dirN',
        default='')
    parser.add_option('-d',
                      '',
                      action='store_true',
                      dest="designMode",
                      default=False,
                      help="start GUI in Design mode")
    parser.add_option('-m',
                      '',
                      action='store_true',
                      dest="showMaximized",
                      default=False,
                      help="maximize main window")
    parser.add_option('',
                      '--no-border',
                      action='store_true',
                      dest='noBorder',
                      default=False,
                      help="does not show borders on main window")
    parser.add_option(
        '-w',
        '--web-server-port',
        action='store',
        type="int",
        dest='webServerPort',
        default=0,
        help="port number for the remote interpreter web application server")
    #parser.add_option('', '--widgetcount', action='store_true', dest='widgetCount', default=False, help="prints debug message at the end about number of widgets left undestroyed")

    (opts, args) = parser.parse_args()

    if len(args) >= 1:
        if len(args) == 1:
            GUIConfigFile = os.path.abspath(args[0])
        else:
            parser.error('Too many arguments.')
            sys.exit(1)

    if opts.webServerPort:
        interpreter = terminal_server.InteractiveInterpreter()
        terminal_server.set_interpreter(interpreter)
        gevent.spawn(terminal_server.serve_forever, opts.webServerPort)

    #
    # get config from arguments
    #
    logFile = opts.logFile
    hoDirs = opts.hardwareObjectsDirs.split(os.path.pathsep)
    bricksDirs = opts.bricksDirs.split(os.path.pathsep)

    if opts.hardwareRepositoryServer:
        hwrServer = opts.hardwareRepositoryServer
    else:
        #
        # try to set Hardware Repository server from environment
        #
        try:
            hwrServer = os.environ['HARDWARE_REPOSITORY_SERVER']
        except KeyError:
            hwrServer = defaultHwrServer

    #
    # add bricks directories and hardware objects directories from environment
    #
    try:
        bricksDirs += os.environ['CUSTOM_BRICKS_PATH'].split(os.path.pathsep)
    except KeyError:
        pass

    try:
        hoDirs += os.environ['CUSTOM_HARDWARE_OBJECTS_PATH'].split(
            os.path.pathsep)
    except KeyError:
        pass

    bricksDirs = [_f for _f in bricksDirs if _f]
    hoDirs = [_f for _f in hoDirs if _f]

    app = QApplication([])
    lockfile = None

    if not opts.designMode and GUIConfigFile:
        lock_filename = os.path.join(
            tempfile.gettempdir(),
            '.%s.lock' % os.path.basename(GUIConfigFile or "unnamed"))
        try:
            lockfile = open(lock_filename, "w")
        except:
            logging.getLogger().exception(
                "Cannot create lock file (%s), exiting" % lock_filename)

            sys.exit(1)
        else:
            os.chmod(lock_filename, 0o666)
            try:
                fcntl.lockf(lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except:
                logging.getLogger().exception(
                    "Cannot acquire lock (%s), exiting (hint: maybe the same application is already running ?)"
                    % lock_filename)

                sys.exit(1)

    #
    # configure modules
    #
    HardwareRepository.setHardwareRepositoryServer(hwrServer)
    HardwareRepository.addHardwareObjectsDirs(hoDirs)
    BlissFramework.addCustomBricksDirs(bricksDirs)

    #
    # set log name and log file
    #
    if GUIConfigFile:
        BlissFramework.setLoggingName(os.path.basename(GUIConfigFile))

    log_lockfile = None
    if len(logFile) > 0:
        log_lock_filename = os.path.join(
            tempfile.gettempdir(), '.%s.lock' % os.path.basename(logFile))

        log_ok = True
        try:
            log_lockfile = open(log_lock_filename, "w")
        except:
            log_ok = False
        else:
            try:
                os.chmod(log_lock_filename, 0o666)
            except:
                pass
            try:
                fcntl.lockf(log_lockfile.fileno(),
                            fcntl.LOCK_EX | fcntl.LOCK_NB)
            except:
                log_ok = False
                try:
                    log_lockfile.close()
                except:
                    pass

        if not log_ok:
            i = 1
            logfile_details = os.path.splitext(logFile)
            logFile = ""
            while i < 10:
                logFile2 = "%s.%d%s" % (logfile_details[0], i,
                                        logfile_details[1])
                log_lock_filename2 = os.path.join(
                    tempfile.gettempdir(),
                    '.%s.lock' % os.path.basename(logFile2))
                try:
                    log_lockfile = open(log_lock_filename2, "w")
                except:
                    pass
                else:
                    try:
                        os.chmod(log_lock_filename2, 0o666)
                    except:
                        pass
                    try:
                        fcntl.lockf(log_lockfile.fileno(),
                                    fcntl.LOCK_EX | fcntl.LOCK_NB)
                    except:
                        pass
                    else:
                        log_ok = True
                if log_ok:
                    logFile = logFile2
                    break
                i += 1

        if len(logFile) > 0:
            BlissFramework.setLogFile(logFile)

    #
    # log startup details
    #
    logLevel = getattr(logging, opts.logLevel)
    logging.getLogger().setLevel(logLevel)
    logInfo = 'GUI started (%s)' % (GUIConfigFile or "unnamed")
    logInfo += ', HWRSERVER=%s' % hwrServer
    if len(hoDirs) > 0:
        logInfo += ', HODIRS=%s' % os.path.pathsep.join(hoDirs)
    if len(bricksDirs) > 0:
        logInfo += ', BRICKSDIRS=%s' % os.path.pathsep.join(bricksDirs)
    logging.getLogger().info(logInfo)

    QApplication.setDesktopSettingsAware(False)  #use default settings
    QObject.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))

    supervisor = GUISupervisor.GUISupervisor(designMode=opts.designMode,
                                             showMaximized=opts.showMaximized,
                                             noBorder=opts.noBorder)

    #BlissFramework.setDebugMode(True)
    #
    # post event for GUI creation
    #
    app.postEvent(supervisor,
                  QCustomEvent(GUISupervisor.LOAD_GUI_EVENT, GUIConfigFile))

    #
    # redirect errors to logger
    #
    ErrorHandler.enableStdErrRedirection()

    timer = QTimer()
    timer.connect(timer, SIGNAL("timeout()"), do_gevent)
    timer.start(0)

    app.exec_loop()
    """
    def process_qt_events():
      while True:
        time.sleep(0.01)
        while app.hasPendingEvents():
          app.processEvents() 
          time.sleep(0.01)
          if not app.mainWidget() or not app.mainWidget().isVisible():
            return
    qt_events = gevent.spawn(process_qt_events) 
    qt_events.join()   
    """

    supervisor.finalize()

    if lockfile is not None:
        filename = lockfile.name
        try:
            lockfile.close()
            os.unlink(filename)
        except:
            logging.getLogger().error("Problem removing the lock file")

    if log_lockfile is not None:
        filename = log_lockfile.name
        try:
            log_lockfile.close()
            os.unlink(filename)
        except:
            logging.getLogger().exception("Problem removing the log lock file")
Exemplo n.º 2
0
def run(GUIConfigFile = None):    
    """
    Descript. : 
    """

    defaultHwrServer = 'localhost:hwr'
    userHomeDir = os.path.expanduser("~") #path to user's home dir. (works on Win2K, XP, Unix, Mac...) 

    parser = OptionParser(usage = 'usage: %prog <GUI definition file> [options]')
    parser.add_option('', '--logFile', action = 'store', type = 'string', 
                      help = 'Log file', dest = 'logFile', metavar = 'FILE', default = '')
    parser.add_option('', '--logLevel', action = 'store', type = 'string', 
                      help = 'Log level', dest = 'logLevel', default = 'INFO')
    parser.add_option('', '--bricksDirs', action = 'store', type = 'string', 
                      help = 'Additional directories for bricks search path (you can also use the CUSTOM_BRICKS_PATH environment variable)', 
                      dest = 'bricksDirs', metavar = 'dir1'+os.path.pathsep+'dir2...dirN', default = '')
    parser.add_option('', '--hardwareRepository', action = 'store', type = 'string', 
                      help = 'Hardware Repository Server host:port (default to %s) (you can also use HARDWARE_REPOSITORY_SERVER the environment variable)' % defaultHwrServer, 
                      metavar = 'HOST:PORT', dest = 'hardwareRepositoryServer', default = '')                   
    parser.add_option('', '--hardwareObjectsDirs', action = 'store', type = 'string', 
                      help = 'Additional directories for Hardware Objects search path (you can also use the CUSTOM_HARDWARE_OBJECTS_PATH environment variable)', 
                      dest = 'hardwareObjectsDirs', metavar = 'dir1' + os.path.pathsep + 'dir2...dirN', 
                      default = '')
    parser.add_option('-d', '', action='store_true', dest="designMode", 
                      default=False, help="start GUI in Design mode")
    parser.add_option('-m', '', action='store_true', dest="showMaximized", 
                      default=False, help="maximize main window")	
    parser.add_option('', '--no-border', action='store_true', dest='noBorder', 
                      default=False, help="does not show borders on main window")
    #parser.add_option('-s', '--syle', action='store', type="string", dest='style', default=0, help="GUI style")
    parser.add_option('-w', '--web-server-port', action='store', type="int", 
                      dest='webServerPort', default=0, help="port number for the remote interpreter web application server")
    #parser.add_option('', '--widgetcount', action='store_true', dest='widgetCount', default=False, help="prints debug message at the end about number of widgets left undestroyed")

    (opts, args) = parser.parse_args()
    
    if len(args) >= 1:
        if len(args) == 1:
            GUIConfigFile = os.path.abspath(args[0])
        else:
            parser.error('Too many arguments.')
            sys.exit(1)

    """if opts.webServerPort:
        interpreter = terminal_server.InteractiveInterpreter()
        terminal_server.set_interpreter(interpreter) 
        gevent.spawn(terminal_server.serve_forever, opts.webServerPort)"""

    #
    # get config from arguments
    #
    logFile = opts.logFile        
    hoDirs = opts.hardwareObjectsDirs.split(os.path.pathsep)
    bricksDirs = opts.bricksDirs.split(os.path.pathsep)

    if opts.hardwareRepositoryServer:
      hwrServer = opts.hardwareRepositoryServer
    else:
      #
      # try to set Hardware Repository server from environment
      #
      try:
          hwrServer = os.environ['HARDWARE_REPOSITORY_SERVER']
      except KeyError:
          hwrServer = defaultHwrServer

    #
    # add bricks directories and hardware objects directories from environment
    #
    try:
        bricksDirs += os.environ['CUSTOM_BRICKS_PATH'].split(os.path.pathsep)
    except KeyError:
        pass
    
    try:
        hoDirs += os.environ['CUSTOM_HARDWARE_OBJECTS_PATH'].split(os.path.pathsep)
    except KeyError:
        pass

    bricksDirs = filter(None, bricksDirs)
    hoDirs = filter(None, hoDirs)
    
    app = QtGui.QApplication([])
    lockfile = None

    if not opts.designMode and GUIConfigFile: 
      lock_filename=os.path.join(tempfile.gettempdir(), '.%s.lock' % os.path.basename(GUIConfigFile or "unnamed"))
      try:
          lockfile = open(lock_filename, "w")
      except:
          logging.getLogger().exception("Cannot create lock file (%s), exiting" % lock_filename)

          sys.exit(1)
      else:
          os.chmod(lock_filename,0666)
          try:
             fcntl.lockf(lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
          except:
             logging.getLogger().exception("Cannot acquire lock (%s), exiting (hint: maybe the same application is already running ?)" % lock_filename)
           
             sys.exit(1)
    
    #
    # configure modules
    #
    HardwareRepository.setHardwareRepositoryServer(hwrServer)
    HardwareRepository.addHardwareObjectsDirs(hoDirs)
    BlissFramework.addCustomBricksDirs(bricksDirs)
    
    #
    # set log name and log file
    #
    if GUIConfigFile:
        BlissFramework.setLoggingName(os.path.basename(GUIConfigFile))

    log_lockfile = None
    if len(logFile) > 0:
      log_lock_filename=os.path.join(tempfile.gettempdir(), '.%s.lock' % os.path.basename(logFile))

      log_ok=True
      try:
          log_lockfile = open(log_lock_filename, "w")
      except:
          log_ok=False
      else:
          try:
            os.chmod(log_lock_filename,0666)
          except:
            pass
          try:
             fcntl.lockf(log_lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
          except:
             log_ok=False
             try:
               log_lockfile.close()
             except:
               pass

      if not log_ok:
        i=1
        logfile_details=os.path.splitext(logFile)
        logFile=""
        while i<10:
          logFile2="%s.%d%s" % (logfile_details[0],i,logfile_details[1])
          log_lock_filename2=os.path.join(tempfile.gettempdir(), '.%s.lock' % os.path.basename(logFile2))
          try:
            log_lockfile = open(log_lock_filename2, "w")
          except:
            pass
          else:
            try:
              os.chmod(log_lock_filename2,0666)
            except:
              pass
            try:
               fcntl.lockf(log_lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except:
               pass
            else:
              log_ok=True
          if log_ok:
            logFile=logFile2
            break
          i+=1

      if len(logFile) > 0:
        BlissFramework.setLogFile(logFile)

    #
    # log startup details
    #
    logLevel = getattr(logging, opts.logLevel)
    logging.getLogger().setLevel(logLevel)
    logInfo = 'Qt4 GUI started (%s)' % (GUIConfigFile or "unnamed")
    logInfo += ', HWRSERVER=%s' % hwrServer
    if len(hoDirs) > 0:
        logInfo += ', HODIRS=%s' % os.path.pathsep.join(hoDirs)
    if len(bricksDirs) > 0:
        logInfo += ', BRICKSDIRS=%s' % os.path.pathsep.join(bricksDirs)
    logging.getLogger().info(logInfo)

    QtGui.QApplication.setDesktopSettingsAware(False) #use default settings
    QtCore.QObject.connect(app, QtCore.SIGNAL("lastWindowClosed()"), app.quit)
   
    supervisor = Qt4_GUISupervisor.GUISupervisor(designMode = opts.designMode, showMaximized=opts.showMaximized, noBorder=opts.noBorder)

    #BlissFramework.setDebugMode(True)
    #
    # post event for GUI creation
    #
    #pp.postEvent(supervisor, QtCore.QEvent(Qt4_GUISupervisor.LOAD_GUI_EVENT, GUIConfigFile))
    app.postEvent(supervisor, MyCustomEvent(Qt4_GUISupervisor.LOAD_GUI_EVENT, GUIConfigFile))
        
    #
    # redirect errors to logger
    #
    Qt4_ErrorHandler.enableStdErrRedirection()

    gevent_timer = QtCore.QTimer()
    gevent_timer.connect(gevent_timer, QtCore.SIGNAL("timeout()"), do_gevent)
    gevent_timer.start(0)

    app.setOrganizationName("MXCuBE")
    app.setOrganizationDomain("https://github.com/mxcube")
    app.setApplicationName("MXCuBE")
    #app.setWindowIcon(QIcon("images/icon.png"))
    app.exec_()



    """
    def process_qt_events():
      while True:
        time.sleep(0.01)
        while app.hasPendingEvents():
          app.processEvents() 
          time.sleep(0.01)
          if not app.mainWidget() or not app.mainWidget().isVisible():
            return
    qt_events = gevent.spawn(process_qt_events) 
    qt_events.join()   
    """

    supervisor.finalize()

    if lockfile is not None:
        filename = lockfile.name
        try:
            lockfile.close()
            os.unlink(filename)
        except:
            logging.getLogger().error("Problem removing the lock file")

    if log_lockfile is not None:
        filename = log_lockfile.name
        try:
            log_lockfile.close()
            os.unlink(filename)
        except:
            logging.getLogger().exception("Problem removing the log lock file")
Exemplo n.º 3
0
def run(gui_config_file=None):
    """Main run method"""

    default_hwr_server = 'localhost:hwr'
    #path to user's home dir. (works on Win2K, XP, Unix, Mac...)
    parser = OptionParser(usage="usage: %prog <GUI definition file> [options]")
    parser.add_option('', '--logFile', action='store', type='string',
                      help='Log file', dest='logFile', metavar='FILE',
                      default='')
    parser.add_option('', '--logLevel', action='store', type='string',
                      help='Log level', dest='logLevel', default='INFO')
    parser.add_option('', '--logTemplate', action='store', type='string',
                      help='Log template', dest='logTemplate', default='')
    parser.add_option('', '--bricksDirs', action='store', type='string',
                      help="Additional directories for bricks search " + \
                           "path (you can also use the CUSTOM_BRICKS_PATH " + \
                           "environment variable)",
                      dest='bricksDirs', metavar='dir1'+os.path.pathsep+\
                      'dir2...dirN', default='')
    parser.add_option('', '--hardwareRepository', action='store', type='string',
                      help="Hardware Repository Server host:port (default" + \
                      " to %s) (you can also use " % default_hwr_server+ \
                      "HARDWARE_REPOSITORY_SERVER the environment variable)",
                      metavar='HOST:PORT', dest='hardwareRepositoryServer',
                      default='')
    parser.add_option('', '--hardwareObjectsDirs', action='store',
                      type='string', help="Additional directories for " + \
                      "Hardware Objects search path (you can also use " + \
                      "the CUSTOM_HARDWARE_OBJECTS_PATH environment " + \
                      "variable)", dest='hardwareObjectsDirs',
                      metavar='dir1'+os.path.pathsep+'dir2...dirN', default='')
    parser.add_option('-d', '', action='store_true', dest="designMode",
                      default=False, help="start GUI in Design mode")
    parser.add_option('-m', '', action='store_true', dest="showMaximized",
                      default=False, help="maximize main window")
    parser.add_option('', '--no-border', action='store_true', dest='noBorder',
                      default=False,
                      help="does not show borders on main window")
    parser.add_option('', '--style', action='store', type='string',
                      help="Visual style of the application (windows, motif," + \
                           "cde, plastique, windowsxp, or macintosh)",
                      dest='appStyle', default=None)
    parser.add_option('', '--userFileDir', action='store', type='string',
                      help="User settings file stores application related settings " + \
                           "(window size and position). If not defined then user home " + \
                           "directory is used",
                      dest='userFileDir', default=None)

    parser.add_option('', '--pyqt4', action='store_true', default=None)
    parser.add_option('', '--pyqt5', action='store_true', default=None)
    parser.add_option('', '--pyside', action='store_true', default=None)

    (opts, args) = parser.parse_args()

    if len(args) >= 1:
        if len(args) == 1:
            gui_config_file = os.path.abspath(args[0])
        else:
            parser.error('Too many arguments.')
            sys.exit(1)

    # get config from arguments
    logFile = opts.logFile
    log_template = opts.logTemplate
    hwobj_directories = opts.hardwareObjectsDirs.split(os.path.pathsep)
    custom_bricks_directories = opts.bricksDirs.split(os.path.pathsep)
    if opts.userFileDir:
        user_file_dir = opts.userFileDir
    else:
        user_file_dir = os.path.join(os.environ["HOME"], ".mxcube")

    app_style = opts.appStyle

    if opts.hardwareRepositoryServer:
        hwr_server = opts.hardwareRepositoryServer
    else:
        # try to set Hardware Repository server from environment
        hwr_server = os.environ.get('HARDWARE_REPOSITORY_SERVER')
        if hwr_server is None:
            hwr_server = default_hwr_server

    # add bricks directories and hardware objects directories from environment
    try:
        custom_bricks_directories += \
           os.environ.get('CUSTOM_BRICKS_PATH', '').split(os.path.pathsep)
    except KeyError:
        pass

    try:
        hwobj_directories += \
           os.environ.get('CUSTOM_HARDWARE_OBJECTS_PATH', '').split(os.path.pathsep)
    except KeyError:
        pass

    try:
        if not os.path.exists(user_file_dir):
            os.makedirs(user_file_dir)
    except:
        logging.getLogger().exception(\
          "Unable to create user files directory: %s" % user_file_dir)

    custom_bricks_directories = [_directory for _directory in \
                                 custom_bricks_directories if _directory]
    hwobj_directories = [_directory for _directory in \
                         hwobj_directories if _directory]

    main_application = QApplication([])
    if app_style:
        main_application.setStyle(app_style)
    lockfile = None

    if not opts.designMode and gui_config_file:
        lock_filename = os.path.join(tempfile.gettempdir(), '.%s.lock' % \
          os.path.basename(gui_config_file or "unnamed"))

        try:
            lockfile = open(lock_filename, "w")
        except:
            logging.getLogger().exception(\
                 "Cannot create lock file (%s), exiting" % lock_filename)
            sys.exit(1)
        else:
            os.chmod(lock_filename, 0666)
            try:
                fcntl.lockf(lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except:
                logging.getLogger().exception("Cannot acquire " + \
                    "lock (%s), exiting " % lock_filename + \
                    "(hint: maybe the same application is already running ?)")
                sys.exit(1)
    # configure modules
    HardwareRepository.setHardwareRepositoryServer(hwr_server)
    HardwareRepository.setUserFileDirectory(user_file_dir)
    if hwobj_directories:
        HardwareRepository.addHardwareObjectsDirs(hwobj_directories)
    if custom_bricks_directories:
        BlissFramework.addCustomBricksDirs(custom_bricks_directories)

    # set log name and log file
    if gui_config_file:
        BlissFramework.setLoggingName(os.path.basename(gui_config_file),
                                      log_template)

    log_lockfile = None
    if len(logFile) > 0:
        log_lock_filename = os.path.join(tempfile.gettempdir(),
          '.%s.lock' % os.path.basename(logFile))

        log_ok = True
        try:
            log_lockfile = open(log_lock_filename, "w")
        except:
            log_ok = False
        else:
            try:
                os.chmod(log_lock_filename, 0o666)
            except:
                pass
            try:
                fcntl.lockf(log_lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except:
                log_ok = False
                try:
                    log_lockfile.close()
                except:
                    pass

        if not log_ok:
            index = 1
            logfile_details = os.path.splitext(logFile)
            logFile = ""
            while index < 10:
                logFile2 = "%s.%d%s" % (logfile_details[0],
                    index, logfile_details[1])
                log_lock_filename2 = os.path.join(tempfile.gettempdir(),
                    '.%s.lock' % os.path.basename(logFile2))
                try:
                    log_lockfile = open(log_lock_filename2, "w")
                except:
                    pass
                else:
                    try:
                        os.chmod(log_lock_filename2, 0o666)
                    except:
                        pass
                    try:
                        fcntl.lockf(log_lockfile.fileno(),
                                    fcntl.LOCK_EX | fcntl.LOCK_NB)
                    except:
                        pass
                    else:
                        log_ok = True
                if log_ok:
                    logFile = logFile2
                    break
            index += 1

        if len(logFile) > 0:
            BlissFramework.setLogFile(logFile)

    # log startup details
    log_level = getattr(logging, opts.logLevel)
    logging.getLogger().setLevel(log_level)
    #logging.getLogger().info("\n\n\n\n")
    logging.getLogger().info("=================================================================================")
    logging.getLogger().info("Starting MXCuBE v%s" % str(__version__))
    logging.getLogger().info("GUI file: %s" % (gui_config_file or "unnamed"))
    logging.getLogger().info("Hardware repository: %s" % hwr_server)
    logging.getLogger().info("User file directory: %s" % user_file_dir)
    if len(logFile) > 0:
        logging.getLogger().info("Log file: %s" % logFile)
    logging.getLogger().info("System info:")
    logging.getLogger().info("    - Python %s on %s" %(platform.python_version(), platform.system()))
    logging.getLogger().info("    - Qt %s - %s %s" % \
                  ("%d.%d.%d" % tuple(qt_version_no), qt_variant, "%d.%d.%d" % tuple(pyqt_version_no)) )
    if mpl_imported:
        logging.getLogger().info("    - Matplotlib %s" % "%d.%d.%d" % tuple(mpl_version_no))
    else:
        logging.getLogger().info("    - Matplotlib not available")
    logging.getLogger().info("---------------------------------------------------------------------------------")

    QApplication.setDesktopSettingsAware(False)

    main_application.lastWindowClosed.connect(main_application.quit)
    supervisor = Qt4_GUISupervisor.GUISupervisor(design_mode=opts.designMode,
        show_maximized=opts.showMaximized, no_border=opts.noBorder)
    supervisor.set_user_file_directory(user_file_dir)
    # post event for GUI creation
    main_application.postEvent(supervisor,
        MyCustomEvent(Qt4_GUISupervisor.LOAD_GUI_EVENT, gui_config_file))

    # redirect errors to logger
    Qt4_ErrorHandler.enableStdErrRedirection()

    gevent_timer = QTimer()
    gevent_timer.timeout.connect(do_gevent)
    gevent_timer.start(0)

    palette = main_application.palette()
    palette.setColor(QPalette.ToolTipBase, QColor(255, 241, 204))
    palette.setColor(QPalette.ToolTipText, Qt.black)
    main_application.setPalette(palette)

    main_application.setOrganizationName("MXCuBE")
    main_application.setOrganizationDomain("https://github.com/mxcube")
    main_application.setApplicationName("MXCuBE")
    #app.setWindowIcon(QIcon("images/icon.png"))
    main_application.exec_()

    supervisor.finalize()

    if lockfile is not None:
        filename = lockfile.name
        try:
            lockfile.close()
            os.unlink(filename)
        except:
            logging.getLogger().error("Problem removing the lock file")

    if log_lockfile is not None:
        filename = log_lockfile.name
        try:
            log_lockfile.close()
            os.unlink(filename)
        except:
            logging.getLogger().exception("Problem removing the log lock file")
Exemplo n.º 4
0
def run(gui_config_file=None):
    """Main run method"""

    default_hwr_server = 'localhost:hwr'
    #path to user's home dir. (works on Win2K, XP, Unix, Mac...)
    parser = OptionParser(usage="usage: %prog <GUI definition file> [options]")
    parser.add_option('', '--logFile', action='store', type='string',
                      help='Log file', dest='logFile', metavar='FILE',
                      default='')
    parser.add_option('', '--logLevel', action='store', type='string',
                      help='Log level', dest='logLevel', default='INFO')
    parser.add_option('', '--logTemplate', action='store', type='string',
                      help='Log template', dest='logTemplate', default='')
    parser.add_option('', '--bricksDirs', action='store', type='string',
                      help="Additional directories for bricks search " + \
                           "path (you can also use the CUSTOM_BRICKS_PATH " + \
                           "environment variable)",
                      dest='bricksDirs', metavar='dir1'+os.path.pathsep+\
                      'dir2...dirN', default='')
    parser.add_option('', '--hardwareRepository', action='store', type='string',
                      help="Hardware Repository Server host:port (default" + \
                      " to %s) (you can also use " % default_hwr_server+ \
                      "HARDWARE_REPOSITORY_SERVER the environment variable)",
                      metavar='HOST:PORT', dest='hardwareRepositoryServer',
                      default='')
    parser.add_option('', '--hardwareObjectsDirs', action='store',
                      type='string', help="Additional directories for " + \
                      "Hardware Objects search path (you can also use " + \
                      "the CUSTOM_HARDWARE_OBJECTS_PATH environment " + \
                      "variable)", dest='hardwareObjectsDirs',
                      metavar='dir1'+os.path.pathsep+'dir2...dirN', default='')
    parser.add_option('-d', '', action='store_true', dest="designMode",
                      default=False, help="start GUI in Design mode")
    parser.add_option('-m', '', action='store_true', dest="showMaximized",
                      default=False, help="maximize main window")
    parser.add_option('', '--no-border', action='store_true', dest='noBorder',
                      default=False,
                      help="does not show borders on main window")
    parser.add_option('', '--style', action='store', type='string',
                      help="Visual style of the application (windows, motif," + \
                           "cde, plastique, windowsxp, or macintosh)",
                      dest='appStyle', default=None)
    parser.add_option('', '--userFileDir', action='store', type='string',
                      help="User settings file stores application related settings " + \
                           "(window size and position). If not defined then user home " + \
                           "directory is used",
                      dest='userFileDir', default=None)

    parser.add_option('', '--pyqt4', action='store_true', default=None)
    parser.add_option('', '--pyqt5', action='store_true', default=None)
    parser.add_option('', '--pyside', action='store_true', default=None)

    (opts, args) = parser.parse_args()

    # get config from arguments
    logFile = opts.logFile
    log_template = opts.logTemplate
    hwobj_directories = opts.hardwareObjectsDirs.split(os.path.pathsep)
    custom_bricks_directories = opts.bricksDirs.split(os.path.pathsep)
    if opts.userFileDir:
        user_file_dir = opts.userFileDir
    else:
        user_file_dir = os.path.join(os.environ["HOME"], ".mxcube")

    app_style = opts.appStyle

    if opts.hardwareRepositoryServer:
        hwr_server = opts.hardwareRepositoryServer
    else:
        # try to set Hardware Repository server from environment
        hwr_server = os.environ.get('HARDWARE_REPOSITORY_SERVER')
        if hwr_server is None:
            hwr_server = default_hwr_server

    # add bricks directories and hardware objects directories from environment
    try:
        custom_bricks_directories += \
           os.environ.get('CUSTOM_BRICKS_PATH', '').split(os.path.pathsep)
    except KeyError:
        pass

    try:
        hwobj_directories += \
           os.environ.get('CUSTOM_HARDWARE_OBJECTS_PATH', '').split(os.path.pathsep)
    except KeyError:
        pass

    try:
        if not os.path.exists(user_file_dir):
            os.makedirs(user_file_dir)
    except:
        logging.getLogger().exception(\
          "Unable to create user files directory: %s" % user_file_dir)

    custom_bricks_directories = [_directory for _directory in \
                                 custom_bricks_directories if _directory]
    hwobj_directories = [_directory for _directory in \
                         hwobj_directories if _directory]

    main_application = QApplication([])
    if app_style:
        main_application.setStyle(app_style)
    lockfile = None

    if len(args) >= 1:
        if len(args) == 1:
            gui_config_file = os.path.abspath(args[0])
        else:
            parser.error('Too many arguments.')
            sys.exit(1)

    if len( os.popen( "ps -aef | grep 'python' -i | grep 'hardwareRepository'  | grep -v 'grep' | awk '{ print $3 }'" ).read().strip().split( '\n' )) > 1:
        QMessageBox.warning(None, "Warning", "Another instance of MXCuBE is running.\n" + \
                            "Please close it and start MXCuBE again.",
                            QMessageBox.Ok)
        sys.exit(1)

    # configure modules
    HardwareRepository.setHardwareRepositoryServer(hwr_server)
    HardwareRepository.setUserFileDirectory(user_file_dir)
    if hwobj_directories:
        HardwareRepository.addHardwareObjectsDirs(hwobj_directories)
    if custom_bricks_directories:
        BlissFramework.addCustomBricksDirs(custom_bricks_directories)

    # set log name and log file
    if gui_config_file:
        BlissFramework.setLoggingName(os.path.basename(gui_config_file),
                                      log_template)

    log_lockfile = None
    if len(logFile) > 0:
        log_lock_filename = os.path.join(tempfile.gettempdir(),
          '.%s.lock' % os.path.basename(logFile))

        log_ok = True
        try:
            log_lockfile = open(log_lock_filename, "w")
        except:
            log_ok = False
        else:
            try:
                os.chmod(log_lock_filename, 0o666)
            except:
                pass
            try:
                fcntl.lockf(log_lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except:
                log_ok = False
                try:
                    log_lockfile.close()
                except:
                    pass

        if not log_ok:
            index = 1
            logfile_details = os.path.splitext(logFile)
            logFile = ""
            while index < 10:
                logFile2 = "%s.%d%s" % (logfile_details[0],
                    index, logfile_details[1])
                log_lock_filename2 = os.path.join(tempfile.gettempdir(),
                    '.%s.lock' % os.path.basename(logFile2))
                try:
                    log_lockfile = open(log_lock_filename2, "w")
                except:
                    pass
                else:
                    try:
                        os.chmod(log_lock_filename2, 0o666)
                    except:
                        pass
                    try:
                        fcntl.lockf(log_lockfile.fileno(),
                                    fcntl.LOCK_EX | fcntl.LOCK_NB)
                    except:
                        pass
                    else:
                        log_ok = True
                if log_ok:
                    logFile = logFile2
                    break
            index += 1

        if len(logFile) > 0:
            BlissFramework.setLogFile(logFile)

    # log startup details
    log_level = getattr(logging, opts.logLevel)
    logging.getLogger().setLevel(log_level)
    #logging.getLogger().info("\n\n\n\n")
    logging.getLogger().info("=================================================================================")
    logging.getLogger().info("Starting MXCuBE v%s" % str(__version__))
    logging.getLogger().info("GUI file: %s" % (gui_config_file or "unnamed"))
    logging.getLogger().info("Hardware repository: %s" % hwr_server)
    logging.getLogger().info("User file directory: %s" % user_file_dir)
    if len(logFile) > 0:
        logging.getLogger().info("Log file: %s" % logFile)
    logging.getLogger().info("System info:")
    logging.getLogger().info("    - Python %s on %s" %(platform.python_version(), platform.system()))
    logging.getLogger().info("    - Qt %s - %s %s" % \
                  ("%d.%d.%d" % tuple(qt_version_no), qt_variant, "%d.%d.%d" % tuple(pyqt_version_no)) )
    if mpl_imported:
        logging.getLogger().info("    - Matplotlib %s" % "%d.%d.%d" % tuple(mpl_version_no))
    else:
        logging.getLogger().info("    - Matplotlib not available")
    logging.getLogger().info("---------------------------------------------------------------------------------")

    QApplication.setDesktopSettingsAware(False)

    main_application.lastWindowClosed.connect(main_application.quit)
    supervisor = Qt4_GUISupervisor.GUISupervisor(design_mode=opts.designMode,
        show_maximized=opts.showMaximized, no_border=opts.noBorder)
    supervisor.set_user_file_directory(user_file_dir)
    # post event for GUI creation
    main_application.postEvent(supervisor,
        MyCustomEvent(Qt4_GUISupervisor.LOAD_GUI_EVENT, gui_config_file))

    # redirect errors to logger
    Qt4_ErrorHandler.enableStdErrRedirection()

    gevent_timer = QTimer()
    gevent_timer.timeout.connect(do_gevent)
    gevent_timer.start(0)

    palette = main_application.palette()
    palette.setColor(QPalette.ToolTipBase, QColor(255, 241, 204))
    palette.setColor(QPalette.ToolTipText, Qt.black)
    main_application.setPalette(palette)

    main_application.setOrganizationName("MXCuBE")
    main_application.setOrganizationDomain("https://github.com/mxcube")
    main_application.setApplicationName("MXCuBE")
    #app.setWindowIcon(QIcon("images/icon.png"))
    main_application.exec_()

    supervisor.finalize()

    if log_lockfile is not None:
        filename = log_lockfile.name
        try:
            log_lockfile.close()
            os.unlink(filename)
        except:
            logging.getLogger().exception("Problem removing the log lock file")
Exemplo n.º 5
0
def run(GUIConfigFile=None):
    defaultHwrServer = "localhost:hwr"
    # path to user's home dir. (works on Win2K, XP, Unix, Mac...)
    userHomeDir = os.path.expanduser("~")

    parser = OptionParser(usage="usage: %prog <GUI definition file> [options]")
    parser.add_option(
        "",
        "--logFile",
        action="store",
        type="string",
        help="Log file",
        dest="logFile",
        metavar="FILE",
        default="",
    )
    parser.add_option(
        "",
        "--logLevel",
        action="store",
        type="string",
        help="Log level",
        dest="logLevel",
        default="INFO",
    )
    parser.add_option(
        "",
        "--bricksDirs",
        action="store",
        type="string",
        help="Additional directories for bricks search path (you can also use the CUSTOM_BRICKS_PATH environment variable)",
        dest="bricksDirs",
        metavar="dir1" + os.path.pathsep + "dir2...dirN",
        default="",
    )
    parser.add_option(
        "",
        "--hardwareRepository",
        action="store",
        type="string",
        help="Hardware Repository Server host:port (default to %s) (you can also use HARDWARE_REPOSITORY_SERVER the environment variable)"
        % defaultHwrServer,
        metavar="HOST:PORT",
        dest="hardwareRepositoryServer",
        default="",
    )
    parser.add_option(
        "",
        "--hardwareObjectsDirs",
        action="store",
        type="string",
        help="Additional directories for Hardware Objects search path (you can also use the CUSTOM_HARDWARE_OBJECTS_PATH environment variable)",
        dest="hardwareObjectsDirs",
        metavar="dir1" + os.path.pathsep + "dir2...dirN",
        default="",
    )
    parser.add_option(
        "-d",
        "",
        action="store_true",
        dest="designMode",
        default=False,
        help="start GUI in Design mode",
    )
    parser.add_option(
        "-m",
        "",
        action="store_true",
        dest="showMaximized",
        default=False,
        help="maximize main window",
    )
    parser.add_option(
        "",
        "--no-border",
        action="store_true",
        dest="noBorder",
        default=False,
        help="does not show borders on main window",
    )
    parser.add_option(
        "-w",
        "--web-server-port",
        action="store",
        type="int",
        dest="webServerPort",
        default=0,
        help="port number for the remote interpreter web application server",
    )
    # parser.add_option('', '--widgetcount', action='store_true', dest='widgetCount', default=False, help="prints debug message at the end about number of widgets left undestroyed")

    (opts, args) = parser.parse_args()

    if len(args) >= 1:
        if len(args) == 1:
            GUIConfigFile = os.path.abspath(args[0])
        else:
            parser.error("Too many arguments.")
            sys.exit(1)

    if opts.webServerPort:
        from BlissFramework.Utils import terminal_server

        interpreter = terminal_server.InteractiveInterpreter()
        terminal_server.set_interpreter(interpreter)
        gevent.spawn(terminal_server.serve_forever, opts.webServerPort)

    #
    # get config from arguments
    #
    logFile = opts.logFile
    hoDirs = opts.hardwareObjectsDirs.split(os.path.pathsep)
    bricksDirs = opts.bricksDirs.split(os.path.pathsep)

    if opts.hardwareRepositoryServer:
        hwrServer = opts.hardwareRepositoryServer
    else:
        #
        # try to set Hardware Repository server from environment
        #
        try:
            hwrServer = os.environ["HARDWARE_REPOSITORY_SERVER"]
        except KeyError:
            hwrServer = defaultHwrServer

    #
    # add bricks directories and hardware objects directories from environment
    #
    try:
        bricksDirs += os.environ["CUSTOM_BRICKS_PATH"].split(os.path.pathsep)
    except KeyError:
        pass

    try:
        hoDirs += os.environ["CUSTOM_HARDWARE_OBJECTS_PATH"].split(os.path.pathsep)
    except KeyError:
        pass

    bricksDirs = filter(None, bricksDirs)
    hoDirs = filter(None, hoDirs)

    app = QApplication([])
    lockfile = None

    if not opts.designMode and GUIConfigFile:
        lock_filename = os.path.join(
            tempfile.gettempdir(),
            ".%s.lock" % os.path.basename(GUIConfigFile or "unnamed"),
        )
        try:
            lockfile = open(lock_filename, "w")
        except BaseException:
            logging.getLogger().exception(
                "Cannot create lock file (%s), exiting" % lock_filename
            )

            sys.exit(1)
        else:
            os.chmod(lock_filename, 0o666)
            try:
                fcntl.lockf(lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except BaseException:
                logging.getLogger().exception(
                    "Cannot acquire lock (%s), exiting (hint: maybe the same application is already running ?)"
                    % lock_filename
                )

                sys.exit(1)

    #
    # configure modules
    #
    HardwareRepository.setHardwareRepositoryServer(hwrServer)
    HardwareRepository.addHardwareObjectsDirs(hoDirs)
    BlissFramework.addCustomBricksDirs(bricksDirs)

    #
    # set log name and log file
    #
    if GUIConfigFile:
        BlissFramework.setLoggingName(os.path.basename(GUIConfigFile))

    log_lockfile = None
    if len(logFile) > 0:
        log_lock_filename = os.path.join(
            tempfile.gettempdir(), ".%s.lock" % os.path.basename(logFile)
        )

        log_ok = True
        try:
            log_lockfile = open(log_lock_filename, "w")
        except BaseException:
            log_ok = False
        else:
            try:
                os.chmod(log_lock_filename, 0o666)
            except BaseException:
                pass
            try:
                fcntl.lockf(log_lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except BaseException:
                log_ok = False
                try:
                    log_lockfile.close()
                except BaseException:
                    pass

        if not log_ok:
            i = 1
            logfile_details = os.path.splitext(logFile)
            logFile = ""
            while i < 10:
                logFile2 = "%s.%d%s" % (logfile_details[0], i, logfile_details[1])
                log_lock_filename2 = os.path.join(
                    tempfile.gettempdir(), ".%s.lock" % os.path.basename(logFile2)
                )
                try:
                    log_lockfile = open(log_lock_filename2, "w")
                except BaseException:
                    pass
                else:
                    try:
                        os.chmod(log_lock_filename2, 0o666)
                    except BaseException:
                        pass
                    try:
                        fcntl.lockf(
                            log_lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB
                        )
                    except BaseException:
                        pass
                    else:
                        log_ok = True
                if log_ok:
                    logFile = logFile2
                    break
                i += 1

        if len(logFile) > 0:
            BlissFramework.setLogFile(logFile)

    #
    # log startup details
    #
    logLevel = getattr(logging, opts.logLevel)
    logging.getLogger().setLevel(logLevel)
    logInfo = "GUI started (%s)" % (GUIConfigFile or "unnamed")
    logInfo += ", HWRSERVER=%s" % hwrServer
    if len(hoDirs) > 0:
        logInfo += ", HODIRS=%s" % os.path.pathsep.join(hoDirs)
    if len(bricksDirs) > 0:
        logInfo += ", BRICKSDIRS=%s" % os.path.pathsep.join(bricksDirs)
    logging.getLogger().info(logInfo)

    QApplication.setDesktopSettingsAware(False)  # use default settings
    QObject.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))

    supervisor = GUISupervisor.GUISupervisor(
        designMode=opts.designMode,
        showMaximized=opts.showMaximized,
        noBorder=opts.noBorder,
    )

    # BlissFramework.setDebugMode(True)
    #
    # post event for GUI creation
    #
    app.postEvent(supervisor, QCustomEvent(GUISupervisor.LOAD_GUI_EVENT, GUIConfigFile))

    #
    # redirect errors to logger
    #
    ErrorHandler.enableStdErrRedirection()

    timer = QTimer()
    timer.connect(timer, SIGNAL("timeout()"), do_gevent)
    timer.start(0)

    app.exec_loop()
    """
    def process_qt_events():
      while True:
        time.sleep(0.01)
        while app.hasPendingEvents():
          app.processEvents()
          time.sleep(0.01)
          if not app.mainWidget() or not app.mainWidget().isVisible():
            return
    qt_events = gevent.spawn(process_qt_events)
    qt_events.join()
    """

    supervisor.finalize()

    if lockfile is not None:
        filename = lockfile.name
        try:
            lockfile.close()
            os.unlink(filename)
        except BaseException:
            logging.getLogger().error("Problem removing the lock file")

    if log_lockfile is not None:
        filename = log_lockfile.name
        try:
            log_lockfile.close()
            os.unlink(filename)
        except BaseException:
            logging.getLogger().exception("Problem removing the log lock file")
Exemplo n.º 6
0
def run(gui_config_file=None):
    """Main run method"""

    default_hwr_server = 'localhost:hwr'
    #path to user's home dir. (works on Win2K, XP, Unix, Mac...)
    parser = OptionParser(usage="usage: %prog <GUI definition file> [options]")
    parser.add_option('', '--logFile', action='store', type='string',
                      help='Log file', dest='logFile', metavar='FILE',
                      default='')
    parser.add_option('', '--logLevel', action='store', type='string',
                      help='Log level', dest='logLevel', default='INFO')
    parser.add_option('', '--logTemplate', action='store', type='string',
                      help='Log template', dest='logTemplate', default='')
    parser.add_option('', '--bricksDirs', action='store', type='string',
                      help="Additional directories for bricks search " + \
                           "path (you can also use the CUSTOM_BRICKS_PATH " + \
                           "environment variable)",
                      dest='bricksDirs', metavar='dir1'+os.path.pathsep+\
                      'dir2...dirN', default='')
    parser.add_option('', '--hardwareRepository', action='store', type='string',
                      help="Hardware Repository Server host:port (default" + \
                      " to %s) (you can also use " % default_hwr_server+ \
                      "HARDWARE_REPOSITORY_SERVER the environment variable)",
                      metavar='HOST:PORT', dest='hardwareRepositoryServer',
                      default='')
    parser.add_option('', '--hardwareObjectsDirs', action='store',
                      type='string', help="Additional directories for " + \
                      "Hardware Objects search path (you can also use " + \
                      "the CUSTOM_HARDWARE_OBJECTS_PATH environment " + \
                      "variable)", dest='hardwareObjectsDirs',
                      metavar='dir1'+os.path.pathsep+'dir2...dirN', default='')
    parser.add_option('-d', '', action='store_true', dest="designMode",
                      default=False, help="start GUI in Design mode")
    parser.add_option('-m', '', action='store_true', dest="showMaximized",
                      default=False, help="maximize main window")
    parser.add_option('', '--no-border', action='store_true', dest='noBorder',
                      default=False,
                      help="does not show borders on main window")
    parser.add_option('', '--style', action='store', type='string',
                      help="Visual style of the application (windows, motif," + \
                           "cde, plastique, windowsxp, or macintosh)",
                      dest='appStyle', default=None)

    (opts, args) = parser.parse_args()

    if len(args) >= 1:
        if len(args) == 1:
            gui_config_file = os.path.abspath(args[0])
        else:
            parser.error('Too many arguments.')
            sys.exit(1)

    # get config from arguments
    logFile = opts.logFile
    log_template = opts.logTemplate
    hwobj_directory = opts.hardwareObjectsDirs.split(os.path.pathsep)
    custom_bricks_directory = opts.bricksDirs.split(os.path.pathsep)
    app_style = opts.appStyle

    if opts.hardwareRepositoryServer:
        hwr_server = opts.hardwareRepositoryServer
    else:
        # try to set Hardware Repository server from environment
        try:
            hwr_server = os.environ['HARDWARE_REPOSITORY_SERVER']
        except KeyError:
            hwr_server = default_hwr_server

    # add bricks directories and hardware objects directories from environment
    try:
        custom_bricks_directory += \
           os.environ['CUSTOM_BRICKS_PATH'].split(os.path.pathsep)
    except KeyError:
        pass

    try:
        hwobj_directory += \
           os.environ['CUSTOM_HARDWARE_OBJECTS_PATH'].split(os.path.pathsep)
    except KeyError:
        pass

    custom_bricks_directory = [_directory for _directory in \
          custom_bricks_directory if _directory]
    hwobj_directory = [_directory for _directory in \
          hwobj_directory if _directory]

    main_application = QtGui.QApplication([])
    if app_style:
        main_application.setStyle(app_style)
    lockfile = None

    if not opts.designMode and gui_config_file:
        lock_filename = os.path.join(tempfile.gettempdir(), '.%s.lock' % \
          os.path.basename(gui_config_file or "unnamed"))
        try:
            lockfile = open(lock_filename, "w")
        except:
            logging.getLogger().exception(\
                 "Cannot create lock file (%s), exiting" % lock_filename)
            sys.exit(1)
        else:
            os.chmod(lock_filename, 0o666)
            try:
                fcntl.lockf(lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except:
                logging.getLogger().exception("Cannot acquire " + \
                    "lock (%s), exiting " % lock_filename + \
                    "(hint: maybe the same application is already running ?)")
                sys.exit(1)

    # configure modules
    HardwareRepository.setHardwareRepositoryServer(hwr_server)
    HardwareRepository.addHardwareObjectsDirs(hwobj_directory)
    BlissFramework.addCustomBricksDirs(custom_bricks_directory)

    # set log name and log file
    if gui_config_file:
        BlissFramework.setLoggingName(os.path.basename(gui_config_file),
                                      log_template)

    log_lockfile = None
    if len(logFile) > 0:
        log_lock_filename = os.path.join(tempfile.gettempdir(),
          '.%s.lock' % os.path.basename(logFile))

        log_ok = True
        try:
            log_lockfile = open(log_lock_filename, "w")
        except:
            log_ok = False
        else:
            try:
                os.chmod(log_lock_filename, 0o666)
            except:
                pass
            try:
                fcntl.lockf(log_lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except:
                log_ok = False
                try:
                    log_lockfile.close()
                except:
                    pass

        if not log_ok:
            index = 1
            logfile_details = os.path.splitext(logFile)
            logFile = ""
            while index < 10:
                logFile2 = "%s.%d%s" % (logfile_details[0],
                    index, logfile_details[1])
                log_lock_filename2 = os.path.join(tempfile.gettempdir(),
                    '.%s.lock' % os.path.basename(logFile2))
                try:
                    log_lockfile = open(log_lock_filename2, "w")
                except:
                    pass
                else:
                    try:
                        os.chmod(log_lock_filename2, 0o666)
                    except:
                        pass
                    try:
                        fcntl.lockf(log_lockfile.fileno(),
                                    fcntl.LOCK_EX | fcntl.LOCK_NB)
                    except:
                        pass
                    else:
                        log_ok = True
                if log_ok:
                    logFile = logFile2
                    break
            index += 1

        if len(logFile) > 0:
            BlissFramework.setLogFile(logFile)

    # log startup details
    log_level = getattr(logging, opts.logLevel)
    logging.getLogger().setLevel(log_level)
    print ("=================================================================================")
    logging.getLogger().info("Starting MXCuBE")
    logging.getLogger().info("Qt4 GUI file: %s" % (gui_config_file or "unnamed"))
    logging.getLogger().info("Hardware repository: %s" % hwr_server)
    print ("---------------------------------------------------------------------------------")

    QtGui.QApplication.setDesktopSettingsAware(False)
    QtCore.QObject.connect(main_application,
                           QtCore.SIGNAL("lastWindowClosed()"),
                           main_application.quit)
 
    supervisor = Qt4_GUISupervisor.GUISupervisor(design_mode=opts.designMode,
        show_maximized=opts.showMaximized, no_border=opts.noBorder)

    # post event for GUI creation
    main_application.postEvent(supervisor,
        MyCustomEvent(Qt4_GUISupervisor.LOAD_GUI_EVENT, gui_config_file))

    # redirect errors to logger
    Qt4_ErrorHandler.enableStdErrRedirection()

    gevent_timer = QtCore.QTimer()
    gevent_timer.connect(gevent_timer, QtCore.SIGNAL("timeout()"), do_gevent)
    gevent_timer.start(0)

    main_application.setOrganizationName("MXCuBE")
    main_application.setOrganizationDomain("https://github.com/mxcube")
    main_application.setApplicationName("MXCuBE")
    #app.setWindowIcon(QIcon("images/icon.png"))
    main_application.exec_()

    supervisor.finalize()

    if lockfile is not None:
        filename = lockfile.name
        try:
            lockfile.close()
            os.unlink(filename)
        except:
            logging.getLogger().error("Problem removing the lock file")

    if log_lockfile is not None:
        filename = log_lockfile.name
        try:
            log_lockfile.close()
            os.unlink(filename)
        except:
            logging.getLogger().exception("Problem removing the log lock file")