Пример #1
0
    def initializeInstance(self):
        # Remove BlissFramework application lockfile
        #self.guiConfiguration=qt.qApp.mainWidget().configuration

        if BlissFramework.get_gui_version() == "qt3":
            from qt import qApp
            self.guiConfiguration = qApp.mainWidget().configuration
        elif BlissFramework.get_gui_version() == "qt4":
            from PyQt4.QtGui import QApplication
            self.guiConfiguration = QApplication.activeWindow().configuration
        else:
            logging.getLogger("HWR").error('InstanceServer: % gui version not supported' % \
                                            BlissFramework.get_gui_version())

        lockfilename = os.path.join(tempfile.gettempdir(),
                                    '.%s.lock' % BlissFramework.loggingName)

        try:
            os.unlink(lockfilename)
        except:
            pass
        self.emit('instanceInitializing', ())
        if self.isLocal():
            self.startServer()
        else:
            self.connectToServer()
Пример #2
0
 def loadUIFile(self, filename):
     for path in [BlissFramework.getStdBricksPath()
                  ] + BlissFramework.getCustomBricksDirs():
         # modulePath = sys.modules[self.__class__.__module__].__file__
         # path = os.path.dirname(modulePath)
         if os.path.exists(os.path.join(path, filename)):
             return qtui.QWidgetFactory.create(os.path.join(path, filename))
    def initializeInstance(self):
        # Remove BlissFramework application lockfile
        #self.guiConfiguration=qt.qApp.mainWidget().configuration

        if BlissFramework.get_gui_version() == "qt3":
            from qt import qApp
            self.guiConfiguration = qApp.mainWidget().configuration     
        elif BlissFramework.get_gui_version() == "qt4":
            from PyQt4.QtGui import QApplication
            self.guiConfiguration = QApplication.activeWindow().configuration
        else:
            logging.getLogger("HWR").error('InstanceServer: % gui version not supported' % \
                                            BlissFramework.get_gui_version())

        lockfilename=os.path.join(tempfile.gettempdir(), '.%s.lock' % BlissFramework.loggingName)
        
        try:
            os.unlink(lockfilename)
        except:
            pass
        self.emit('instanceInitializing', ())
        if self.isLocal():
            self.startServer()
        else:
            self.connectToServer()
Пример #4
0
 def loadUIFile(self, filename):
     """
     Descript. :
     """
     for path in [BlissFramework.getStdBricksPath()] + \
                  BlissFramework.getCustomBricksDirs():
         if os.path.exists(os.path.join(path, filename)):
             return qtui.QWidgetFactory.create(os.path.join(path, filename))
Пример #5
0
 def loadUIFile(self, filename):
     for path in [
         BlissFramework.getStdBricksPath()
     ] + BlissFramework.getCustomBricksDirs():
         # modulePath = sys.modules[self.__class__.__module__].__file__
         # path = os.path.dirname(modulePath)
         if os.path.exists(os.path.join(path, filename)):
             return qtui.QWidgetFactory.create(os.path.join(path, filename))
Пример #6
0
 def refresh(self):
     """Refresh bricks window"""
     while self.bricksToolbox.currentItem():
         self.bricksToolbox.removeItem(self.bricksToolbox.currentItem())
    
     self.bricks = {}
     self.bricksTab = {}
         
     self.addBrickTab("General")
     # bricks without category fall into 'General'
     self.bricksTab[""] = self.bricksTab["General"]
    
     map(self.addBricks, (BlissFramework.getStdBricksPath(), ) + tuple(BlissFramework.getCustomBricksDirs()))
Пример #7
0
 def refresh(self):
     """Refresh bricks window"""
     while self.bricksToolbox.currentItem():
         self.bricksToolbox.removeItem(self.bricksToolbox.currentItem())
    
     self.bricks = {}
     self.bricksTab = {}
         
     self.addBrickTab("General")
     # bricks without category fall into 'General'
     self.bricksTab[""] = self.bricksTab["General"]
    
     map(self.addBricks, (BlissFramework.getStdBricksPath(), ) + tuple(BlissFramework.getCustomBricksDirs()))
Пример #8
0
    def getHardwareObject(self, hardware_object_name, optional=False):
        """
        Descript. :
        """
        splash_screen = BlissFramework.get_splash_screen()
        if splash_screen:
            splash_screen.set_message(\
                "Loading hardware object defined in %s.xml" %
                hardware_object_name)

        if not hardware_object_name in self.__loaded_hardware_objects:
            self.__loaded_hardware_objects.append(hardware_object_name)

        hwobj = HardwareRepository.HardwareRepository().\
                   getHardwareObject(hardware_object_name)

        if hwobj is not None:
            self.connect(hwobj, "progressInit", self.progress_init)
            self.connect(hwobj, 'progressStep', self.progress_step)
            self.connect(hwobj, 'progressStop', self.progress_stop)
            self.connect(hwobj, 'statusMessage', self.status_message_changed)

        if hwobj is None and not optional:
            logging.getLogger("GUI").error(\
               "%s: Unable to initialize hardware object defined in %s.xml" % \
                (self.objectName(),
                 hardware_object_name[1:]))
            self.set_background_color(Qt4_widget_colors.LIGHT_RED)
            self.__failed_to_load_hwobj = True
            self.setDisabled(True)

        return hwobj
Пример #9
0
    def launchGUIClicked(self):
        if self.guiEditorWindow.configuration.hasChanged or self.filename is None:
            if qt.QMessageBox.warning(self, "GUI file not saved yet",
                                      "Before starting the GUI, the file needs to be saved.\nContinue ?",
                                      qt.QMessageBox.Yes, qt.QMessageBox.No) == qt.QMessageBox.No:
                return
            
            self.saveClicked()
            
        terminal = os.environ["TERM"] or "xterm"

        try:
            hwr_server = HardwareRepository.HardwareRepository().serverAddress
        except:
            logging.getLogger().error("Sorry, could not find Hardware Repository server")
        else:
            customBricksDirs = os.path.pathsep.join(BlissFramework.getCustomBricksDirs())
            pid = subprocess.Popen("%s -title %s -e startGUI --bricksDirs=%s %s%s" % (terminal,os.path.basename(self.filename),customBricksDirs, (hwr_server and "--hardwareRepository=%s " % hwr_server or ""), self.filename), shell=True).pid
            
            logging.getLogger().debug("GUI launched, pid is %d", pid)
Пример #10
0
    def launchGUIClicked(self):
        if self.guiEditorWindow.configuration.hasChanged or self.filename is None:
            if qt.QMessageBox.warning(self, "GUI file not saved yet",
                                      "Before starting the GUI, the file needs to be saved.\nContinue ?",
                                      qt.QMessageBox.Yes, qt.QMessageBox.No) == qt.QMessageBox.No:
                return
            
            self.saveClicked()
            
        terminal = os.environ["TERM"] or "xterm"

        try:
            hwr_server = HardwareRepository.HardwareRepository().serverAddress
        except:
            logging.getLogger().error("Sorry, could not find Hardware Repository server")
        else:
            customBricksDirs = os.path.pathsep.join(BlissFramework.getCustomBricksDirs())
            pid = subprocess.Popen("%s -title %s -e startGUI --bricksDirs=%s %s%s" % (terminal,os.path.basename(self.filename),customBricksDirs, (hwr_server and "--hardwareRepository=%s " % hwr_server or ""), self.filename), shell=True).pid
            
            logging.getLogger().debug("GUI launched, pid is %d", pid)
Пример #11
0
    def getHardwareObject(self, hardware_object_name, optional=False):
        """
        Descript. :
        """
        splash_screen = BlissFramework.get_splash_screen()
        if splash_screen:
            splash_screen.set_message(\
                "Loading hardware object defined in %s.xml" %
                hardware_object_name)        

        if not hardware_object_name in self.__loaded_hardware_objects:
            self.__loaded_hardware_objects.append(hardware_object_name)

        hwobj = HardwareRepository.getHardwareRepository().\
                   getHardwareObject(hardware_object_name)

        if hwobj is not None:
            self.connect(hwobj,
                         "progressInit",
                         self.progress_init)
            self.connect(hwobj,
                         'progressStep',
                         self.progress_step)
            self.connect(hwobj,
                         'progressStop',
                         self.progress_stop)
            self.connect(hwobj,
                         'statusMessage',
                         self.status_message_changed)

        if hwobj is None and not optional:
            logging.getLogger("GUI").error(\
               "%s: Unable to initialize hardware object defined in %s.xml" % \
                (self.objectName(),
                 hardware_object_name[1:]))
            self.set_background_color(Qt4_widget_colors.LIGHT_RED)
            self.__failed_to_load_hwobj = True
            self.setDisabled(True)

        return hwobj
Пример #12
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")
Пример #13
0
import gevent
import time
import fcntl
import tempfile
import socket
import sys
import os
import logging
import traceback
from optparse import OptionParser

from PyQt4 import QtCore
from PyQt4 import QtGui

import BlissFramework
BlissFramework.set_gui_version("qt4")
from BlissFramework import Qt4_GUISupervisor
from BlissFramework.Utils import Qt4_ErrorHandler
from BlissFramework.Utils import Qt4_GUILogHandler

#from BlissFramework.Utils import terminal_server

from HardwareRepository import HardwareRepository

_logger = logging.getLogger()
_GUIhdlr = Qt4_GUILogHandler.GUILogHandler()
_logger.addHandler(_GUIhdlr)


def do_gevent():
    """
Пример #14
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")
Пример #15
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")
Пример #16
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")
Пример #17
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")
Пример #18
0
import gevent
import time
import fcntl
import tempfile
import socket
import sys
import os
import logging
import traceback
from optparse import OptionParser

from PyQt4 import QtCore
from PyQt4 import QtGui

import BlissFramework
BlissFramework.set_gui_version("qt4")
from BlissFramework import Qt4_GUISupervisor
from BlissFramework.Utils import Qt4_ErrorHandler
from BlissFramework.Utils import Qt4_GUILogHandler

#from BlissFramework.Utils import terminal_server

from HardwareRepository import HardwareRepository

_logger = logging.getLogger()
_GUIhdlr = Qt4_GUILogHandler.GUILogHandler()
_logger.addHandler(_GUIhdlr)


def do_gevent():
    """
Пример #19
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")