示例#1
0
文件: example2.py 项目: hdfeos/ginga
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    viewer = FitsViewer(logger)

    viewer.top.resize(700, 540)

    if len(args) > 0:
        viewer.load_file(args[0])

    viewer.top.show()
    viewer.top.raise_()

    try:
        app = viewer.top.get_app()

        # TODO: unify these
        if hasattr(app, "start"):
            app.start()

        else:
            while True:
                app.process_events()

    except KeyboardInterrupt:
        print("Terminating viewer...")
        if viewer.top is not None:
            viewer.top.close()
示例#2
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    viewer = FitsViewer(logger)

    viewer.top.resize(700, 540)

    if len(args) > 0:
        viewer.load_file(viewer.viewer1, args[0])

    viewer.top.show()
    viewer.top.raise_()

    try:
        viewer.mainloop()

    except KeyboardInterrupt:
        print("Terminating viewer...")
        if viewer.top is not None:
            viewer.top.close()
示例#3
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    viewer = FitsViewer(logger)

    viewer.top.resize(700, 540)

    if len(args) > 0:
        viewer.load_file(viewer.viewer1, args[0])

    viewer.top.show()
    viewer.top.raise_()

    try:
        viewer.app.mainloop()

    except KeyboardInterrupt:
        print("Terminating viewer...")
        if viewer.top is not None:
            viewer.top.close()
示例#4
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    # event for synchronizing exit of all threads
    ev_quit = threading.Event()

    gv = GingaVision(logger, ev_quit, options)
    gv.top.resize(670, 540)
    gv.top.show()
    gv.top.raise_()

    # start video capture thread
    if len(args) > 0:
        filename = args[0]
    else:
        # default video input device
        filename = 0

    gv.main.nongui_do(gv.capture_video, filename)

    gv.main.mainloop()
    logger.info("program terminating...")
    sys.exit(0)
示例#5
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    # event for synchronizing exit of all threads
    ev_quit = threading.Event()

    gv = GingaVision(logger, ev_quit, options)
    gv.top.resize(670, 540)
    gv.top.show()
    gv.top.raise_()

    # start video capture thread
    if len(args) > 0:
        filename = args[0]
    else:
        # default video input device
        filename = 0

    gv.main.nongui_do(gv.capture_video, filename)

    gv.main.mainloop()
    logger.info("program terminating...")
    sys.exit(0)
示例#6
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    viewer = FitsViewer(logger)

    viewer.top.resize(700, 540)

    if len(args) > 0:
        viewer.load_file(args[0])

    viewer.top.show()
    viewer.top.raise_()

    try:
        app = viewer.top.get_app()

        # TODO: unify these
        if hasattr(app, 'start'):
            app.start()

        else:
            while True:
                app.process_events()

    except KeyboardInterrupt:
        print("Terminating viewer...")
        if viewer.top is not None:
            viewer.top.close()
示例#7
0
文件: clocks.py 项目: mfwofford/ginga
def main(options, args):

    # TODO: when ginga gets updated on the summit
    logger = log.get_logger("clocks", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    cfgfile = os.path.join(ginga_home, "clocks.cfg")
    settings = SettingGroup(name='clocks', logger=logger, preffile=cfgfile)
    settings.load(onError='silent')

    clock = ClockApp(logger, settings, options)

    if len(options.args) == 0:
        zones = ['UTC']
        #zones = ['HST', 'Asia/Tokyo', 'UTC']
    else:
        zones = options.args
    cols = settings.get('columns', 3)

    wd, ht = width * cols, height
    if options.show_seconds:
        wd += cols * 300
    clock.top.resize(wd, ht)

    # get the list of colors
    if options.colors is None:
        colors = clock.colors
    else:
        colors = options.colors.split(',')

    # get the list of time zones
    for i, zone in enumerate(zones):
        color = colors[i % len(colors)]
        clock.add_clock(zone, color=color)
        clock.color_index = i + 1

    clock.top.show()

    if options.geometry is not None:
        clock.set_geometry(options.geometry)

    clock.top.raise_()

    try:
        app = clock.top.get_app()
        app.mainloop()

    except KeyboardInterrupt:
        if clock.top is not None:
            clock.top.close()

    logger.info("Terminating clocks...")
示例#8
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    if options.use_opencv:
        from ginga import trcalc
        try:
            trcalc.use('opencv')
        except Exception as e:
            logger.warning("Error using OpenCv: %s" % str(e))

    if options.use_opencl:
        from ginga import trcalc
        try:
            trcalc.use('opencl')
        except Exception as e:
            logger.warning("Error using OpenCL: %s" % str(e))

    viewer = FitsViewer(logger)

    if options.renderer is not None:
        render_class = render.get_render_class(options.renderer)
        viewer.fitsimage.set_renderer(render_class(viewer.fitsimage))

    viewer.top.resize(700, 540)

    if len(args) > 0:
        viewer.load_file(args[0])

    viewer.top.show()
    viewer.top.raise_()

    try:
        app = viewer.top.get_app()
        app.mainloop()

    except KeyboardInterrupt:
        print("Terminating viewer...")
        if viewer.top is not None:
            viewer.top.close()
示例#9
0
def main(options, args):

    logger = log.get_logger("example2", options=options)

    if options.toolkit is None:
        logger.error("Please choose a GUI toolkit with -t option")

    # decide our toolkit, then import
    ginga_toolkit.use(options.toolkit)

    if options.use_opencv:
        from ginga import trcalc
        try:
            trcalc.use('opencv')
        except Exception as e:
            logger.warning("Error using OpenCv: %s" % str(e))

    if options.use_opencl:
        from ginga import trcalc
        try:
            trcalc.use('opencl')
        except Exception as e:
            logger.warning("Error using OpenCL: %s" % str(e))

    viewer = FitsViewer(logger)

    if options.renderer is not None:
        render_class = render.get_render_class(options.renderer)
        viewer.fitsimage.set_renderer(render_class(viewer.fitsimage))

    viewer.top.resize(700, 540)

    if len(args) > 0:
        viewer.load_file(args[0])

    viewer.top.show()
    viewer.top.raise_()

    try:
        app = viewer.top.get_app()
        app.mainloop()

    except KeyboardInterrupt:
        print("Terminating viewer...")
        if viewer.top is not None:
            viewer.top.close()
示例#10
0
        self._plot_target(observer, target, time_start, color)
        self.redraw()

    def plot_targets(self, observer, targets, time_start, colors):
        i = 0
        for target in targets:
            self._plot_target(observer, target, time_start, colors[i])
            i = (i+1) % len(colors)
        self.redraw()

if __name__ == '__main__':
    import entity, common
    import pytz

    from ginga import toolkit
    toolkit.use('qt')

    from ginga.gw import Widgets, Plot

    plot = AZELPlot(1000, 1000)
    plot.setup()

    app = Widgets.Application()
    topw = app.make_window()
    plotw = Plot.PlotWidget(plot)
    topw.set_widget(plotw)
    topw.add_callback('close', lambda w: w.delete())
    topw.show()

    plot.plot_azel([(-210.0, 60.43, "telescope"),])
    tgt3 = entity.StaticTarget(name="Bootes", ra="14:31:45.40",
示例#11
0
    def main(self, options, args):
        """
        Main routine for running the reference viewer.

        `options` is a OptionParser object that has been populated with
        values from parsing the command line.  It should at least include
        the options from add_default_options()

        `args` is a list of arguments to the viewer after parsing out
        options.  It should contain a list of files or URLs to load.
        """

        # Create a logger
        logger = log.get_logger(name='ginga', options=options)

        # Get settings (preferences)
        basedir = paths.ginga_home
        if not os.path.exists(basedir):
            try:
                os.mkdir(basedir)
            except OSError as e:
                logger.warning("Couldn't create ginga settings area (%s): %s" %
                               (basedir, str(e)))
                logger.warning("Preferences will not be able to be saved")

        # Set up preferences
        prefs = Settings.Preferences(basefolder=basedir, logger=logger)
        settings = prefs.create_category('general')
        settings.set_defaults(useMatplotlibColormaps=False,
                              widgetSet='choose',
                              WCSpkg='choose',
                              FITSpkg='choose',
                              recursion_limit=2000,
                              icc_working_profile=None,
                              font_scaling_factor=None,
                              save_layout=True,
                              channel_prefix="Image")
        settings.load(onError='silent')

        # default of 1000 is a little too small
        sys.setrecursionlimit(settings.get('recursion_limit'))

        # So we can find our plugins
        sys.path.insert(0, basedir)
        package_home = os.path.split(sys.modules['ginga.version'].__file__)[0]
        child_dir = os.path.join(package_home, 'rv', 'plugins')
        sys.path.insert(0, child_dir)
        plugin_dir = os.path.join(basedir, 'plugins')
        sys.path.insert(0, plugin_dir)

        gc = os.path.join(basedir, "ginga_config.py")
        have_ginga_config = os.path.exists(gc)

        # User configuration, earliest possible intervention
        if have_ginga_config:
            try:
                import ginga_config

                if hasattr(ginga_config, 'init_config'):
                    ginga_config.init_config(self)

            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error processing Ginga config file: %s" %
                             (str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Choose a toolkit
        if options.toolkit:
            toolkit = options.toolkit
        else:
            toolkit = settings.get('widgetSet', 'choose')

        if toolkit == 'choose':
            try:
                ginga_toolkit.choose()
            except ImportError as e:
                print("UI toolkit choose error: %s" % str(e))
                sys.exit(1)
        else:
            ginga_toolkit.use(toolkit)

        tkname = ginga_toolkit.get_family()
        logger.info("Chosen toolkit (%s) family is '%s'" %
                    (ginga_toolkit.toolkit, tkname))

        # these imports have to be here, otherwise they force the choice
        # of toolkit too early
        from ginga.rv.Control import GingaShell, GuiLogHandler

        if settings.get('useMatplotlibColormaps', False):
            # Add matplotlib color maps if matplotlib is installed
            try:
                from ginga import cmap
                cmap.add_matplotlib_cmaps(fail_on_import_error=False)
            except Exception as e:
                logger.warning("failed to load matplotlib colormaps: %s" %
                               (str(e)))

        # Set a working RGB ICC profile if user has one
        working_profile = settings.get('icc_working_profile', None)
        rgb_cms.working_profile = working_profile

        # User wants to customize the WCS package?
        if options.wcspkg:
            wcspkg = options.wcspkg
        else:
            wcspkg = settings.get('WCSpkg', 'choose')

        try:
            from ginga.util import wcsmod
            if wcspkg != 'choose':
                assert wcsmod.use(wcspkg) is True
        except Exception as e:
            logger.warning("failed to set WCS package preference: %s" %
                           (str(e)))

        # User wants to customize the FITS package?
        if options.fitspkg:
            fitspkg = options.fitspkg
        else:
            fitspkg = settings.get('FITSpkg', 'choose')

        try:
            from ginga.util import io_fits, loader
            if fitspkg != 'choose':
                assert io_fits.use(fitspkg) is True
                # opener name is not necessarily the same
                opener = loader.get_opener(io_fits.fitsLoaderClass.name)
                # set this opener as the priority one
                opener.priority = -99

        except Exception as e:
            logger.warning("failed to set FITS package preference: %s" %
                           (str(e)))

        # Check whether user wants to use OpenCv
        use_opencv = settings.get('use_opencv', False)
        if use_opencv or options.opencv:
            from ginga import trcalc
            try:
                trcalc.use('opencv')
            except Exception as e:
                logger.warning("failed to set OpenCv preference: %s" %
                               (str(e)))

        # Check whether user wants to use OpenCL
        use_opencl = settings.get('use_opencl', False)
        if use_opencl or options.opencl:
            from ginga import trcalc
            try:
                trcalc.use('opencl')
            except Exception as e:
                logger.warning("failed to set OpenCL preference: %s" %
                               (str(e)))

        # Create the dynamic module manager
        mm = ModuleManager.ModuleManager(logger)

        # Create and start thread pool
        ev_quit = threading.Event()
        thread_pool = Task.ThreadPool(options.numthreads,
                                      logger,
                                      ev_quit=ev_quit)
        thread_pool.startall()

        # Create the Ginga main object
        ginga_shell = GingaShell(logger,
                                 thread_pool,
                                 mm,
                                 prefs,
                                 ev_quit=ev_quit)

        # user wants to set font scaling.
        # NOTE: this happens *after* creation of shell object, since
        # Application object constructor will also set this
        font_scaling = settings.get('font_scaling_factor', None)
        if font_scaling is not None:
            logger.debug(
                "overriding font_scaling_factor to {}".format(font_scaling))
            from ginga.fonts import font_asst
            font_asst.default_scaling_factor = font_scaling

        layout_file = None
        if not options.norestore and settings.get('save_layout', False):
            layout_file = os.path.join(basedir, 'layout')

        ginga_shell.set_layout(self.layout, layout_file=layout_file)

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                if hasattr(ginga_config, 'pre_gui_config'):
                    ginga_config.pre_gui_config(ginga_shell)
            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error importing Ginga config file: %s" %
                             (str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Build desired layout
        ginga_shell.build_toplevel()

        # Did user specify a particular geometry?
        if options.geometry:
            ginga_shell.set_geometry(options.geometry)

        # make the list of disabled plugins
        if options.disable_plugins is not None:
            disabled_plugins = options.disable_plugins.lower().split(',')
        else:
            disabled_plugins = settings.get('disable_plugins', [])
            if not isinstance(disabled_plugins, list):
                disabled_plugins = disabled_plugins.lower().split(',')

        # Add GUI log handler (for "Log" global plugin)
        guiHdlr = GuiLogHandler(ginga_shell)
        guiHdlr.setLevel(options.loglevel)
        fmt = logging.Formatter(log.LOG_FORMAT)
        guiHdlr.setFormatter(fmt)
        logger.addHandler(guiHdlr)

        # Load any custom modules
        if options.modules is not None:
            modules = options.modules.split(',')
        else:
            modules = settings.get('global_plugins', [])
            if not isinstance(modules, list):
                modules = modules.split(',')

        for long_plugin_name in modules:
            if '.' in long_plugin_name:
                tmpstr = long_plugin_name.split('.')
                plugin_name = tmpstr[-1]
                pfx = '.'.join(tmpstr[:-1])
            else:
                plugin_name = long_plugin_name
                pfx = None
            menu_name = "%s [G]" % (plugin_name)
            spec = Bunch(name=plugin_name,
                         module=plugin_name,
                         ptype='global',
                         tab=plugin_name,
                         menu=menu_name,
                         category="Custom",
                         workspace='right',
                         pfx=pfx)
            self.add_plugin_spec(spec)

        # Load any custom local plugins
        if options.plugins is not None:
            plugins = options.plugins.split(',')
        else:
            plugins = settings.get('local_plugins', [])
            if not isinstance(plugins, list):
                plugins = plugins.split(',')

        for long_plugin_name in plugins:
            if '.' in long_plugin_name:
                tmpstr = long_plugin_name.split('.')
                plugin_name = tmpstr[-1]
                pfx = '.'.join(tmpstr[:-1])
            else:
                plugin_name = long_plugin_name
                pfx = None
            spec = Bunch(module=plugin_name,
                         workspace='dialogs',
                         ptype='local',
                         category="Custom",
                         hidden=False,
                         pfx=pfx)
            self.add_plugin_spec(spec)

        # Add non-disabled plugins
        enabled_plugins = [
            spec for spec in self.plugins
            if spec.module.lower() not in disabled_plugins
        ]
        ginga_shell.set_plugins(enabled_plugins)

        # start any plugins that have start=True
        ginga_shell.boot_plugins()
        ginga_shell.update_pending()

        # TEMP?
        tab_names = [
            name.lower() for name in ginga_shell.ds.get_tabnames(group=None)
        ]
        if 'info' in tab_names:
            ginga_shell.ds.raise_tab('Info')
        if 'synopsis' in tab_names:
            ginga_shell.ds.raise_tab('Synopsis')
        if 'thumbs' in tab_names:
            ginga_shell.ds.raise_tab('Thumbs')

        # Add custom channels
        if options.channels is not None:
            channels = options.channels.split(',')
        else:
            channels = settings.get('channels', self.channels)
            if not isinstance(channels, list):
                channels = channels.split(',')

        if len(channels) == 0:
            # should provide at least one default channel?
            channels = [settings.get('channel_prefix', "Image")]

        # populate the initial channel lineup
        for item in channels:
            if isinstance(item, str):
                chname, wsname = item, None
            else:
                chname, wsname = item
            ginga_shell.add_channel(chname, workspace=wsname)

        ginga_shell.change_channel(chname)

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                if hasattr(ginga_config, 'post_gui_config'):
                    ginga_config.post_gui_config(ginga_shell)

            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error processing Ginga config file: %s" %
                             (str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Redirect warnings to logger
        for hdlr in logger.handlers:
            logging.getLogger('py.warnings').addHandler(hdlr)

        # Display banner the first time run, unless suppressed
        show_banner = True
        try:
            show_banner = settings.get('showBanner')

        except KeyError:
            # disable for subsequent runs
            settings.set(showBanner=False)
            if not os.path.exists(settings.preffile):
                settings.save()

        if (not options.nosplash) and (len(args) == 0) and show_banner:
            ginga_shell.banner(raiseTab=True)

        # Handle inputs like "*.fits[ext]" that sys cmd cannot auto expand.
        expanded_args = []
        for imgfile in args:
            if '*' in imgfile:
                if '[' in imgfile and imgfile.endswith(']'):
                    s = imgfile.split('[')
                    ext = '[' + s[1]
                    imgfile = s[0]
                else:
                    ext = ''
                for fname in glob.iglob(imgfile):
                    expanded_args.append(fname + ext)
            else:
                expanded_args.append(imgfile)

        # Assume remaining arguments are fits files and load them.
        if not options.separate_channels:
            chname = channels[0]
            ginga_shell.gui_do(ginga_shell.open_uris,
                               expanded_args,
                               chname=chname)
        else:
            i = 0
            num_channels = len(channels)
            for imgfile in expanded_args:
                if i < num_channels:
                    chname = channels[i]
                    i = i + 1
                else:
                    channel = ginga_shell.add_channel_auto()
                    chname = channel.name
                ginga_shell.gui_do(ginga_shell.open_uris, [imgfile],
                                   chname=chname)

        try:
            try:
                # if there is a network component, start it
                if hasattr(ginga_shell, 'start'):
                    logger.info("starting network interface...")
                    task = Task.FuncTask2(ginga_shell.start)
                    thread_pool.addTask(task)

                # Main loop to handle GUI events
                logger.info("entering mainloop...")
                ginga_shell.mainloop(timeout=0.001)

            except KeyboardInterrupt:
                logger.error("Received keyboard interrupt!")

        finally:
            logger.info("Shutting down...")
            ev_quit.set()

        sys.exit(0)
示例#12
0
"""
Example of 3D plotting in Ginga

Plots an octahedron within a wireframe sphere.

Run with no parameters.  Scroll to zoom in/out, click and drag to orbit.

Requirements: Qt5, OpenGL, numpy
"""

import sys

import numpy as np

from ginga import toolkit
toolkit.use('qt5')

from ginga.gw import Widgets  # noqa
from ginga.opengl.ImageViewQtGL import CanvasView  # noqa
from ginga.canvas.CanvasObject import get_canvas_types  # noqa
from ginga.misc import log  # noqa


class Viewer(object):

    def __init__(self, app):
        super(Viewer, self).__init__()
        self.logger = app.logger
        self.dc = get_canvas_types()

        self.top = app.make_window(title="Simple Ginga 3D Viewer")
示例#13
0
    def main(self, options, args):
        """
        Main routine for running the reference viewer.

        `options` is a OptionParser object that has been populated with
        values from parsing the command line.  It should at least include
        the options from add_default_options()

        `args` is a list of arguments to the viewer after parsing out
        options.  It should contain a list of files or URLs to load.
        """

        # Create a logger
        logger = log.get_logger(name='ginga', options=options)

        # Get settings (preferences)
        basedir = paths.ginga_home
        if not os.path.exists(basedir):
            try:
                os.mkdir(basedir)
            except OSError as e:
                logger.warn("Couldn't create ginga settings area (%s): %s" %
                            (basedir, str(e)))
                logger.warn("Preferences will not be able to be saved")

        # Set up preferences
        prefs = Settings.Preferences(basefolder=basedir, logger=logger)
        settings = prefs.createCategory('general')
        settings.load(onError='silent')
        settings.setDefaults(useMatplotlibColormaps=False,
                             widgetSet='choose',
                             WCSpkg='choose',
                             FITSpkg='choose',
                             recursion_limit=2000)

        # default of 1000 is a little too small
        sys.setrecursionlimit(settings.get('recursion_limit'))

        # So we can find our plugins
        sys.path.insert(0, basedir)
        moduleHome = os.path.split(sys.modules['ginga.version'].__file__)[0]
        childDir = os.path.join(moduleHome, 'misc', 'plugins')
        sys.path.insert(0, childDir)
        pluginDir = os.path.join(basedir, 'plugins')
        sys.path.insert(0, pluginDir)

        # Choose a toolkit
        if options.toolkit:
            toolkit = options.toolkit
        else:
            toolkit = settings.get('widgetSet', 'choose')

        if toolkit == 'choose':
            try:
                from ginga.qtw import QtHelp
            except ImportError:
                try:
                    from ginga.gtkw import GtkHelp
                except ImportError:
                    print("You need python-gtk or python-qt to run Ginga!")
                    sys.exit(1)
        else:
            ginga_toolkit.use(toolkit)

        tkname = ginga_toolkit.get_family()
        logger.info("Chosen toolkit (%s) family is '%s'" %
                    (ginga_toolkit.toolkit, tkname))

        # these imports have to be here, otherwise they force the choice
        # of toolkit too early
        from ginga.gw.GingaGw import GingaView
        from ginga.Control import GingaControl, GuiLogHandler

        # Define class dynamically based on toolkit choice
        class GingaShell(GingaControl, GingaView):
            def __init__(self,
                         logger,
                         thread_pool,
                         module_manager,
                         prefs,
                         ev_quit=None):
                GingaView.__init__(self, logger, ev_quit, thread_pool)
                GingaControl.__init__(self,
                                      logger,
                                      thread_pool,
                                      module_manager,
                                      prefs,
                                      ev_quit=ev_quit)

        if settings.get('useMatplotlibColormaps', False):
            # Add matplotlib color maps if matplotlib is installed
            try:
                from ginga import cmap
                cmap.add_matplotlib_cmaps()
            except Exception as e:
                logger.warn("failed to load matplotlib colormaps: %s" %
                            (str(e)))

        # User wants to customize the WCS package?
        if options.wcspkg:
            wcspkg = options.wcspkg
        else:
            wcspkg = settings.get('WCSpkg', 'choose')

        try:
            from ginga.util import wcsmod
            assert wcsmod.use(wcspkg) == True
        except Exception as e:
            logger.warn("failed to set WCS package preference: %s" % (str(e)))

        # User wants to customize the FITS package?
        if options.fitspkg:
            fitspkg = options.fitspkg
        else:
            fitspkg = settings.get('FITSpkg', 'choose')

        try:
            from ginga.util import io_fits
            assert io_fits.use(fitspkg) == True
        except Exception as e:
            logger.warn("failed to set FITS package preference: %s" % (str(e)))

        # Check whether user wants to use OpenCv
        use_opencv = settings.get('use_opencv', False)
        if use_opencv or options.opencv:
            from ginga import trcalc
            try:
                trcalc.use('opencv')
            except Exception as e:
                logger.warn("failed to set OpenCv preference: %s" % (str(e)))

        # Create the dynamic module manager
        mm = ModuleManager.ModuleManager(logger)

        # Create and start thread pool
        ev_quit = threading.Event()
        thread_pool = Task.ThreadPool(options.numthreads,
                                      logger,
                                      ev_quit=ev_quit)
        thread_pool.startall()

        # Create the Ginga main object
        ginga_shell = GingaShell(logger,
                                 thread_pool,
                                 mm,
                                 prefs,
                                 ev_quit=ev_quit)
        ginga_shell.set_layout(self.layout)

        gc = os.path.join(basedir, "ginga_config.py")
        have_ginga_config = os.path.exists(gc)

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                import ginga_config

                ginga_config.pre_gui_config(ginga_shell)
            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error importing Ginga config file: %s" %
                             (str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Build desired layout
        ginga_shell.build_toplevel()

        # Did user specify a particular geometry?
        if options.geometry:
            ginga_shell.set_geometry(options.geometry)

        # make the list of disabled plugins
        disabled_plugins = []
        if not (options.disable_plugins is None):
            disabled_plugins = options.disable_plugins.lower().split(',')

        # Add desired global plugins
        for spec in self.global_plugins:
            if not spec.module.lower() in disabled_plugins:
                ginga_shell.add_global_plugin(spec)

        # Add GUI log handler (for "Log" global plugin)
        guiHdlr = GuiLogHandler(ginga_shell)
        guiHdlr.setLevel(options.loglevel)
        fmt = logging.Formatter(log.LOG_FORMAT)
        guiHdlr.setFormatter(fmt)
        logger.addHandler(guiHdlr)

        # Load any custom modules
        if options.modules:
            modules = options.modules.split(',')
            for longPluginName in modules:
                if '.' in longPluginName:
                    tmpstr = longPluginName.split('.')
                    pluginName = tmpstr[-1]
                    pfx = '.'.join(tmpstr[:-1])
                else:
                    pluginName = longPluginName
                    pfx = None
                spec = Bunch(name=pluginName,
                             module=pluginName,
                             tab=pluginName,
                             ws='right',
                             pfx=pfx)
                ginga_shell.add_global_plugin(spec)

        # Load modules for "local" (per-channel) plug ins
        for spec in self.local_plugins:
            if not spec.module.lower() in disabled_plugins:
                ginga_shell.add_local_plugin(spec)

        # Load any custom plugins
        if options.plugins:
            plugins = options.plugins.split(',')
            for longPluginName in plugins:
                if '.' in longPluginName:
                    tmpstr = longPluginName.split('.')
                    pluginName = tmpstr[-1]
                    pfx = '.'.join(tmpstr[:-1])
                else:
                    pluginName = longPluginName
                    pfx = None
                spec = Bunch(module=pluginName,
                             ws='dialogs',
                             hidden=False,
                             pfx=pfx)
                ginga_shell.add_local_plugin(spec)

        ginga_shell.update_pending()

        # TEMP?
        tab_names = list(
            map(lambda name: name.lower(),
                ginga_shell.ds.get_tabnames(group=None)))
        if 'info' in tab_names:
            ginga_shell.ds.raise_tab('Info')
        if 'thumbs' in tab_names:
            ginga_shell.ds.raise_tab('Thumbs')

        # Add custom channels
        channels = options.channels.split(',')
        for chname in channels:
            ginga_shell.add_channel(chname)
        ginga_shell.change_channel(channels[0])

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                ginga_config.post_gui_config(ginga_shell)
            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error processing Ginga config file: %s" %
                             (str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Redirect warnings to logger
        for hdlr in logger.handlers:
            logging.getLogger('py.warnings').addHandler(hdlr)

        # Display banner the first time run, unless suppressed
        showBanner = True
        try:
            showBanner = settings.get('showBanner')

        except KeyError:
            # disable for subsequent runs
            settings.set(showBanner=False)
            settings.save()

        if (not options.nosplash) and (len(args) == 0) and showBanner:
            ginga_shell.banner(raiseTab=True)

        # Assume remaining arguments are fits files and load them.
        for imgfile in args:
            ginga_shell.nongui_do(ginga_shell.load_file, imgfile)

        try:
            try:
                # if there is a network component, start it
                if hasattr(ginga_shell, 'start'):
                    task = Task.FuncTask2(ginga_shell.start)
                    thread_pool.addTask(task)

                # Main loop to handle GUI events
                logger.info("Entering mainloop...")
                ginga_shell.mainloop(timeout=0.001)

            except KeyboardInterrupt:
                logger.error("Received keyboard interrupt!")

        finally:
            logger.info("Shutting down...")
            ev_quit.set()

        sys.exit(0)
示例#14
0
def main(options, args):

    # default of 1000 is a little too small
    sys.setrecursionlimit(2000)

    # Create a logger
    logger = log.get_logger(name='ginga', options=options)

    # Get settings (preferences)
    basedir = paths.ginga_home
    if not os.path.exists(basedir):
        try:
            os.mkdir(basedir)
        except OSError as e:
            logger.warn("Couldn't create ginga settings area (%s): %s" %
                        (basedir, str(e)))
            logger.warn("Preferences will not be able to be saved")

    # Set up preferences
    prefs = Settings.Preferences(basefolder=basedir, logger=logger)
    settings = prefs.createCategory('general')
    settings.load(onError='silent')
    settings.setDefaults(useMatplotlibColormaps=False,
                         widgetSet='choose',
                         WCSpkg='choose',
                         FITSpkg='choose')

    # So we can find our plugins
    sys.path.insert(0, basedir)
    moduleHome = os.path.split(sys.modules['ginga.version'].__file__)[0]
    childDir = os.path.join(moduleHome, 'misc', 'plugins')
    sys.path.insert(0, childDir)
    pluginDir = os.path.join(basedir, 'plugins')
    sys.path.insert(0, pluginDir)

    # Choose a toolkit
    if options.toolkit:
        toolkit = options.toolkit
    else:
        toolkit = settings.get('widgetSet', 'choose')

    ginga_toolkit.use(toolkit)
    tkname = ginga_toolkit.get_family()

    if tkname == 'gtk':
        from ginga.gtkw.GingaGtk import GingaView
    elif tkname == 'qt':
        from ginga.qtw.GingaQt import GingaView
    else:
        try:
            from ginga.qtw.GingaQt import GingaView
        except ImportError:
            try:
                from ginga.gtkw.GingaGtk import GingaView
            except ImportError:
                print("You need python-gtk or python-qt4 to run Ginga!")
                sys.exit(1)

    # Define class dynamically based on toolkit choice
    class Ginga(GingaControl, GingaView):
        def __init__(self,
                     logger,
                     threadPool,
                     module_manager,
                     prefs,
                     ev_quit=None):
            GingaView.__init__(self, logger, ev_quit)
            GingaControl.__init__(self,
                                  logger,
                                  threadPool,
                                  module_manager,
                                  prefs,
                                  ev_quit=ev_quit)

    if settings.get('useMatplotlibColormaps', False):
        # Add matplotlib color maps if matplotlib is installed
        try:
            from ginga import cmap
            cmap.add_matplotlib_cmaps()
        except Exception as e:
            logger.warn("failed to load matplotlib colormaps: %s" % (str(e)))

    # User wants to customize the WCS package?
    if options.wcs:
        wcspkg = options.wcs
    else:
        wcspkg = settings.get('WCSpkg', 'choose')

    try:
        from ginga.util import wcsmod
        assert wcsmod.use(wcspkg) == True
    except Exception as e:
        logger.warn("failed to set WCS package preference: %s" % (str(e)))

    # User wants to customize the FITS package?
    if options.fits:
        fitspkg = options.fits
    else:
        fitspkg = settings.get('FITSpkg', 'choose')

    try:
        from ginga.util import io_fits
        assert io_fits.use(fitspkg) == True
    except Exception as e:
        logger.warn("failed to set FITS package preference: %s" % (str(e)))

    # Create the dynamic module manager
    mm = ModuleManager.ModuleManager(logger)

    # Create and start thread pool
    ev_quit = threading.Event()
    threadPool = Task.ThreadPool(options.numthreads, logger, ev_quit=ev_quit)
    threadPool.startall()

    # Create the Ginga main object
    ginga = Ginga(logger, threadPool, mm, prefs, ev_quit=ev_quit)
    ginga.set_layout(default_layout)

    # User configuration (custom star catalogs, etc.)
    try:
        import ginga_config

        ginga_config.pre_gui_config(ginga)
    except Exception as e:
        try:
            (type, value, tb) = sys.exc_info()
            tb_str = "\n".join(traceback.format_tb(tb))

        except Exception:
            tb_str = "Traceback information unavailable."

        logger.error("Error importing Ginga config file: %s" % (str(e)))
        logger.error("Traceback:\n%s" % (tb_str))

    # Build desired layout
    ginga.build_toplevel()

    # Did user specify a particular geometry?
    if options.geometry:
        ginga.setGeometry(options.geometry)

    # Add desired global plugins
    for spec in global_plugins:
        ginga.add_global_plugin(spec)

    # Add GUI log handler (for "Log" global plugin)
    guiHdlr = GuiLogHandler(ginga)
    guiHdlr.setLevel(options.loglevel)
    fmt = logging.Formatter(log.LOG_FORMAT)
    guiHdlr.setFormatter(fmt)
    logger.addHandler(guiHdlr)

    # Load any custom modules
    if options.modules:
        modules = options.modules.split(',')
        for pluginName in modules:
            spec = Bunch(name=pluginName,
                         module=pluginName,
                         tab=pluginName,
                         ws='right')
            ginga.add_global_plugin(spec)

    # Load modules for "local" (per-channel) plug ins
    for spec in local_plugins:
        ginga.add_local_plugin(spec)

    # Load any custom plugins
    if options.plugins:
        plugins = options.plugins.split(',')
        for pluginName in plugins:
            spec = Bunch(module=pluginName, ws='dialogs', hidden=False)
            ginga.add_local_plugin(spec)

    ginga.update_pending()

    # TEMP?
    ginga.ds.raise_tab('Info')
    ginga.ds.raise_tab('Thumbs')

    # Add custom channels
    channels = options.channels.split(',')
    for chname in channels:
        datasrc = Datasrc.Datasrc(length=options.bufsize)
        ginga.add_channel(chname, datasrc)
    ginga.change_channel(channels[0])

    # User configuration (custom star catalogs, etc.)
    try:
        ginga_config.post_gui_config(ginga)
    except Exception as e:
        try:
            (type, value, tb) = sys.exc_info()
            tb_str = "\n".join(traceback.format_tb(tb))

        except Exception:
            tb_str = "Traceback information unavailable."

        logger.error("Error processing Ginga config file: %s" % (str(e)))
        logger.error("Traceback:\n%s" % (tb_str))

    # Display banner the first time run, unless suppressed
    showBanner = True
    try:
        showBanner = settings.get('showBanner')

    except KeyError:
        # disable for subsequent runs
        settings.set(showBanner=False)
        settings.save()

    if (not options.nosplash) and (len(args) == 0) and showBanner:
        ginga.banner()

    # Assume remaining arguments are fits files and load them.
    for imgfile in args:
        ginga.nongui_do(ginga.load_file, imgfile)

    try:
        try:
            # Main loop to handle GUI events
            logger.info("Entering mainloop...")
            ginga.mainloop(timeout=0.001)

        except KeyboardInterrupt:
            logger.error("Received keyboard interrupt!")

    finally:
        logger.info("Shutting down...")
        ev_quit.set()

    sys.exit(0)
示例#15
0
文件: main.py 项目: jkunimune15/qplan
    def main(self, options, args):
        # Create top level logger.
        svcname = 'qplan'
        logger = log.get_logger(name=svcname, options=options)

        ev_quit = threading.Event()

        thread_pool = Task.ThreadPool(logger=logger, ev_quit=ev_quit,
                                     numthreads=options.numthreads)

        ginga_toolkit.use(options.toolkit)

        from qplan.View import Viewer
        # must import AFTER Viewer
        from ginga.Control import GuiLogHandler

        class QueuePlanner(Controller, Viewer):

            def __init__(self, logger, thread_pool, module_manager, preferences,
                         ev_quit, model):

                Viewer.__init__(self, logger, ev_quit)
                Controller.__init__(self, logger, thread_pool, module_manager,
                                    preferences, ev_quit, model)

        # Get settings folder
        ## if os.environ.has_key('CONFHOME'):
        ##     basedir = os.path.join(os.environ['CONFHOME'], svcname)
        ## else:
        basedir = os.path.join(os.environ['HOME'], '.' + svcname)
        if not os.path.exists(basedir):
            os.mkdir(basedir)
        prefs = Settings.Preferences(basefolder=basedir, logger=logger)

        mm = ModuleManager.ModuleManager(logger)

        ## # Add any custom modules
        ## if options.modules:
        ##     modules = options.modules.split(',')
        ##     for mdlname in modules:
        ##         #self.mm.loadModule(name, pfx=pluginconfpfx)
        ##         self.mm.loadModule(name)

        model = QueueModel(logger=logger)

        if options.completed is not None:
            # specify a list of completed OB keys
            with open(options.completed, 'r') as in_f:
                buf = in_f.read()
            import ast
            model.completed_keys = ast.literal_eval(buf)

        # Start up the control/display engine
        qplanner = QueuePlanner(logger, thread_pool, mm, prefs, ev_quit, model)
        qplanner.set_input_dir(options.input_dir)
        qplanner.set_input_fmt(options.input_fmt)

        # Build desired layout
        qplanner.build_toplevel(default_layout)
        for w in qplanner.ds.toplevels:
            w.show()

        # load plugins
        for pluginName, moduleName, className, wsName, tabName in self.plugins:
            qplanner.load_plugin(pluginName, moduleName, className,
                                 wsName, tabName)

        guiHdlr = GuiLogHandler(qplanner)
        #guiHdlr.setLevel(options.loglevel)
        guiHdlr.setLevel(logging.INFO)
        fmt = logging.Formatter(log.LOG_FORMAT)
        guiHdlr.setFormatter(fmt)
        logger.addHandler(guiHdlr)

        qplanner.update_pending()

        # Did user specify geometry
        if options.geometry:
            qplanner.set_geometry(options.geometry)

        # Raise window
        w = qplanner.w.root
        w.show()

        server_started = False

        # Create threadpool and start it
        try:
            # Startup monitor threadpool
            thread_pool.startall(wait=True)

            try:
                # if there is a network component, start it
                if hasattr(qplanner, 'start'):
                    task = Task.FuncTask2(qplanner.start)
                    thread_pool.addTask(task)

                # Main loop to handle GUI events
                qplanner.mainloop(timeout=0.001)

            except KeyboardInterrupt:
                logger.error("Received keyboard interrupt!")

        finally:
            logger.info("Shutting down...")
            thread_pool.stopall(wait=True)

        sys.exit(0)
示例#16
0
from __future__ import absolute_import, division, print_function

import sys
import os.path

import numpy as np
from ginga.misc import log
from ginga import toolkit
try:
    toolkit.use('qt')
    from ginga.gw import ColorBar
except ImportError:
    # older versions of ginga
    from ginga.qtw import ColorBar
from ginga import cmap as ginga_cmap
from ginga.qtw.ImageViewCanvasQt import ImageViewCanvas

from qtpy.QtCore import Qt
from qtpy import QtCore, QtWidgets, QtGui
from glue.core.callback_property import add_callback
from glue.core import roi as roimod
from glue.config import tool_registry
from glue.plugins.ginga_viewer.qt.client import GingaClient
from glue.plugins.tools.spectrum_tool.qt import SpectrumTool
from glue.icons.qt import get_icon
from glue.viewers.image.qt import ImageWidgetBase
from glue.utils import nonpartial

from glue.plugins.tools.pv_slicer.qt import PVSlicerTool

try:
示例#17
0
Examples:
  $ python widgets.py qt5 gridbox
  $ python widgets.py gtk3 label
  $ python widgets.py pg button
"""
import sys
import os

from ginga.misc import log
import ginga.toolkit as ginga_toolkit

# decide our toolkit, then import
tkit = sys.argv[1]
wname = sys.argv[2]

ginga_toolkit.use(tkit)
from ginga.gw import Widgets, Viewers, GwHelp  # noqa
from ginga.util.paths import icondir  # noqa

top = None


def quit(*args):
    if top is not None:
        top.delete()
    sys.exit()


def popup_dialog(parent):
    dia = Widgets.Dialog(title="Dialog Title",
                         buttons=[('ok', 0), ('cancel', 1)],
示例#18
0
    def main(self, options, args):
        """
        Main routine for running the reference viewer.

        `options` is a OptionParser object that has been populated with
        values from parsing the command line.  It should at least include
        the options from add_default_options()

        `args` is a list of arguments to the viewer after parsing out
        options.  It should contain a list of files or URLs to load.
        """

        # Create a logger
        logger = log.get_logger(name='ginga', options=options)

        # Get settings (preferences)
        basedir = paths.ginga_home
        if not os.path.exists(basedir):
            try:
                os.mkdir(basedir)
            except OSError as e:
                logger.warning(
                    "Couldn't create ginga settings area (%s): %s" % (
                        basedir, str(e)))
                logger.warning("Preferences will not be able to be saved")

        # Set up preferences
        prefs = Settings.Preferences(basefolder=basedir, logger=logger)
        settings = prefs.create_category('general')
        settings.set_defaults(useMatplotlibColormaps=False,
                              widgetSet='choose',
                              WCSpkg='choose', FITSpkg='choose',
                              recursion_limit=2000,
                              icc_working_profile=None,
                              font_scaling_factor=None,
                              save_layout=True,
                              channel_prefix="Image")
        settings.load(onError='silent')

        # default of 1000 is a little too small
        sys.setrecursionlimit(settings.get('recursion_limit'))

        # So we can find our plugins
        sys.path.insert(0, basedir)
        package_home = os.path.split(sys.modules['ginga.version'].__file__)[0]
        child_dir = os.path.join(package_home, 'rv', 'plugins')
        sys.path.insert(0, child_dir)
        plugin_dir = os.path.join(basedir, 'plugins')
        sys.path.insert(0, plugin_dir)

        gc = os.path.join(basedir, "ginga_config.py")
        have_ginga_config = os.path.exists(gc)

        # User configuration, earliest possible intervention
        if have_ginga_config:
            try:
                import ginga_config

                if hasattr(ginga_config, 'init_config'):
                    ginga_config.init_config(self)

            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error processing Ginga config file: %s" % (
                    str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Choose a toolkit
        if options.toolkit:
            toolkit = options.toolkit
        else:
            toolkit = settings.get('widgetSet', 'choose')

        if toolkit == 'choose':
            try:
                ginga_toolkit.choose()
            except ImportError as e:
                print("UI toolkit choose error: %s" % str(e))
                sys.exit(1)
        else:
            ginga_toolkit.use(toolkit)

        tkname = ginga_toolkit.get_family()
        logger.info("Chosen toolkit (%s) family is '%s'" % (
            ginga_toolkit.toolkit, tkname))

        # these imports have to be here, otherwise they force the choice
        # of toolkit too early
        from ginga.rv.Control import GingaShell, GuiLogHandler

        if settings.get('useMatplotlibColormaps', False):
            # Add matplotlib color maps if matplotlib is installed
            try:
                from ginga import cmap
                cmap.add_matplotlib_cmaps(fail_on_import_error=False)
            except Exception as e:
                logger.warning(
                    "failed to load matplotlib colormaps: %s" % (str(e)))

        # user wants to set font scaling
        font_scaling = settings.get('font_scaling_factor', None)
        if font_scaling is not None:
            from ginga.fonts import font_asst
            font_asst.default_scaling_factor = font_scaling

        # Set a working RGB ICC profile if user has one
        working_profile = settings.get('icc_working_profile', None)
        rgb_cms.working_profile = working_profile

        # User wants to customize the WCS package?
        if options.wcspkg:
            wcspkg = options.wcspkg
        else:
            wcspkg = settings.get('WCSpkg', 'choose')

        try:
            from ginga.util import wcsmod
            if wcspkg != 'choose':
                assert wcsmod.use(wcspkg) is True
        except Exception as e:
            logger.warning(
                "failed to set WCS package preference: %s" % (str(e)))

        # User wants to customize the FITS package?
        if options.fitspkg:
            fitspkg = options.fitspkg
        else:
            fitspkg = settings.get('FITSpkg', 'choose')

        try:
            from ginga.util import io_fits
            if fitspkg != 'choose':
                assert io_fits.use(fitspkg) is True
        except Exception as e:
            logger.warning(
                "failed to set FITS package preference: %s" % (str(e)))

        # Check whether user wants to use OpenCv
        use_opencv = settings.get('use_opencv', False)
        if use_opencv or options.opencv:
            from ginga import trcalc
            try:
                trcalc.use('opencv')
            except Exception as e:
                logger.warning(
                    "failed to set OpenCv preference: %s" % (str(e)))

        # Check whether user wants to use OpenCL
        use_opencl = settings.get('use_opencl', False)
        if use_opencl or options.opencl:
            from ginga import trcalc
            try:
                trcalc.use('opencl')
            except Exception as e:
                logger.warning(
                    "failed to set OpenCL preference: %s" % (str(e)))

        # Create the dynamic module manager
        mm = ModuleManager.ModuleManager(logger)

        # Create and start thread pool
        ev_quit = threading.Event()
        thread_pool = Task.ThreadPool(options.numthreads, logger,
                                      ev_quit=ev_quit)
        thread_pool.startall()

        # Create the Ginga main object
        ginga_shell = GingaShell(logger, thread_pool, mm, prefs,
                                 ev_quit=ev_quit)

        layout_file = None
        if not options.norestore and settings.get('save_layout', False):
            layout_file = os.path.join(basedir, 'layout')

        ginga_shell.set_layout(self.layout, layout_file=layout_file)

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                if hasattr(ginga_config, 'pre_gui_config'):
                    ginga_config.pre_gui_config(ginga_shell)
            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error importing Ginga config file: %s" % (
                    str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Build desired layout
        ginga_shell.build_toplevel()

        # Did user specify a particular geometry?
        if options.geometry:
            ginga_shell.set_geometry(options.geometry)

        # make the list of disabled plugins
        if options.disable_plugins is not None:
            disabled_plugins = options.disable_plugins.lower().split(',')
        else:
            disabled_plugins = settings.get('disable_plugins', [])
            if not isinstance(disabled_plugins, list):
                disabled_plugins = disabled_plugins.lower().split(',')

        # Add GUI log handler (for "Log" global plugin)
        guiHdlr = GuiLogHandler(ginga_shell)
        guiHdlr.setLevel(options.loglevel)
        fmt = logging.Formatter(log.LOG_FORMAT)
        guiHdlr.setFormatter(fmt)
        logger.addHandler(guiHdlr)

        # Load any custom modules
        if options.modules is not None:
            modules = options.modules.split(',')
        else:
            modules = settings.get('global_plugins', [])
            if not isinstance(modules, list):
                modules = modules.split(',')

        for long_plugin_name in modules:
            if '.' in long_plugin_name:
                tmpstr = long_plugin_name.split('.')
                plugin_name = tmpstr[-1]
                pfx = '.'.join(tmpstr[:-1])
            else:
                plugin_name = long_plugin_name
                pfx = None
            menu_name = "%s [G]" % (plugin_name)
            spec = Bunch(name=plugin_name, module=plugin_name,
                         ptype='global', tab=plugin_name,
                         menu=menu_name, category="Custom",
                         workspace='right', pfx=pfx)
            self.add_plugin_spec(spec)

        # Load any custom local plugins
        if options.plugins is not None:
            plugins = options.plugins.split(',')
        else:
            plugins = settings.get('local_plugins', [])
            if not isinstance(plugins, list):
                plugins = plugins.split(',')

        for long_plugin_name in plugins:
            if '.' in long_plugin_name:
                tmpstr = long_plugin_name.split('.')
                plugin_name = tmpstr[-1]
                pfx = '.'.join(tmpstr[:-1])
            else:
                plugin_name = long_plugin_name
                pfx = None
            spec = Bunch(module=plugin_name, workspace='dialogs',
                         ptype='local', category="Custom",
                         hidden=False, pfx=pfx)
            self.add_plugin_spec(spec)

        # Add non-disabled plugins
        enabled_plugins = [spec for spec in self.plugins
                           if spec.module.lower() not in disabled_plugins]
        ginga_shell.set_plugins(enabled_plugins)

        # start any plugins that have start=True
        ginga_shell.boot_plugins()
        ginga_shell.update_pending()

        # TEMP?
        tab_names = [name.lower()
                     for name in ginga_shell.ds.get_tabnames(group=None)]
        if 'info' in tab_names:
            ginga_shell.ds.raise_tab('Info')
        if 'synopsis' in tab_names:
            ginga_shell.ds.raise_tab('Synopsis')
        if 'thumbs' in tab_names:
            ginga_shell.ds.raise_tab('Thumbs')

        # Add custom channels
        if options.channels is not None:
            channels = options.channels.split(',')
        else:
            channels = settings.get('channels', [])
            if not isinstance(channels, list):
                channels = channels.split(',')

        if len(channels) == 0:
            # should provide at least one default channel?
            channels = [settings.get('channel_prefix', "Image")]

        for chname in channels:
            ginga_shell.add_channel(chname)
        ginga_shell.change_channel(channels[0])

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                if hasattr(ginga_config, 'post_gui_config'):
                    ginga_config.post_gui_config(ginga_shell)

            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error processing Ginga config file: %s" % (
                    str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Redirect warnings to logger
        for hdlr in logger.handlers:
            logging.getLogger('py.warnings').addHandler(hdlr)

        # Display banner the first time run, unless suppressed
        showBanner = True
        try:
            showBanner = settings.get('showBanner')

        except KeyError:
            # disable for subsequent runs
            settings.set(showBanner=False)
            if not os.path.exists(settings.preffile):
                settings.save()

        if (not options.nosplash) and (len(args) == 0) and showBanner:
            ginga_shell.banner(raiseTab=True)

        # Handle inputs like "*.fits[ext]" that sys cmd cannot auto expand.
        expanded_args = []
        for imgfile in args:
            if '*' in imgfile:
                if '[' in imgfile and imgfile.endswith(']'):
                    s = imgfile.split('[')
                    ext = '[' + s[1]
                    imgfile = s[0]
                else:
                    ext = ''
                for fname in glob.iglob(imgfile):
                    expanded_args.append(fname + ext)
            else:
                expanded_args.append(imgfile)

        # Assume remaining arguments are fits files and load them.
        if not options.separate_channels:
            chname = channels[0]
            ginga_shell.gui_do(ginga_shell.open_uris, expanded_args,
                               chname=chname)
        else:
            i = 0
            num_channels = len(channels)
            for imgfile in expanded_args:
                if i < num_channels:
                    chname = channels[i]
                    i = i + 1
                else:
                    channel = ginga_shell.add_channel_auto()
                    chname = channel.name
                ginga_shell.gui_do(ginga_shell.open_uris, [imgfile],
                                   chname=chname)

        try:
            try:
                # if there is a network component, start it
                if hasattr(ginga_shell, 'start'):
                    task = Task.FuncTask2(ginga_shell.start)
                    thread_pool.addTask(task)

                # Main loop to handle GUI events
                logger.info("Entering mainloop...")
                ginga_shell.mainloop(timeout=0.001)

            except KeyboardInterrupt:
                logger.error("Received keyboard interrupt!")

        finally:
            logger.info("Shutting down...")
            ev_quit.set()

        sys.exit(0)
示例#19
0
文件: main.py 项目: jeanconn/ginga
def main(options, args):

    # default of 1000 is a little too small
    sys.setrecursionlimit(2000)
    
    # Create a logger
    logger = log.get_logger(name='ginga', options=options)

    # Get settings (preferences)
    basedir = paths.ginga_home
    if not os.path.exists(basedir):
        try:
            os.mkdir(basedir)
        except OSError as e:
            logger.warn("Couldn't create ginga settings area (%s): %s" % (
                basedir, str(e)))
            logger.warn("Preferences will not be able to be saved")

    # Set up preferences
    prefs = Settings.Preferences(basefolder=basedir, logger=logger)
    settings = prefs.createCategory('general')
    settings.load(onError='silent')
    settings.setDefaults(useMatplotlibColormaps=False,
                         widgetSet='choose',
                         WCSpkg='choose', FITSpkg='choose')

    # So we can find our plugins
    sys.path.insert(0, basedir)
    moduleHome = os.path.split(sys.modules['ginga.version'].__file__)[0]
    childDir = os.path.join(moduleHome, 'misc', 'plugins')
    sys.path.insert(0, childDir)
    pluginDir = os.path.join(basedir, 'plugins')
    sys.path.insert(0, pluginDir)

    # Choose a toolkit
    if options.toolkit:
        toolkit = options.toolkit
    else:
        toolkit = settings.get('widgetSet', 'choose')

    ginga_toolkit.use(toolkit)
    tkname = ginga_toolkit.get_family()
    
    if tkname == 'gtk':
        from ginga.gtkw.GingaGtk import GingaView
    elif tkname == 'qt':
        from ginga.qtw.GingaQt import GingaView
    else:
        try:
            from ginga.qtw.GingaQt import GingaView
        except ImportError:
            try:
                from ginga.gtkw.GingaGtk import GingaView
            except ImportError:
                print("You need python-gtk or python-qt4 to run Ginga!")
                sys.exit(1)

    # Define class dynamically based on toolkit choice
    class Ginga(GingaControl, GingaView):

        def __init__(self, logger, threadPool, module_manager, prefs,
                     ev_quit=None):
            GingaView.__init__(self, logger, ev_quit)
            GingaControl.__init__(self, logger, threadPool, module_manager,
                                  prefs, ev_quit=ev_quit)

    if settings.get('useMatplotlibColormaps', False):
        # Add matplotlib color maps if matplotlib is installed
        try:
            from ginga import cmap
            cmap.add_matplotlib_cmaps()
        except Exception as e:
            logger.warn("failed to load matplotlib colormaps: %s" % (str(e)))

    # User wants to customize the WCS package?
    if options.wcs:
        wcspkg = options.wcs
    else:
        wcspkg = settings.get('WCSpkg', 'choose')

    try:
        from ginga.util import wcsmod
        assert wcsmod.use(wcspkg) == True
    except Exception as e:
        logger.warn("failed to set WCS package preference: %s" % (str(e)))

    # User wants to customize the FITS package?
    if options.fits:
        fitspkg = options.fits
    else:
        fitspkg = settings.get('FITSpkg', 'choose')

    try:
        from ginga.util import io_fits
        assert io_fits.use(fitspkg) == True
    except Exception as e:
        logger.warn("failed to set FITS package preference: %s" % (str(e)))

    # Create the dynamic module manager
    mm = ModuleManager.ModuleManager(logger)

    # Create and start thread pool
    ev_quit = threading.Event()
    threadPool = Task.ThreadPool(options.numthreads, logger,
                                 ev_quit=ev_quit)
    threadPool.startall()

    # Create the Ginga main object
    ginga = Ginga(logger, threadPool, mm, prefs, ev_quit=ev_quit)
    ginga.set_layout(default_layout)

    # User configuration (custom star catalogs, etc.)
    try:
        import ginga_config

        ginga_config.pre_gui_config(ginga)
    except Exception as e:
        try:
            (type, value, tb) = sys.exc_info()
            tb_str = "\n".join(traceback.format_tb(tb))

        except Exception:
            tb_str = "Traceback information unavailable."

        logger.error("Error importing Ginga config file: %s" % (
            str(e)))
        logger.error("Traceback:\n%s" % (tb_str))

    # Build desired layout
    ginga.build_toplevel()

    # Did user specify a particular geometry?
    if options.geometry:
        ginga.setGeometry(options.geometry)

    # Add desired global plugins
    for spec in global_plugins:
        ginga.add_global_plugin(spec)

    # Add GUI log handler (for "Log" global plugin)
    guiHdlr = GuiLogHandler(ginga)
    guiHdlr.setLevel(options.loglevel)
    fmt = logging.Formatter(log.LOG_FORMAT)
    guiHdlr.setFormatter(fmt)
    logger.addHandler(guiHdlr)

    # Load any custom modules
    if options.modules:
        modules = options.modules.split(',')
        for pluginName in modules:
            spec = Bunch(name=pluginName, module=pluginName,
                         tab=pluginName, ws='right')
            ginga.add_global_plugin(spec)

    # Load modules for "local" (per-channel) plug ins
    for spec in local_plugins:
        ginga.add_local_plugin(spec)

    # Load any custom plugins
    if options.plugins:
        plugins = options.plugins.split(',')
        for pluginName in plugins:
            spec = Bunch(module=pluginName, ws='dialogs',
                         hidden=False)
            ginga.add_local_plugin(spec)

    ginga.update_pending()

    # TEMP?
    ginga.ds.raise_tab('Info')
    ginga.ds.raise_tab('Thumbs')

    # Add custom channels
    channels = options.channels.split(',')
    for chname in channels:
        datasrc = Datasrc.Datasrc(length=options.bufsize)
        ginga.add_channel(chname, datasrc)
    ginga.change_channel(channels[0])

    # User configuration (custom star catalogs, etc.)
    try:
        ginga_config.post_gui_config(ginga)
    except Exception as e:
        try:
            (type, value, tb) = sys.exc_info()
            tb_str = "\n".join(traceback.format_tb(tb))

        except Exception:
            tb_str = "Traceback information unavailable."

        logger.error("Error processing Ginga config file: %s" % (
            str(e)))
        logger.error("Traceback:\n%s" % (tb_str))

    # Display banner the first time run, unless suppressed
    showBanner = True
    try:
        showBanner = settings.get('showBanner')
        
    except KeyError:
        # disable for subsequent runs
        settings.set(showBanner=False)
        settings.save()
        
    if (not options.nosplash) and (len(args) == 0) and showBanner:
        ginga.banner()

    # Assume remaining arguments are fits files and load them.
    for imgfile in args:
        ginga.nongui_do(ginga.load_file, imgfile)

    try:
        try:
            # Main loop to handle GUI events
            logger.info("Entering mainloop...")
            ginga.mainloop(timeout=0.001)

        except KeyboardInterrupt:
            logger.error("Received keyboard interrupt!")

    finally:
        logger.info("Shutting down...")
        ev_quit.set()

    sys.exit(0)
示例#20
0
"""
Example of 3D plotting in Ginga

Plots an octahedron within a wireframe sphere.

Run with no parameters.  Scroll to zoom in/out, click and drag to orbit.

Requirements: Qt5, OpenGL, numpy
"""
from __future__ import print_function
import sys, os
import logging
import numpy as np

from ginga import toolkit
toolkit.use('qt5')

from ginga import colors
from ginga.gw import Widgets, Viewers
from ginga.opengl.ImageViewQtGL import CanvasView
from ginga.canvas.CanvasObject import get_canvas_types
from ginga.misc import log

class Viewer(object):

    def __init__(self, app):
        super(Viewer, self).__init__()
        self.logger = app.logger
        self.dc = get_canvas_types()

        self.top = app.make_window(title="Simple Ginga 3D Viewer")
示例#21
0
    def main(self, options, args):
        # Create top level logger.
        svcname = 'qplan'
        logger = log.get_logger(name=svcname, options=options)

        logger.info("starting qplan %s" % (version.version))

        ev_quit = threading.Event()

        thread_pool = Task.ThreadPool(logger=logger,
                                      ev_quit=ev_quit,
                                      numthreads=options.numthreads)

        if options.toolkit is not None:
            ginga_toolkit.use(options.toolkit)
        else:
            ginga_toolkit.choose()

        tkname = ginga_toolkit.get_family()
        logger.info("Chosen toolkit (%s) family is '%s'" %
                    (ginga_toolkit.toolkit, tkname))

        from qplan.View import Viewer
        # must import AFTER Viewer
        from ginga.rv.Control import GuiLogHandler

        class QueuePlanner(Controller, Viewer):
            def __init__(self, logger, thread_pool, module_manager,
                         preferences, ev_quit, model):

                Viewer.__init__(self, logger, ev_quit)
                Controller.__init__(self, logger, thread_pool, module_manager,
                                    preferences, ev_quit, model)

        # Get settings folder
        if 'CONFHOME' in os.environ:
            basedir = os.path.join(os.environ['CONFHOME'], svcname)
        else:
            basedir = os.path.join(os.environ['HOME'], '.' + svcname)
        if not os.path.exists(basedir):
            os.mkdir(basedir)
        prefs = Settings.Preferences(basefolder=basedir, logger=logger)

        settings = prefs.create_category('general')
        settings.load(onError='silent')
        settings.set_defaults(output_dir=options.output_dir, save_layout=False)

        mm = ModuleManager.ModuleManager(logger)

        ## # Add any custom modules
        ## if options.modules:
        ##     modules = options.modules.split(',')
        ##     for mdlname in modules:
        ##         #self.mm.loadModule(name, pfx=pluginconfpfx)
        ##         self.mm.loadModule(name)

        observer = site.get_site(options.sitename)

        scheduler = Scheduler(logger, observer)

        model = QueueModel(logger, scheduler)

        if options.completed is not None:
            import json
            logger.info("reading executed OBs from '{}' ...".format(
                options.completed))
            # user specified a set of completed OB keys
            with open(options.completed, 'r') as in_f:
                buf = in_f.read()
            d = json.loads(buf)
            model.completed_obs = {(propid, obcode): d[propid][obcode]
                                   for propid in d for obcode in d[propid]}

        # Start up the control/display engine
        qplanner = QueuePlanner(logger, thread_pool, mm, prefs, ev_quit, model)
        qplanner.set_input_dir(options.input_dir)
        qplanner.set_input_fmt(options.input_fmt)

        layout_file = None
        if not options.norestore and settings.get('save_layout', False):
            layout_file = os.path.join(basedir, 'layout')

        # Build desired layout
        qplanner.build_toplevel(default_layout, layout_file=layout_file)
        for w in qplanner.ds.toplevels:
            w.show()

        # load plugins
        for spec in plugins:
            qplanner.load_plugin(spec.name, spec)

        # start any plugins that have start=True
        qplanner.boot_plugins()

        qplanner.ds.raise_tab('Control Panel')

        guiHdlr = GuiLogHandler(qplanner)
        #guiHdlr.setLevel(options.loglevel)
        guiHdlr.setLevel(logging.INFO)
        fmt = logging.Formatter(log.LOG_FORMAT)
        guiHdlr.setFormatter(fmt)
        logger.addHandler(guiHdlr)

        qplanner.update_pending()

        # Did user specify geometry
        if options.geometry:
            qplanner.set_geometry(options.geometry)

        # Raise window
        w = qplanner.w.root
        w.show()

        server_started = False

        # Create threadpool and start it
        try:
            # Startup monitor threadpool
            thread_pool.startall(wait=True)

            try:
                # if there is a network component, start it
                if hasattr(qplanner, 'start'):
                    task = Task.FuncTask2(qplanner.start)
                    thread_pool.addTask(task)

                # Main loop to handle GUI events
                qplanner.mainloop(timeout=0.001)

            except KeyboardInterrupt:
                logger.error("Received keyboard interrupt!")

        finally:
            logger.info("Shutting down...")
            thread_pool.stopall(wait=True)

        sys.exit(0)
示例#22
0
文件: main.py 项目: jochym/ginga
    def main(self, options, args):
        """
        Main routine for running the reference viewer.

        `options` is a OptionParser object that has been populated with
        values from parsing the command line.  It should at least include
        the options from add_default_options()

        `args` is a list of arguments to the viewer after parsing out
        options.  It should contain a list of files or URLs to load.
        """

        # Create a logger
        logger = log.get_logger(name='ginga', options=options)

        # Get settings (preferences)
        basedir = paths.ginga_home
        if not os.path.exists(basedir):
            try:
                os.mkdir(basedir)
            except OSError as e:
                logger.warn("Couldn't create ginga settings area (%s): %s" % (
                    basedir, str(e)))
                logger.warn("Preferences will not be able to be saved")

        # Set up preferences
        prefs = Settings.Preferences(basefolder=basedir, logger=logger)
        settings = prefs.createCategory('general')
        settings.load(onError='silent')
        settings.setDefaults(useMatplotlibColormaps=False,
                             widgetSet='choose',
                             WCSpkg='choose', FITSpkg='choose',
                             recursion_limit=2000)

        # default of 1000 is a little too small
        sys.setrecursionlimit(settings.get('recursion_limit'))

        # So we can find our plugins
        sys.path.insert(0, basedir)
        moduleHome = os.path.split(sys.modules['ginga.version'].__file__)[0]
        childDir = os.path.join(moduleHome, 'misc', 'plugins')
        sys.path.insert(0, childDir)
        pluginDir = os.path.join(basedir, 'plugins')
        sys.path.insert(0, pluginDir)

        # Choose a toolkit
        if options.toolkit:
            toolkit = options.toolkit
        else:
            toolkit = settings.get('widgetSet', 'choose')

        ginga_toolkit.use(toolkit)
        tkname = ginga_toolkit.get_family()
        logger.info("Chosen toolkit (%s) family is '%s'" % (
            ginga_toolkit.toolkit, tkname))

        ##from ginga.gw.GingaGw import GingaView
        if tkname == 'gtk':
            from ginga.gtkw.GingaGtk import GingaView
        elif tkname == 'qt':
            from ginga.qtw.GingaQt import GingaView
        else:
            try:
                from ginga.qtw.GingaQt import GingaView
            except ImportError:
                try:
                    from ginga.gtkw.GingaGtk import GingaView
                except ImportError:
                    print("You need python-gtk or python-qt4 to run Ginga!")
                    sys.exit(1)

        # these imports have to be here, otherwise they force the choice
        # of toolkit too early
        from ginga.Control import GingaControl, GuiLogHandler

        # Define class dynamically based on toolkit choice
        class Ginga(GingaControl, GingaView):

            def __init__(self, logger, thread_pool, module_manager, prefs,
                         ev_quit=None):
                GingaView.__init__(self, logger, ev_quit)
                GingaControl.__init__(self, logger, thread_pool, module_manager,
                                      prefs, ev_quit=ev_quit)

        if settings.get('useMatplotlibColormaps', False):
            # Add matplotlib color maps if matplotlib is installed
            try:
                from ginga import cmap
                cmap.add_matplotlib_cmaps()
            except Exception as e:
                logger.warn("failed to load matplotlib colormaps: %s" % (str(e)))

        # User wants to customize the WCS package?
        if options.wcspkg:
            wcspkg = options.wcspkg
        else:
            wcspkg = settings.get('WCSpkg', 'choose')

        try:
            from ginga.util import wcsmod
            assert wcsmod.use(wcspkg) == True
        except Exception as e:
            logger.warn("failed to set WCS package preference: %s" % (str(e)))

        # User wants to customize the FITS package?
        if options.fitspkg:
            fitspkg = options.fitspkg
        else:
            fitspkg = settings.get('FITSpkg', 'choose')

        try:
            from ginga.util import io_fits
            assert io_fits.use(fitspkg) == True
        except Exception as e:
            logger.warn("failed to set FITS package preference: %s" % (str(e)))

        # Check whether user wants to use OpenCv
        use_opencv = settings.get('use_opencv', False)
        if use_opencv or options.opencv:
            from ginga import trcalc
            try:
                trcalc.use('opencv')
            except Exception as e:
                logger.warn("failed to set OpenCv preference: %s" % (str(e)))

        # Create the dynamic module manager
        mm = ModuleManager.ModuleManager(logger)

        # Create and start thread pool
        ev_quit = threading.Event()
        thread_pool = Task.ThreadPool(options.numthreads, logger,
                                     ev_quit=ev_quit)
        thread_pool.startall()

        # Create the Ginga main object
        ginga = Ginga(logger, thread_pool, mm, prefs, ev_quit=ev_quit)
        ginga.set_layout(self.layout)

        gc = os.path.join(basedir, "ginga_config.py")
        have_ginga_config = os.path.exists(gc)

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                import ginga_config

                ginga_config.pre_gui_config(ginga)
            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error importing Ginga config file: %s" % (
                    str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Build desired layout
        ginga.build_toplevel()

        # Did user specify a particular geometry?
        if options.geometry:
            ginga.setGeometry(options.geometry)

        # make the list of disabled plugins
        disabled_plugins = []
        if not (options.disable_plugins is None):
            disabled_plugins = options.disable_plugins.lower().split(',')

        # Add desired global plugins
        for spec in self.global_plugins:
            if not spec.module.lower() in disabled_plugins:
                ginga.add_global_plugin(spec)

        # Add GUI log handler (for "Log" global plugin)
        guiHdlr = GuiLogHandler(ginga)
        guiHdlr.setLevel(options.loglevel)
        fmt = logging.Formatter(log.LOG_FORMAT)
        guiHdlr.setFormatter(fmt)
        logger.addHandler(guiHdlr)

        # Load any custom modules
        if options.modules:
            modules = options.modules.split(',')
            for longPluginName in modules:
                if '.' in longPluginName:
                    tmpstr = longPluginName.split('.')
                    pluginName = tmpstr[-1]
                    pfx = '.'.join(tmpstr[:-1])
                else:
                    pluginName = longPluginName
                    pfx = None
                spec = Bunch(name=pluginName, module=pluginName,
                             tab=pluginName, ws='right', pfx=pfx)
                ginga.add_global_plugin(spec)

        # Load modules for "local" (per-channel) plug ins
        for spec in self.local_plugins:
            if not spec.module.lower() in disabled_plugins:
                ginga.add_local_plugin(spec)

        # Load any custom plugins
        if options.plugins:
            plugins = options.plugins.split(',')
            for longPluginName in plugins:
                if '.' in longPluginName:
                    tmpstr = longPluginName.split('.')
                    pluginName = tmpstr[-1]
                    pfx = '.'.join(tmpstr[:-1])
                else:
                    pluginName = longPluginName
                    pfx = None
                spec = Bunch(module=pluginName, ws='dialogs',
                             hidden=False, pfx=pfx)
                ginga.add_local_plugin(spec)

        ginga.update_pending()

        # TEMP?
        tab_names = list(map(lambda name: name.lower(),
                             ginga.ds.get_tabnames(group=None)))
        if 'info' in tab_names:
            ginga.ds.raise_tab('Info')
        if 'thumbs' in tab_names:
            ginga.ds.raise_tab('Thumbs')

        # User configuration (custom star catalogs, etc.)
        if have_ginga_config:
            try:
                ginga_config.post_gui_config(ginga)
            except Exception as e:
                try:
                    (type, value, tb) = sys.exc_info()
                    tb_str = "\n".join(traceback.format_tb(tb))

                except Exception:
                    tb_str = "Traceback information unavailable."

                logger.error("Error processing Ginga config file: %s" % (
                    str(e)))
                logger.error("Traceback:\n%s" % (tb_str))

        # Add custom channels
        channels = options.channels.split(',')
        for chname in channels:
            datasrc = Datasrc.Datasrc(length=options.bufsize)
            ginga.add_channel(chname, datasrc)
        ginga.change_channel(channels[0])

        # Display banner the first time run, unless suppressed
        showBanner = True
        try:
            showBanner = settings.get('showBanner')

        except KeyError:
            # disable for subsequent runs
            settings.set(showBanner=False)
            settings.save()

        if (not options.nosplash) and (len(args) == 0) and showBanner:
            ginga.banner()

        # Assume remaining arguments are fits files and load them.
        for imgfile in args:
            ginga.nongui_do(ginga.load_file, imgfile)

        try:
            try:
                # if there is a network component, start it
                if hasattr(ginga, 'start'):
                    task = Task.FuncTask2(ginga.start)
                    thread_pool.addTask(task)

                # Main loop to handle GUI events
                logger.info("Entering mainloop...")
                ginga.mainloop(timeout=0.001)

            except KeyboardInterrupt:
                logger.error("Received keyboard interrupt!")

        finally:
            logger.info("Shutting down...")
            ev_quit.set()

        sys.exit(0)
示例#23
0
Examples:
  $ python widgets.py qt5 gridbox
  $ python widgets.py gtk3 label
  $ python widgets.py pg button
"""
import sys
import os

from ginga.misc import log
import ginga.toolkit as ginga_toolkit

# decide our toolkit, then import
tkit = sys.argv[1]
wname = sys.argv[2]

ginga_toolkit.use(tkit)
from ginga.gw import Widgets, Viewers, GwHelp  # noqa
from ginga.util.paths import icondir  # noqa

top = None


def quit(*args):
    if top is not None:
        top.delete()
    sys.exit()


def popup_dialog(parent):
    dia = Widgets.Dialog(title="Dialog Title",
                         buttons=[('ok', 0), ('cancel', 1)],