Пример #1
0
 def initialize(self):
     self.w1 = Window(5,
                      5,
                      15,
                      15,
                      title='Window 1',
                      framed=True,
                      window_manager=self.window_manager)
     self.w2 = Window(10,
                      10,
                      20,
                      30,
                      title='Window 2',
                      framed=True,
                      window_manager=self.window_manager)
     self.list_view = ListWindow(tlx=15,
                                 tly=15,
                                 width=20,
                                 height=5,
                                 title='List Window',
                                 framed=True,
                                 window_manager=self.window_manager)
     self.list_view.add_item('An item.', 'An item.')
     self.list_view.add_item('Another item.', 'Uhuh.')
     self.list_view.add_item('Keep going.', 'Number.')
     self.list_view.add_item('Scrolling yet?', 'Scroll')
     self.list_view.add_item('last one', 'the end.')
Пример #2
0
 def __init__(self, beam_setup, root_frame):
     """Initialise the window"""
     self.window = Window(
         ROOT.gClient.GetRoot(),  # pylint: disable = E1101
         root_frame,
         SHARE_DIR + "twiss_setup.json")
     self.beam_setup = beam_setup
     self.window.set_button_action("&Okay", self.okay_action)
     self.window.set_button_action("&Cancel", self.cancel_action)
Пример #3
0
    def run():
        Log.log_application_name = "Test"
        Log.log("Starting...")
        window = Window()
        window.add_workspace(WsStart)
        window.add_workspace(WsTest)
        window.activate_workspace(WsStart)

        window.run()
Пример #4
0
 def __init__(self, main_window, parent):
     """Initialise the GUI window"""
     self.main_window = main_window
     self.parent = parent
     manipulators = {"magnet_setup_action": self.magnet_setup_action}
     self.window = Window(
         ROOT.gClient.GetRoot(),  # pylint: disable = E1101
         parent,
         data_file=self.share_dir + "magnet_setup.json",
         manipulator_dict=manipulators)
     self.window.set_button_action("&Okay", self.okay_action)
     self.window.set_button_action("&Cancel", self.cancel_action)
Пример #5
0
class DashboardThread(Thread):

    def __init__(self):
        super().__init__()
        self.window = None

    def run(self):
        logger.debug(f'{self.__class__.__name__} started')
        self.window = Window()
        logger.debug(f'{self.__class__.__name__} ready')
        self.window.work()
        logger.debug(f'{self.__class__.__name__} finished')

    def handle(self, state, out=None):
        if self.window is not None:
            self.window.handle(state, out)
        else:
            logger.debug('Window is None, can not handle incoming')

    def set_stop(self):
        if self.window is not None:
            self.window.add_event(QUIT)
        else:
            logger.debug('Window is None, can not stop')

    def clear(self):
        if self.window is not None:
            self.window.clear()
        else:
            logger.debug('Window is None, can not handle clear')
Пример #6
0
class Application(QtGui.QApplication):
    """
    Main application representation.
    """
    def __init__(self, simulation):
        super(Application, self).__init__(sys.argv)
        self.frame = Window(simulation=simulation)
        self.sim = simulation
        self.frame.show()

    def run(self):
        """
        Starts the QT mainloop for application.
        """
        sys.exit(self.exec_())
Пример #7
0
    def __init__(self, main_window, parent):
        """Initialise the window"""
        self.window = Window(
            ROOT.gClient.GetRoot(),  # pylint: disable = E1101
            parent,
            SHARE_DIR + "beam_setup.json")
        self.main_window = main_window
        self.parent = parent
        self.matrix_select = None
        self.matrix = None

        self.window.set_button_action("&Penn", self.penn_action)
        self.window.set_button_action("&Twiss", self.twiss_action)
        self.window.set_button_action("&Okay", self.okay_action)
        self.window.set_button_action("&Cancel", self.cancel_action)
Пример #8
0
def main(stdscr):
    test = Window(30, 30, 0, 0)
    while True:
        test.clear()
        test.add_str(0, 0,
                     "Lines: {} Colums: {}".format(curses.LINES, curses.COLS))
        test.add_str(1, 0, "{}".format(stdscr.getmaxyx()))
        stdscr.getkey()
Пример #9
0
    def configure(self, parent):
        """ Show the configuration window """
        if self.cfgWindow is None:
            from gui.window import Window

            self.cfgWindow = Window('IMStatus.ui', 'vbox1', __name__, _(MOD_NAME), 440, 290)
            # GTK handlers
            self.cfgWindow.getWidget('rad-stopDoNothing').connect('toggled', self.onRadToggled)
            self.cfgWindow.getWidget('rad-stopSetStatus').connect('toggled', self.onRadToggled)
            self.cfgWindow.getWidget('btn-ok').connect('clicked', self.onBtnOk)
            self.cfgWindow.getWidget('btn-cancel').connect('clicked', lambda btn: self.cfgWindow.hide())
            self.cfgWindow.getWidget('btn-help').connect('clicked', self.onBtnHelp)

        if not self.cfgWindow.isVisible():
            self.cfgWindow.getWidget('txt-status').set_text(prefs.get(__name__, 'status-msg', DEFAULT_STATUS_MSG))
            self.cfgWindow.getWidget('chk-updateOnPaused').set_active(prefs.get(__name__, 'update-on-paused', DEFAULT_UPDATE_ON_PAUSED))
            self.cfgWindow.getWidget('chk-updateWhenAway').set_active(prefs.get(__name__, 'update-when-away', DEFAULT_UPDATE_WHEN_AWAY))
            self.cfgWindow.getWidget('rad-stopDoNothing').set_active(prefs.get(__name__, 'stop-action', DEFAULT_STOP_ACTION) == STOP_DO_NOTHING)
            self.cfgWindow.getWidget('rad-stopSetStatus').set_active(prefs.get(__name__, 'stop-action', DEFAULT_STOP_ACTION) == STOP_SET_STATUS)
            self.cfgWindow.getWidget('txt-stopStatus').set_sensitive(prefs.get(__name__, 'stop-action', DEFAULT_STOP_ACTION) == STOP_SET_STATUS)
            self.cfgWindow.getWidget('txt-stopStatus').set_text(prefs.get(__name__, 'stop-status', DEFAULT_STOP_STATUS))
            self.cfgWindow.getWidget('txt-sanitizedWords').get_buffer().set_text(prefs.get(__name__, 'sanitized-words', DEFAULT_SANITIZED_WORDS))
            self.cfgWindow.getWidget('btn-ok').grab_focus()

        self.cfgWindow.show()
def main():
    window, size = Window()
    sidebar = LoadSidebar(window)
    navigator = LoadNavigator(window, size)
    canvas, charts = LoadCanvas(window, size)

    status = StringVar(value=WAITING)  # 程序状态 1. 未开始 2. 计算中 3. 结果
    updateStatus = bindStatus(status)

    addLabel(navigator, status)
    addCommand(sidebar, COMPUTE_LABEL_P, startFetch(FETCH_P, updateStatus))
    addCommand(sidebar, COMPUTE_LABEL_V, startFetch(FETCH_V, updateStatus))
    addCommand(sidebar, CLEAR_LABEL, clearUI(updateStatus))
    addCommand(sidebar, SAVE_LABEL, save)
    addCommand(sidebar, UPLOAD_LABEL, upload)

    window.mainloop()
Пример #11
0
 def __init__(self, beam_setup, root_frame):
     """Initialise the window"""
     self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable = E1101
                          root_frame,
                          SHARE_DIR+"twiss_setup.json")
     self.beam_setup = beam_setup
     self.window.set_button_action("&Okay", self.okay_action)
     self.window.set_button_action("&Cancel", self.cancel_action)
Пример #12
0
 def __init__(self):
     """Initialise the main window"""
     self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable=E1101
                          ROOT.gClient.GetRoot(), # pylint: disable=E1101
                          SHARE_DIR+"main_frame.json")
     self.lattice = Lattice()
     self.beam_setup = None
     self.magnet_setup = None
     self.plot_setup = None
     self.plot_setup_options = [{"variable_type":0,
                                 "first_var":0,
                                 "plot_apertures":True}]
     self.window.set_button_action("&Beam Setup", self.beam_button_action)
     self.window.set_button_action("&Magnet Setup",
                                                   self.magnet_button_action)
     self.window.set_button_action("&Plot Setup", self.plot_button_action)
     self.window.set_button_action("E&xit", self.exit_button_action)
     self.update_plot()
Пример #13
0
 def __init__(self, main_window, parent, selected):
     """
     Initialise the window
     """
     self.main_window = main_window
     self.parent = parent
     self.selected = selected
     self.window = Window(
         ROOT.gClient.GetRoot(),  # pylint: disable = E1101
         parent,
         self.share_dir + "plot_setup.json")
     for i, item in enumerate(self.selected):
         self.window.set_action("variable_type_" + str(i), "drop_down",
                                "Selected(Int_t)", self.select_action)
         type_frame = self.window.get_frame("variable_type_" + str(i),
                                            "drop_down")
         type_frame.Select(item["variable_type"])
     self.window.set_button_action("&Okay", self.okay_action)
     self.window.set_button_action("&Cancel", self.cancel_action)
Пример #14
0
def main():
    """main函数"""

    app = Window()
    queue = Queue()

    watcher.start()

    for _ in range(4):
        reg = Recognize(queue, watcher.original_cmd())
        reg.start()

    camera = CameraTools(queue, 8500)
    camera.start_monitor()

    board = BoardTools()
    board.start_monitor()

    app.show()
Пример #15
0
 def __init__(self, main_window, parent):
     """Initialise the GUI window"""
     self.main_window = main_window
     self.parent = parent
     manipulators = {"magnet_setup_action":self.magnet_setup_action}
     self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable = E1101
                          parent,
                          data_file = self.share_dir+"magnet_setup.json",
                          manipulator_dict = manipulators)
     self.window.set_button_action("&Okay", self.okay_action)
     self.window.set_button_action("&Cancel", self.cancel_action)
Пример #16
0
    def __init__(self, main_window, parent):
        """Initialise the window"""
        self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable = E1101
                             parent,
                             SHARE_DIR+"beam_setup.json")
        self.main_window = main_window
        self.parent = parent
        self.matrix_select = None
        self.matrix = None

        self.window.set_button_action("&Penn", self.penn_action)
        self.window.set_button_action("&Twiss", self.twiss_action)
        self.window.set_button_action("&Okay", self.okay_action)
        self.window.set_button_action("&Cancel", self.cancel_action)
Пример #17
0
 def __init__(self, datacards):
     """Initialise the main window"""
     self.last = datetime.datetime.now()
     self.window = Window(ROOT.gClient.GetRoot(), ROOT.gClient.GetRoot(),
                          SHARE_DIR + "online_gui.json")
     self._set_actions()
     self._docstore = None
     self._datacards = datacards
     self._draw_titles = Queue.Queue()
     for title in datacards["online_gui_default_canvases"]:
         self._draw_titles.put(title)
     self._canvases_read = Queue.Queue()
     self._canvases_draw = ThreadedValue([])
     self._redraw_target = None
     self._paused = ThreadedValue(False)
     rotate_tmp = self.window.get_text_entry("Rotate period", type(1.))
     self._rotate_period = ThreadedValue(rotate_tmp)
     reload_tmp = self.window.get_text_entry("Reload period", type(1.))
     self._reload_period = ThreadedValue(reload_tmp)
     self._poll_period = ThreadedValue(0.1)
     self._collections = ThreadedValue([])
     self._init_docstore()
     self._start_polling()
Пример #18
0
    def configure(self, parent):
        """ Show the configuration window """
        if self.cfgWin is None:
            from gui.window import Window

            self.cfgWin = Window('Covers.ui', 'vbox1', __name__,
                                 MOD_INFO[modules.MODINFO_L10N], 320, 265)
            self.cfgWin.getWidget('btn-ok').connect('clicked', self.onBtnOk)
            self.cfgWin.getWidget('img-lastfm').set_from_file(
                os.path.join(consts.dirPix, 'audioscrobbler.png'))
            self.cfgWin.getWidget('btn-help').connect('clicked',
                                                      self.onBtnHelp)
            self.cfgWin.getWidget('chk-downloadCovers').connect(
                'toggled', self.onDownloadCoversToggled)
            self.cfgWin.getWidget('btn-cancel').connect(
                'clicked', lambda btn: self.cfgWin.hide())

        if not self.cfgWin.isVisible():
            downloadCovers = prefs.get(__name__, 'download-covers',
                                       PREFS_DFT_DOWNLOAD_COVERS)
            preferUserCovers = prefs.get(__name__, 'prefer-user-covers',
                                         PREFS_DFT_PREFER_USER_COVERS)
            userCoverFilenames = prefs.get(__name__, 'user-cover-filenames',
                                           PREFS_DFT_USER_COVER_FILENAMES)

            self.cfgWin.getWidget('btn-ok').grab_focus()
            self.cfgWin.getWidget('txt-filenames').set_text(
                ', '.join(userCoverFilenames))
            self.cfgWin.getWidget('chk-downloadCovers').set_active(
                downloadCovers)
            self.cfgWin.getWidget('chk-preferUserCovers').set_active(
                preferUserCovers)
            self.cfgWin.getWidget('chk-preferUserCovers').set_sensitive(
                downloadCovers)

        self.cfgWin.show()
Пример #19
0
    def __init__(self):
        self.config_path = join_path('utils/config.json')
        font_id = Qt.QFontDatabase.addApplicationFont(
            join_path("static/iconfont.ttf"))
        self.ico_font = Qt.QFont(
            Qt.QFontDatabase.applicationFontFamilies(font_id)[0], 30)
        self.config = {}
        self.load_config()

        self.Setting = Setting(self)
        self.Window = Window(self)
        self.Tray = Tray(self)

        if self.config['show_setting_window']:
            self.Setting.show()
            self.config['show_setting_window'] = False
            self.dump_config()
Пример #20
0
 def __init__(self, main_window, parent, selected):
     """
     Initialise the window
     """
     self.main_window = main_window
     self.parent = parent
     self.selected = selected
     self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable = E1101
                          parent,
                          self.share_dir+"plot_setup.json")
     for i, item in enumerate(self.selected):
         self.window.set_action("variable_type_"+str(i), "drop_down",
                               "Selected(Int_t)", self.select_action)
         type_frame = self.window.get_frame("variable_type_"+str(i),
                                            "drop_down")
         type_frame.Select(item["variable_type"])
     self.window.set_button_action("&Okay", self.okay_action)
     self.window.set_button_action("&Cancel", self.cancel_action)
Пример #21
0
 def __init__(self, datacards):
     """Initialise the main window"""
     self.last = datetime.datetime.now()
     self.window = Window(ROOT.gClient.GetRoot(),
                          ROOT.gClient.GetRoot(),
                          SHARE_DIR+"online_gui.json")
     self._set_actions()
     self._docstore = None
     self._datacards = datacards
     self._draw_titles = Queue.Queue()
     for title in datacards["online_gui_default_canvases"]:
         self._draw_titles.put(title)
     self._canvases_read = Queue.Queue()
     self._canvases_draw = ThreadedValue([])
     self._redraw_target = None
     self._paused = ThreadedValue(False)
     rotate_tmp = self.window.get_text_entry("Rotate period", type(1.))
     self._rotate_period = ThreadedValue(rotate_tmp)
     reload_tmp = self.window.get_text_entry("Reload period", type(1.))
     self._reload_period = ThreadedValue(reload_tmp)
     self._poll_period = ThreadedValue(0.1)
     self._collections = ThreadedValue([])
     self._init_docstore()
     self._start_polling()
Пример #22
0
    def __init__(self, stdscr):
        curses.curs_set(0)
        curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_MAGENTA)

        self.clipbord = None
        self.tab_manager = Tab_manager(
            os.path.dirname(os.path.abspath(__file__)))
        self.stdscr = Window(curses.LINES, curses.COLS, 0, 0)
        self.stdscr.window = stdscr

        self.stdscr.refresh()
        self.parent_dir_widged = File_viewer(
            self.stdscr.x - 3,
            round(config.parent_dir_width * self.stdscr.y / 100), 1, 0,
            self.tab_manager.selected_tab.current_file.parent_dir,
            self.tab_manager.selected_tab.current_file)
        self.current_dir_widged = File_viewer(
            self.stdscr.x - 3,
            round(config.current_dir_width * self.stdscr.y / 100), 1,
            self.parent_dir_widged.y,
            self.tab_manager.selected_tab.current_file,
            self.tab_manager.selected_tab.selected_file, True)
        self.preview_widged = File_viewer(
            self.stdscr.x - 3, self.stdscr.y - self.parent_dir_widged.y -
            self.current_dir_widged.y - 1, 1,
            self.stdscr.y - (self.stdscr.y - self.parent_dir_widged.y -
                             self.current_dir_widged.y - 1),
            self.tab_manager.selected_tab.selected_file)
        self.statusbar = Statusbar(
            1, self.stdscr.y, 0, 0, getpass.getuser(), socket.gethostname(),
            self.tab_manager.selected_tab.current_file.path,
            self.tab_manager.tab_list)
        self.window_command = Window(1, self.stdscr.y, self.stdscr.x - 1, 0)
        self.window_info = Window(1, self.stdscr.y, self.stdscr.x - 2, 0)
        self.stdscr.refresh()

        #self.resize()
        self.stdscr.refresh()
        self.mainloop()
Пример #23
0
class PennSetup:
    """GUI window to setup a beam according to 4D Penn parameterisation"""
    def __init__(self, beam_setup, root_frame):
        """Initialise the window"""
        self.window = Window(
            ROOT.gClient.GetRoot(),  # pylint: disable = E1101
            root_frame,
            SHARE_DIR + "penn_setup.json")
        self.beam_setup = beam_setup
        self.window.set_button_action("&Okay", self.okay_action)
        self.window.set_button_action("&Cancel", self.cancel_action)
        self.window.set_button_action("Get &B0", self.get_b0_action)
        self.window.set_button_action("&Constant Beta",
                                      self.constant_beta_action)

    def okay_action(self):
        """Handle a click on the Okay button, building the beam matrix"""
        ref = self.beam_setup.get_reference()
        matrix = maus_cpp.covariance_matrix.create_from_penn_parameters(
            mass=ref['mass'],
            momentum=ref['p'],
            emittance_t=self.window.get_text_entry("emittance_trans",
                                                   type(1.)),
            beta_t=self.window.get_text_entry("beta_trans", type(1.)),
            emittance_l=self.window.get_text_entry("emittance_l", type(1.)),
            beta_l=self.window.get_text_entry("beta_l", type(1.)),
            alpha_t=self.window.get_text_entry("alpha_trans", type(1.)),
            alpha_l=self.window.get_text_entry("alpha_l", type(1.)),
            charge=ref["charge"],
            # BUG - multiply by -1 to fix BUG in source code
            bz=-self.window.get_text_entry("B0", type(1.)) * common.units['T'],
            ltwiddle=self.window.get_text_entry("Lc", type(1.)),
            dispersion_x=self.window.get_text_entry("disp_x", type(1.)),
            dispersion_prime_x=self.window.get_text_entry(
                "disp_prime_x", type(1.)),
            dispersion_y=self.window.get_text_entry("disp_y", type(1.)),
            dispersion_prime_y=self.window.get_text_entry(
                "disp_prime_y", type(1.)))
        self.beam_setup.set_matrix(matrix)
        self.beam_setup.get_matrix()  # check for consistency
        self.window.close_window()
        self.beam_setup.matrix_select = None

    def cancel_action(self):
        """Handle a click on the Cancel button"""
        self.window.close_window()
        self.beam_setup.matrix_select = None

    def get_b0_action(self):
        """
        Handle a click on the Get B0 button, getting B magnitude at the location
        of the reference particle
        """
        ref = self.beam_setup.get_reference()
        b_vec = maus_cpp.field.get_field_value(ref['x'], ref['y'], ref['z'],
                                               ref['t'])
        _b0 = (b_vec[0]**2 + b_vec[1]**2 + b_vec[2]**2)**0.5
        self.window.set_text_entry('B0', _b0 * common.units['T'])

    def constant_beta_action(self):
        """
        Handle a click on the Constant Beta button, getting beta function that
        would be required to get a constant beta function, given other settings
        (reference particle, B0, Lc)
        """
        _b0 = abs(self.window.get_text_entry("B0", type(1.)) * 1e-3)  # kT
        if abs(_b0) < 1e-9:
            raise ValueError(
              "Constant beta requires B0 is not 0. "+\
              "Modify the B0 field and try again."
            )
        _lc = self.window.get_text_entry("Lc", type(1.))  # kT
        mom = self.beam_setup.get_reference()['p']  # MeV/c
        charge = abs(self.beam_setup.get_reference()['charge'])  # eplus
        beta = (1 + _lc**
                2)**0.5 * 2. * charge * mom / common.constants['c_light'] / _b0
        self.window.set_text_entry('alpha_trans', 0.0)
        self.window.set_text_entry('beta_trans', beta)  # beta in mm
Пример #24
0
class MainWindow():
    """
    Defines the main window for the envelope tool GUI
    """
    def __init__(self):
        """Initialise the main window"""
        self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable=E1101
                             ROOT.gClient.GetRoot(), # pylint: disable=E1101
                             SHARE_DIR+"main_frame.json")
        self.lattice = Lattice()
        self.beam_setup = None
        self.magnet_setup = None
        self.plot_setup = None
        self.plot_setup_options = [{"variable_type":0,
                                    "first_var":0,
                                    "plot_apertures":True}]
        self.window.set_button_action("&Beam Setup", self.beam_button_action)
        self.window.set_button_action("&Magnet Setup",
                                                      self.magnet_button_action)
        self.window.set_button_action("&Plot Setup", self.plot_button_action)
        self.window.set_button_action("E&xit", self.exit_button_action)
        self.update_plot()

    def beam_button_action(self):
        """Handle a Beam Setup button press"""
        if self.beam_setup == None:
            self.beam_setup = BeamSetup(self, self.window.main_frame)
            ref, ellipse = self.lattice.get_beam()
            self.beam_setup.set_reference(ref)
            self.beam_setup.set_matrix(ellipse)

    def magnet_button_action(self):
        """Handle a Magnet Setup button press"""
        if self.magnet_setup == None:
            self.magnet_setup = MagnetSetup(self, self.window.main_frame)

    def plot_button_action(self):
        """Handle a Plot Setup button press"""
        if self.plot_setup == None:
            self.plot_setup = PlotSetup(self, self.window.main_frame,
                                        self.plot_setup_options)

    def exit_button_action(self):
        """Handle a Exit button press"""
        self.window.close_window()

    def update_plot(self):
        """Update the plot"""
        canvas_frame = self.window.get_frame("main_canvas", "canvas")
        canvas = canvas_frame.GetCanvas()
        Plotter(self.plot_setup_options, canvas, self.lattice.ref_list,
                self.lattice.ellipse_list, self.lattice.get_field_list())
Пример #25
0
class IMStatus(modules.Module):

    def __init__(self):
        """ Constructor """
        handlers = {
                        consts.MSG_EVT_PAUSED:       self.onPaused,
                        consts.MSG_EVT_STOPPED:      self.onStopped,
                        consts.MSG_EVT_UNPAUSED:     self.onUnpaused,
                        consts.MSG_EVT_APP_QUIT:     self.onStopped,
                        consts.MSG_EVT_NEW_TRACK:    self.onNewTrack,
                        consts.MSG_EVT_MOD_LOADED:   self.onModLoaded,
                        consts.MSG_EVT_APP_STARTED:  self.onModLoaded,
                        consts.MSG_EVT_MOD_UNLOADED: self.onStopped,
                   }

        modules.Module.__init__(self, handlers)


    def __format(self, string, track):
        """ Replace the special fields in the given string by their corresponding value and sanitize the result """
        result = track.format(string)

        if len(prefs.get(__name__, 'sanitized-words', DEFAULT_SANITIZED_WORDS)) != 0:
            lowerResult = result.lower()
            for word in [w.lower() for w in prefs.get(__name__, 'sanitized-words', DEFAULT_SANITIZED_WORDS).split('\n') if len(w) > 2]:
                pos = lowerResult.find(word)
                while pos != -1:
                    result      = result[:pos+1] + ('*' * (len(word)-2)) + result[pos+len(word)-1:]
                    lowerResult = lowerResult[:pos+1] + ('*' * (len(word)-2)) + lowerResult[pos+len(word)-1:]
                    pos         = lowerResult.find(word)

        return result


    def setStatusMsg(self, status):
        """ Update the status of all accounts of all active IM clients """
        for client in self.clients:
            for account in client[IM_ACCOUNTS]:
                client[IM_INSTANCE].setStatusMsg(account, status)


   # --== Message handlers ==--


    def onModLoaded(self):
        """ Initialize the module """
        self.track     = None   # Current track
        self.status    = ''     # The currently used status
        self.paused    = False  # True if the current track is paused
        self.clients   = []     # Clients currently active
        self.cfgWindow = None   # Configuration window

        # Detect active clients
        try:
            import dbus

            session        = dbus.SessionBus()
            activeServices = session.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus').ListNames()
            for activeClient in [client for client in CLIENTS if client[IM_DBUS_SERVICE_NAME] in activeServices]:
                obj       = session.get_object(activeClient[IM_DBUS_SERVICE_NAME], activeClient[IM_DBUS_OBJECT_NAME])
                interface = dbus.Interface(obj, activeClient[IM_DBUS_INTERFACE_NAME])

                activeClient[IM_INSTANCE] = activeClient[IM_CLASS](interface)
                activeClient[IM_ACCOUNTS] = activeClient[IM_INSTANCE].listAccounts()

                logger.info('[%s] Found %s instance' % (MOD_NAME, activeClient[IM_NAME]))
                self.clients.append(activeClient)
        except:
            logger.error('[%s] Error while initializing\n\n%s' % (MOD_NAME, traceback.format_exc()))


    def onNewTrack(self, track):
        """ A new track is being played """
        self.track  = track
        self.status = self.__format(prefs.get(__name__, 'status-msg', DEFAULT_STATUS_MSG), track)
        self.paused = False
        self.setStatusMsg(self.status)


    def onStopped(self):
        """ The current track has been stopped """
        self.track  = None
        self.paused = False
        if prefs.get(__name__, 'stop-action', DEFAULT_STOP_ACTION) == STOP_SET_STATUS:
            self.setStatusMsg(prefs.get(__name__, 'stop-status', DEFAULT_STOP_STATUS))


    def onPaused(self):
        """ The current track has been paused """
        self.paused = True
        if prefs.get(__name__, 'update-on-paused', DEFAULT_UPDATE_ON_PAUSED):
            self.setStatusMsg(_('%(status)s [paused]') % {'status': self.status})


    def onUnpaused(self):
        """ The current track has been unpaused """
        self.paused = False
        self.setStatusMsg(self.status)


    # --== Configuration ==--


    def configure(self, parent):
        """ Show the configuration window """
        if self.cfgWindow is None:
            from gui.window import Window

            self.cfgWindow = Window('IMStatus.ui', 'vbox1', __name__, _(MOD_NAME), 440, 290)
            # GTK handlers
            self.cfgWindow.getWidget('rad-stopDoNothing').connect('toggled', self.onRadToggled)
            self.cfgWindow.getWidget('rad-stopSetStatus').connect('toggled', self.onRadToggled)
            self.cfgWindow.getWidget('btn-ok').connect('clicked', self.onBtnOk)
            self.cfgWindow.getWidget('btn-cancel').connect('clicked', lambda btn: self.cfgWindow.hide())
            self.cfgWindow.getWidget('btn-help').connect('clicked', self.onBtnHelp)

        if not self.cfgWindow.isVisible():
            self.cfgWindow.getWidget('txt-status').set_text(prefs.get(__name__, 'status-msg', DEFAULT_STATUS_MSG))
            self.cfgWindow.getWidget('chk-updateOnPaused').set_active(prefs.get(__name__, 'update-on-paused', DEFAULT_UPDATE_ON_PAUSED))
            self.cfgWindow.getWidget('chk-updateWhenAway').set_active(prefs.get(__name__, 'update-when-away', DEFAULT_UPDATE_WHEN_AWAY))
            self.cfgWindow.getWidget('rad-stopDoNothing').set_active(prefs.get(__name__, 'stop-action', DEFAULT_STOP_ACTION) == STOP_DO_NOTHING)
            self.cfgWindow.getWidget('rad-stopSetStatus').set_active(prefs.get(__name__, 'stop-action', DEFAULT_STOP_ACTION) == STOP_SET_STATUS)
            self.cfgWindow.getWidget('txt-stopStatus').set_sensitive(prefs.get(__name__, 'stop-action', DEFAULT_STOP_ACTION) == STOP_SET_STATUS)
            self.cfgWindow.getWidget('txt-stopStatus').set_text(prefs.get(__name__, 'stop-status', DEFAULT_STOP_STATUS))
            self.cfgWindow.getWidget('txt-sanitizedWords').get_buffer().set_text(prefs.get(__name__, 'sanitized-words', DEFAULT_SANITIZED_WORDS))
            self.cfgWindow.getWidget('btn-ok').grab_focus()

        self.cfgWindow.show()


    def onRadToggled(self, btn):
        """ A radio button has been toggled """
        self.cfgWindow.getWidget('txt-stopStatus').set_sensitive(self.cfgWindow.getWidget('rad-stopSetStatus').get_active())


    def onBtnOk(self, btn):
        """ Save new preferences """
        prefs.set(__name__, 'status-msg', self.cfgWindow.getWidget('txt-status').get_text())
        prefs.set(__name__, 'update-on-paused', self.cfgWindow.getWidget('chk-updateOnPaused').get_active())
        prefs.set(__name__, 'update-when-away', self.cfgWindow.getWidget('chk-updateWhenAway').get_active())
        (start, end) = self.cfgWindow.getWidget('txt-sanitizedWords').get_buffer().get_bounds()
        prefs.set(__name__, 'sanitized-words', self.cfgWindow.getWidget('txt-sanitizedWords').get_buffer().get_text(start, end).strip())
        if self.cfgWindow.getWidget('rad-stopDoNothing').get_active():
            prefs.set(__name__, 'stop-action', STOP_DO_NOTHING)
        else:
            prefs.set(__name__, 'stop-action', STOP_SET_STATUS)
            prefs.set(__name__, 'stop-status', self.cfgWindow.getWidget('txt-stopStatus').get_text())
        self.cfgWindow.hide()
        # Update status
        if self.track is not None:
            self.status = self.__format(prefs.get(__name__, 'status-msg', DEFAULT_STATUS_MSG), self.track)
            if self.paused: self.setStatusMsg(_('%(status)s [paused]') % {'status': self.status})
            else:           self.setStatusMsg(self.status)


    def onBtnHelp(self, btn):
        """ Display a small help message box """
        import gui.help, media.track

        helpDlg = gui.help.HelpDlg(_(MOD_NAME))
        helpDlg.addSection(_('Description'),
                           _('This module detects any running instant messenger and updates your status with regards to the track '
                             'you are listening to. Supported messengers are:')
                           + '\n\n * ' + '\n * '.join(sorted([client[IM_NAME] for client in CLIENTS])))
        helpDlg.addSection(_('Customizing the Status'),
                           _('You can set the status to any text you want. Before setting it, the module replaces all fields of '
                             'the form {field} by their corresponding value. Available fields are:')
                           + '\n\n' + media.track.getFormatSpecialFields(False))
        helpDlg.addSection(_('Markup'),
                           _('You can use the Pango markup language to format the text. More information on that language is '
                             'available on the following web page:')
                           + '\n\nhttp://www.pygtk.org/pygtk2reference/pango-markup-language.html')
        helpDlg.addSection(_('Sanitization'),
                           _('You can define some words that to sanitize before using them to set your status. In this '
                             'case, the middle characters of matching words is automatically replaced with asterisks '
                             '(e.g., "Metallica - Live S**t Binge & Purge"). Put one word per line.'))
        helpDlg.show(self.cfgWindow)
Пример #26
0
'''
The start point of the client.
'''

from gui.window import Window

if __name__ == '__main__':
	window = Window()
	# testing
	for i in range(100):
		window._log.add_to_log("line"+str(i))
	window._contacts.load_list(("foo", "bar"))
	# end testing
	window.mainloop()
Пример #27
0
class MagnetSetup:
    """
    GUI handler for field setup
    """
    def __init__(self, main_window, parent):
        """Initialise the GUI window"""
        self.main_window = main_window
        self.parent = parent
        manipulators = {"magnet_setup_action":self.magnet_setup_action}
        self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable = E1101
                             parent,
                             data_file = self.share_dir+"magnet_setup.json",
                             manipulator_dict = manipulators)
        self.window.set_button_action("&Okay", self.okay_action)
        self.window.set_button_action("&Cancel", self.cancel_action)

    def okay_action(self):
        """Handle okay button press"""
        field_list_out = []
        field_frame = self.window.get_frame_dict("field_list", "vertical_frame")
        for frame in field_frame["children"]:
            try:
                name = frame["name"]
                scale_factor = float(frame["text_entry"].text_entry.GetText())
                field_list_out.append({"field_name":name,
                                       "scale_factor":scale_factor})
            except KeyError:
                pass
        self.main_window.lattice.set_fields(field_list_out)
        self.main_window.lattice.run_lattice()
        self.main_window.update_plot()
        self.window.close_window()
        self.main_window.magnet_setup = None
    
    def cancel_action(self):
        """Handle cancel button press"""
        self.window.close_window()
        self.main_window.magnet_setup = None

    def magnet_setup_action(self, item): # pylint: disable=W0613
        """Iterate over magnets and add a line per magnet (special)"""
        field_list = self.main_window.lattice.get_field_list()
        geometry_list = {
        "type":"vertical_frame",
        "layout":"close",
        "name":"field_list",
        "children":[]}
        if len(field_list) == 0:
            geometry_list["children"].append({"type":"label",
                    "name":"No fields in lattice",
                    "label_length":30})
            return geometry_list
        for field in field_list:
            geometry_list["children"].append({
              "type":"named_text_entry",
              "default_text":str(field["scale_factor"]),
              "label_length":10,
              "name":str(field["field_name"]),
              "tool_tip":"Longitudinal beta function"
            })
        return geometry_list

    share_dir = ""
Пример #28
0
 def viewer_window_provider(title):
     return Window(None, -3, -1, 3, 0, self.window.internal_renderer)
Пример #29
0
class OnlineGui(): # pylint: disable = R0902
    """Main frame for the online gui window"""
    def __init__(self, datacards):
        """Initialise the main window"""
        self.last = datetime.datetime.now()
        self.window = Window(ROOT.gClient.GetRoot(),
                             ROOT.gClient.GetRoot(),
                             SHARE_DIR+"online_gui.json")
        self._set_actions()
        self._docstore = None
        self._datacards = datacards
        self._draw_titles = Queue.Queue()
        for title in datacards["online_gui_default_canvases"]:
            self._draw_titles.put(title)
        self._canvases_read = Queue.Queue()
        self._canvases_draw = ThreadedValue([])
        self._redraw_target = None
        self._paused = ThreadedValue(False)
        rotate_tmp = self.window.get_text_entry("Rotate period", type(1.))
        self._rotate_period = ThreadedValue(rotate_tmp)
        reload_tmp = self.window.get_text_entry("Reload period", type(1.))
        self._reload_period = ThreadedValue(reload_tmp)
        self._poll_period = ThreadedValue(0.1)
        self._collections = ThreadedValue([])
        self._init_docstore()
        self._start_polling()

    def _set_actions(self):
        """
        Set up actions (responses to signals)
        """
        self.window.set_button_action("&Pause", self.pause_action)
        self.window.set_button_action("&Redraw", self.redraw_action)
        self.window.set_button_action("Re&load", self.reload_action)
        self.window.set_button_action("Re&connect", self.reconnect_action)
        self.window.set_button_action("E&xit", self.exit_action)
        self.window.set_button_action("&<", self.back_action)
        self.window.set_button_action("&>", self.forward_action)
        self.window.get_frame("canvas_options", "vertical_frame").\
                                                                Resize(200, 500)
        self.window.get_frame("canvas_select", "list_box").Resize(200, 200)
        self.window.set_action("canvas_select",
                               "list_box",
                               "SelectionChanged()",
                               self.canvas_select_action)
        self.window.set_action("Rotate period", "named_text_entry",
                               "ReturnPressed()", self.rotate_period_action)
        self.window.set_action("Reload period", "named_text_entry",
                               "ReturnPressed()", self.reload_period_action)

    def _init_docstore(self):
        """
        Initialise the docstore
        """
        datacards = self._datacards
        self._docstore = RootDocumentStore(
                  datacards["root_document_store_timeout"],
                  datacards["root_document_store_poll_time"], 10, 10)
        self._docstore.connect({"host":datacards["online_gui_host"],
                               "port":datacards["online_gui_port"]})

    def _start_polling(self):
        """
        Start polling the database and rotating the canvases
        """
        my_thread = threading.Thread(target=self._poll_canvas_draw,
                                     args=())
        my_thread.daemon = True
        my_thread.start()
        my_thread = threading.Thread(target=self._poll_docstore,
                                     args=())
        my_thread.daemon = True
        my_thread.start()

    def pause_action(self):
        """Handle a Pause/Unpause button press"""
        pause_button = self.window.get_frame("&Pause", "button")
        if self._paused.get_value():
            self._paused.set_value(False)
            pause_button.SetText("&Pause")
        else:
            self._paused.set_value(True)
            pause_button.SetText("&Play")

    def redraw_action(self):
        """
        Handle a Redraw button press

        Redraws self._redraw_target
        """
        if self._redraw_target == None:
            raise GuiError("No canvas to draw")
        self._do_redraw(self._redraw_target)

    def reload_action(self):
        """Handle a Reload button press"""
        self._reload()
        if self._redraw_target != None:
            go_back_fifo_queue(self._draw_titles)
            self._draw_next()

    def reconnect_action(self):
        """Handle a Reconnect button press"""
        self._docstore.disconnect()
        self._init_docstore()

    def exit_action(self):
        """Handle a Exit button press"""
        self._paused.set_value(True) # tell polling to wait
        time.sleep(self._poll_period.get_value()) # thinkapow
        self.window.close_window()

    def reload_period_action(self):
        """Handle a change to the reload period"""
        tmp_reload_period = self.window.get_text_entry("Reload period",
                                                       type(1.))
        tmp_reload_period = float(tmp_reload_period)
        self._reload_period.set_value(tmp_reload_period)

    def rotate_period_action(self):
        """Handle a change to the rotate period"""
        tmp_rotate_period = self.window.get_text_entry("Rotate period",
                                                       type(1.))
        tmp_rotate_period = float(tmp_rotate_period)
        self._rotate_period.set_value(tmp_rotate_period)

    def forward_action(self):
        """Handle a click on the > forward button"""
        self._draw_next()

    def back_action(self):
        """Handle a click on the < back button"""
        go_back_fifo_queue(self._draw_titles)
        go_back_fifo_queue(self._draw_titles)
        self._draw_next()

    def canvas_select_action(self):
        """Handle an update to the selected canvases"""
        selected = self._get_canvas_selected()
        new_draw_titles = Queue.Queue()
        for item in selected:
            new_draw_titles.put(item)
        self._draw_titles = new_draw_titles

    def _poll_canvas_draw(self):
        """
        Iterate over the canvas_draw queue, updating the GUI as appropriate

        * Update the queue from the canvas_read queue
        * Refresh the combo box with items in the canvases_draw queue
        """
        # poll_number = 0
        while True:
            # poll_number += 1
            self._draw_next()
            self._sleepish(self._rotate_period)
            # handle pause
            while self._paused.get_value():
                time.sleep(self._poll_period.get_value())

    def _draw_next(self):
        """
        Draw the next canvas in the selected queue
        """
        canvases_draw = self._filter_canvases(self._canvases_draw.get_value())
        if len(canvases_draw) > 0:
            try:
                title = self._draw_titles.get_nowait()
                new_title = copy.deepcopy(title)
                self._draw_titles.put(title)
                for wrap in canvases_draw:
                    if wrap.canvas_title() == new_title:
                        self._do_redraw(wrap)
                        break
            except Queue.Empty:
                pass # no canvas selected
            except ValueError:
                pass
        self._canvases_draw.set_value(canvases_draw)


    def _sleepish(self, sleep_length):
        """
        Sleep - but keep polling for changes to the sleep_length
        * sleep_length - threaded value containing numeric sleep time
        """
        time_slept = 0.
        poll_period = self._poll_period.get_value()
        while sleep_length.get_value() - time_slept > poll_period:
            time_slept += self._poll_period.get_value()
            time.sleep(poll_period)

    def _update_canvases_draw(self):
        """update canvases"""
        draw = [wrap.deepcopy() \
                           for wrap in generate_fifo_queue(self._canvases_read)]
        draw.sort(key = lambda wrap: wrap.sort_key())
        return draw

    def _do_redraw(self, wrap):
        """
        Draw the canvas wrap in the main_canvas
        """
        # wrap_copy is for ROOT
        wrap_copy = wrap.deepcopy()
        embedded_canvas = self.window.get_frame("main_canvas", "canvas")
        # this eats the wrap_copy TCanvas
        wrap_copy.canvas_wrapper.EmbedCanvas(embedded_canvas)
        embedded_canvas.GetCanvas().Update()
        # this _redraw_target is for the main thread
        self._redraw_target = wrap.deepcopy()

    def _poll_docstore(self):
        """
        Poll the doc store for documents
        """
        while True:
            print "poll_docstore"
            self._reload()
            self._sleepish(self._reload_period)
            # handle pause
            while self._paused.get_value():
                time.sleep(self._poll_period.get_value())

    def _reload(self):
        """
        Reload canvases; if the list of canvases changed, update the multiselect
        """
        self._reload_canvases()
        # now update GUI elements (each call iterates over the whole
        # _canvases_draw queue)
        self._update_canvas_select()

    def _update_canvas_select(self):
        """
        Update the list of canvases in the canvas_select frame
        """
        all_canvas_titles = [wrap.canvas_wrapper.GetCanvas().GetTitle() \
                           for wrap in generate_fifo_queue(self._canvases_read)]

        select_box = self.window.get_frame("canvas_select", "list_box")
        select_box.RemoveAll()
        for i, title in enumerate(all_canvas_titles):
            select_box.AddEntry(title, i)
        for title in generate_fifo_queue(self._draw_titles):
            try:
                index = all_canvas_titles.index(title)
                select_box.Select(index)
            except ValueError: # item was no longer in the select - ignore it
                pass
        go_back_fifo_queue(self._draw_titles)
        # ROOT doesn't like redrawing the histogram titles properly - need to
        # force it
        self.window.get_frame("canvas_select", "list_box").Resize(200, 10)
        self.window.get_frame("canvas_select", "list_box").Resize(200, 200)

    def _get_canvas_selected(self):
        """
        Get the list of canvases selected in the canvas_select frame
        """
        select_box = self.window.get_frame("canvas_select", "list_box")
        selected_root = ROOT.TList()
        selected = []
        select_box.GetSelectedEntries(selected_root)
        while selected_root.Last() != None:
            selected.insert(0, copy.deepcopy(selected_root.Last().GetText()))
            selected_root.RemoveLast()
        return selected

    def _reload_canvases(self):
        """
        Reload canvases from the docstore
        """
        # get all of the collections (one for each reducer)
        try:
            collections = self._docstore.collection_names()
        except (DocumentStoreException, SocketError):
            print "Failed to get collection names from the docstore"
            return
        self._collections.set_value(collections)
        temp_canvases = []
        # update "last accessed" timestamp
        self.last = datetime.datetime.now()
        # get new canvases
        for collection_name in collections:
            temp_canvases += self._get_new_canvases(collection_name)
        # purge any duplicate canvases
        filtered_canvases = self._filter_canvases(temp_canvases)
        # build a new queue and reassign _canvases_read
        canvases_read = Queue.Queue()
        for canvas in filtered_canvases:
            canvases_read.put_nowait(canvas)
        self._canvases_read = canvases_read
        self._collections.set_value(collections)

    def _get_new_canvases(self, collection_name):
        """
        Get a list of new canvases from the collection
        """
        try:
            doc_list = self._docstore.get_since(collection_name, self.last)
        except DocumentStoreException:
            print "Failed to get documents from the docstore"
            return []
        if len(doc_list) == 0:
            return []
        tree = doc_list[-1]["doc"]
        image_data = ROOT.MAUS.ImageData()
        tree.SetBranchAddress("data", image_data)
        if tree.GetEntries() == 0:
            return []
        tree.GetEntry()
        return CanvasRewrapped.new_list_from_image(collection_name,
                                                   image_data.GetImage())

    def _filter_canvases(self, new_canvases):
        """
        Enforce that we only have one copy with a given (collection, title)

        Note that we want to keep the item with the highest input_time if there
        is a choice
        """
        combined_list = [wrap.deepcopy() \
                           for wrap in generate_fifo_queue(self._canvases_read)]
        combined_list += new_canvases
        combined_list.sort(key=lambda wrap: wrap.sort_key())

        if len(combined_list) == 0:
            return []
        filtered_list = []
        for i, item_2 in enumerate(combined_list[1:]):
            item_1 = combined_list[i]
            if item_1.collection == item_2.collection and \
               item_1.canvas_title() == item_2.canvas_title():
                pass
            else:
                filtered_list.append(item_1)
        filtered_list.append(combined_list[-1])
        return filtered_list
Пример #30
0
 def main_window(title):
     return Window(title, -2, 0, 2, 0, self)
Пример #31
0
 def __init__(self, simulation):
     super(Application, self).__init__(sys.argv)
     self.frame = Window(simulation=simulation)
     self.sim = simulation
     self.frame.show()
Пример #32
0
class BeamSetup:
    """GUI window to setup a reference particle and beam ellipse"""
    def __init__(self, main_window, parent):
        """Initialise the window"""
        self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable = E1101
                             parent,
                             SHARE_DIR+"beam_setup.json")
        self.main_window = main_window
        self.parent = parent
        self.matrix_select = None
        self.matrix = None

        self.window.set_button_action("&Penn", self.penn_action)
        self.window.set_button_action("&Twiss", self.twiss_action)
        self.window.set_button_action("&Okay", self.okay_action)
        self.window.set_button_action("&Cancel", self.cancel_action)

    def twiss_action(self):
        """Handle Twiss button - open a window to set up Twiss parameters"""
        if self.matrix_select == None:
            self.matrix_select = TwissSetup(self, self.parent)

    def penn_action(self):
        """Handle Penn button - open a window to set up Penn parameters"""
        if self.matrix_select == None:
            self.matrix_select = PennSetup(self, self.parent)

    def okay_action(self):
        """
        Handle Okay button - set the beam in lattice and then close the window
        """
        if self.matrix_select != None:
            print "Close the matrix_select window"
            return
        self.main_window.lattice.set_beam(self.get_reference(),
                                          self.get_matrix())   
        self.main_window.lattice.run_lattice()
        self.main_window.update_plot()
        self.window.close_window()
        self.main_window.beam_setup = None
    
    def cancel_action(self):
        """
        Handle Cancel button - just close the window
        """
        if self.matrix_select != None:
            print "Close the matrix_select window"
            return
        self.window.close_window()
        self.main_window.beam_setup = None

    def set_matrix(self, matrix):
        """
        Set the beam matrix (updating GUI elements)
        - matrix a maus_cpp.covariance_matrix.CovarianceMatrix object
        """
        self.matrix = matrix
        for i, var_i in enumerate(["t", "e", "x", "px", "y", "py"]):
            for j, var_j in enumerate(["t", "e", "x", "px", "y", "py"]):
                value = matrix.get_element(i+1, j+1)
                self.window.set_text_entry(var_i+var_j, value)

    def get_matrix(self):
        """
        Get the beam matrix (reading from GUI elements)

        Returns a maus_cpp.covariance_matrix.CovarianceMatrix object
        """
        np_matrix = numpy.zeros([6, 6])
        for i, var_i in enumerate(["t", "e", "x", "px", "y", "py"]):
            for j, var_j in enumerate(["t", "e", "x", "px", "y", "py"]):
                value1 = self.window.get_text_entry(var_i+var_j, type(1.))
                value2 = self.window.get_text_entry(var_j+var_i, type(1.))
                delta = abs(value1 - value2)
                if delta > 1e-6:
                    err = "Matrix has non-symmetric element Cov("+\
                            var_i+","+var_j+") with delta "+str(delta)+"."
                    err += "This element must be symmetric - upper "+\
                             "diagonal should be equal to lower diagonal."
                    raise GuiError(err)
                else:
                    np_matrix[i, j] = value1
        evals = numpy.linalg.eigvals(np_matrix)
        if not numpy.all(evals > 0):
            evals = [i for i in evals]
            raise GuiError("Beam ellipse should be positive definite but "+\
                           " eigenvalues were not all positive: "+str(evals))
        return maus_cpp.covariance_matrix.create_from_matrix(np_matrix)

    def set_reference(self, ref_hit):
        """
        Get the reference particle (writing to GUI elements)
        - ref_hit an xboa.Hit.Hit object
        """
        for var in ["x", "y", "z", "px", "py", "pz", "pid"]:
            self.window.set_text_entry(var, ref_hit[var])

    def get_reference(self):
        """
        Get the reference particle (reading from GUI elements)

        Returns an xboa.Hit.Hit object
        """
        ref_dict = {}
        for var in ["x", "y", "z", "px", "py", "pz"]: 
            var_dict = self.window.get_frame_dict(var, "named_text_entry")
            ref_dict[var] = float(var_dict["text_entry"].text_entry.GetText())
        pid_dict = self.window.get_frame_dict("pid", "named_text_entry")
        try:
            ref_dict["pid"] = int(pid_dict["text_entry"].text_entry.GetText())
            ref_dict["mass"] = common.pdg_pid_to_mass[abs(ref_dict["pid"])]
            ref_dict["charge"] = common.pdg_pid_to_charge[abs(ref_dict["pid"])]
        except KeyError:
            raise GuiError("Did not recognise reference particle pid")
        try:
            hit = Hit.new_from_dict(ref_dict, "energy")
        except Exception:
            raise GuiError("Failed to generate a reference particle")
        return hit
Пример #33
0
class Covers(modules.ThreadedModule):
    def __init__(self):
        """ Constructor """
        handlers = {
            consts.MSG_EVT_APP_QUIT: self.onModUnloaded,
            consts.MSG_EVT_NEW_TRACK: self.onNewTrack,
            consts.MSG_EVT_MOD_LOADED: self.onModLoaded,
            consts.MSG_EVT_APP_STARTED: self.onModLoaded,
            consts.MSG_EVT_MOD_UNLOADED: self.onModUnloaded,
        }

        modules.ThreadedModule.__init__(self, handlers)

    def _generateCover(self, inFile, outFile, format, max_width, max_height):
        from PIL import Image

        try:
            # Open the image
            cover = Image.open(inFile)
            width = cover.size[0]
            height = cover.size[1]
            newWidth, newHeight = tools.resize(width, height, max_width,
                                               max_height)

            cover = cover.resize((newWidth, newHeight), Image.ANTIALIAS)
            cover.save(outFile, format)
        except Exception:
            # This message will probably be displayed for the thumbnail and the big cover.
            logger.error(
                '[%s] An error occurred while generating the cover for "%s"\n\n%s'
                % (MOD_NAME, inFile, traceback.format_exc()))
            # Remove corrupted file.
            tools.remove(outFile)

    def generateFullSizeCover(self, inFile, outFile, format):
        """ Resize inFile if needed, and write it to outFile (outFile and inFile may be equal) """
        self._generateCover(inFile, outFile, format, FULL_SIZE_COVER_WIDTH,
                            FULL_SIZE_COVER_HEIGHT)

    def generateThumbnail(self, inFile, outFile, format):
        """
        Generate a thumbnail from inFile (e.g., resize it) and write it to
        outFile (outFile and inFile may be equal).
        """
        self._generateCover(inFile, outFile, format, THUMBNAIL_WIDTH,
                            THUMBNAIL_HEIGHT)

    def getUserCover(self, trackPath):
        """ Return the path to a cover file in trackPath, None if no cover found """
        # Create a dictionary with candidates
        candidates = {}
        for (file, path) in tools.listDir(trackPath, True):
            (name, ext) = os.path.splitext(file.lower())
            if ext in ACCEPTED_FILE_FORMATS:
                candidates[name] = path

        # Check each possible name using the its index in the list as its priority
        for name in prefs.get(__name__, 'user-cover-filenames',
                              PREFS_DFT_USER_COVER_FILENAMES):
            if name in candidates:
                return candidates[name]

            if name == '*' and len(candidates) != 0:
                return next(iter(candidates.values()))

        return None

    def getFromCache(self, artist, album):
        """ Return the path to the cached cover, or None if it's not cached """
        cachePath = os.path.join(self.cacheRootPath, str(abs(hash(artist))))
        cacheIdxPath = os.path.join(cachePath, 'INDEX')

        try:
            cacheIdx = tools.pickleLoad(cacheIdxPath)
            cover = os.path.join(cachePath, cacheIdx[artist + album])
            if os.path.exists(cover):
                return cover
        except:
            pass

        return None

    def __getFromInternet(self, artist, album):
        """
            Try to download the cover from the Internet
            If successful, add it to the cache and return the path to it
            Otherwise, return None
        """
        import socket, urllib.request, urllib.error, urllib.parse

        # Make sure to not be blocked by the request
        socket.setdefaulttimeout(consts.socketTimeout)

        # Request information to Last.fm
        # Beware of UTF-8 characters: we need to percent-encode all characters
        try:
            url = 'http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=%s&artist=%s&album=%s' % (
                AS_API_KEY, tools.percentEncode(artist),
                tools.percentEncode(album))
            request = urllib.request.Request(
                url, headers={'User-Agent': USER_AGENT})
            stream = urllib.request.urlopen(request)
            data = stream.read().decode('utf-8')
        except urllib.error.HTTPError as err:
            if err.code == 400:
                logger.error('[%s] No known cover for %s / %s' %
                             (MOD_NAME, artist, album))
            else:
                logger.error('[%s] Information request failed\n\n%s' %
                             (MOD_NAME, traceback.format_exc()))
            return None
        except urllib.error.URLError:
            logger.info('[%s] Could not fetch cover. No internet connection.' %
                        MOD_NAME)
            return None
        except:
            logger.error('[%s] Information request failed\n\n%s' %
                         (MOD_NAME, traceback.format_exc()))
            return None

        # Extract the URL to the cover image
        malformed = True
        startIdx = data.find(AS_TAG_START)
        endIdx = data.find(AS_TAG_END, startIdx)
        if startIdx != -1 and endIdx != -1:
            coverURL = data[startIdx + len(AS_TAG_START):endIdx]
            coverFormat = os.path.splitext(coverURL)[1].lower()
            if coverURL.startswith(
                ('http://',
                 'https://')) and coverFormat in ACCEPTED_FILE_FORMATS:
                malformed = False

        if malformed:
            ## Do not show the data in the log every time no cover is found
            if coverURL:
                logger.error('[%s] Received malformed data\n\n%s' %
                             (MOD_NAME, data))
            return None

        # Download the cover image
        try:
            request = urllib.request.Request(
                coverURL, headers={'User-Agent': USER_AGENT})
            stream = urllib.request.urlopen(request)
            data = stream.read()

            if len(data) < 1024:
                raise Exception(
                    'The cover image seems incorrect (%u bytes is too small)' %
                    len(data))
        except:
            logger.error('[%s] Cover image request failed' % MOD_NAME)
            return None

        # So far, so good: let's cache the image
        cachePath = os.path.join(self.cacheRootPath, str(abs(hash(artist))))
        cacheIdxPath = os.path.join(cachePath, 'INDEX')

        if not os.path.exists(cachePath):
            os.mkdir(cachePath)

        try:
            cacheIdx = tools.pickleLoad(cacheIdxPath)
        except:
            cacheIdx = {}

        nextInt = len(cacheIdx) + 1
        filename = str(nextInt) + coverFormat
        coverPath = os.path.join(cachePath, filename)

        cacheIdx[artist + album] = filename
        tools.pickleSave(cacheIdxPath, cacheIdx)

        try:
            output = open(coverPath, 'wb')
            output.write(data)
            output.close()
            return coverPath
        except:
            logger.error('[%s] Could not save the downloaded cover\n\n%s' %
                         (MOD_NAME, traceback.format_exc()))

        return None

    def getFromInternet(self, artist, album):
        """ Wrapper for __getFromInternet(), manage blacklist """
        # If we already tried without success, don't try again
        if (artist, album) in self.coverBlacklist:
            return None

        # Otherwise, try to download the cover
        cover = self.__getFromInternet(artist, album)

        # If the download failed, blacklist the album
        if cover is None:
            self.coverBlacklist[(artist, album)] = None

        return cover

    # --== Message handlers ==--

    def onModLoaded(self):
        """ The module has been loaded """
        self.cfgWin = None  # Configuration window
        self.coverMap = {}  # Store covers previously requested
        self.currTrack = None  # The current track being played, if any
        self.cacheRootPath = os.path.join(
            consts.dirCfg, MOD_NAME)  # Local cache for Internet covers
        self.coverBlacklist = {
        }  # When a cover cannot be downloaded, avoid requesting it again

        if not os.path.exists(self.cacheRootPath):
            os.mkdir(self.cacheRootPath)

    def onModUnloaded(self):
        """ The module has been unloaded """
        if self.currTrack is not None:
            modules.postMsg(
                consts.MSG_CMD_SET_COVER, {
                    'track': self.currTrack,
                    'pathThumbnail': None,
                    'pathFullSize': None
                })

        # Delete covers that have been generated by this module
        for covers in self.coverMap.values():
            if os.path.exists(covers[CVR_THUMB]):
                os.remove(covers[CVR_THUMB])
            if os.path.exists(covers[CVR_FULL]):
                os.remove(covers[CVR_FULL])
        self.coverMap = None

        # Delete blacklist
        self.coverBlacklist = None

    def onNewTrack(self, track):
        """ A new track is being played, try to retrieve the corresponding cover """
        # Make sure we have enough information
        if track.getArtist() == consts.UNKNOWN_ARTIST or track.getAlbum(
        ) == consts.UNKNOWN_ALBUM:
            modules.postMsg(consts.MSG_CMD_SET_COVER, {
                'track': track,
                'pathThumbnail': None,
                'pathFullSize': None
            })
            return

        album = track.getAlbum().lower()
        artist = track.getArtist().lower()
        rawCover = None
        self.currTrack = track

        # Let's see whether we already have the cover
        if (artist, album) in self.coverMap:
            covers = self.coverMap[(artist, album)]
            pathFullSize = covers[CVR_FULL]
            pathThumbnail = covers[CVR_THUMB]

            # Make sure the files are still there
            if os.path.exists(pathThumbnail) and os.path.exists(pathFullSize):
                modules.postMsg(
                    consts.MSG_CMD_SET_COVER, {
                        'track': track,
                        'pathThumbnail': pathThumbnail,
                        'pathFullSize': pathFullSize
                    })
                return

        # Should we check for a user cover?
        if not prefs.get(__name__, 'download-covers', PREFS_DFT_DOWNLOAD_COVERS)        \
            or prefs.get(__name__, 'prefer-user-covers', PREFS_DFT_PREFER_USER_COVERS):
            rawCover = self.getUserCover(os.path.dirname(track.getFilePath()))

        # Is it in our cache?
        if rawCover is None:
            rawCover = self.getFromCache(artist, album)

        # If we still don't have a cover, maybe we can try to download it
        if rawCover is None:
            modules.postMsg(consts.MSG_CMD_SET_COVER, {
                'track': track,
                'pathThumbnail': None,
                'pathFullSize': None
            })

            if prefs.get(__name__, 'download-covers',
                         PREFS_DFT_DOWNLOAD_COVERS):
                rawCover = self.getFromInternet(artist, album)

        # If we still don't have a cover, too bad
        # Otherwise, generate a thumbnail and a full size cover, and add it to our cover map
        if rawCover is not None:
            import tempfile

            thumbnail = tempfile.mktemp() + '.png'
            fullSizeCover = tempfile.mktemp() + '.png'
            self.generateThumbnail(rawCover, thumbnail, 'PNG')
            self.generateFullSizeCover(rawCover, fullSizeCover, 'PNG')
            if os.path.exists(thumbnail) and os.path.exists(fullSizeCover):
                self.coverMap[(artist, album)] = (thumbnail, fullSizeCover)
                modules.postMsg(
                    consts.MSG_CMD_SET_COVER, {
                        'track': track,
                        'pathThumbnail': thumbnail,
                        'pathFullSize': fullSizeCover
                    })
            else:
                modules.postMsg(consts.MSG_CMD_SET_COVER, {
                    'track': track,
                    'pathThumbnail': None,
                    'pathFullSize': None
                })

    # --== Configuration ==--

    def configure(self, parent):
        """ Show the configuration window """
        if self.cfgWin is None:
            from gui.window import Window

            self.cfgWin = Window('Covers.ui', 'vbox1', __name__,
                                 MOD_INFO[modules.MODINFO_L10N], 320, 265)
            self.cfgWin.getWidget('btn-ok').connect('clicked', self.onBtnOk)
            self.cfgWin.getWidget('img-lastfm').set_from_file(
                os.path.join(consts.dirPix, 'audioscrobbler.png'))
            self.cfgWin.getWidget('btn-help').connect('clicked',
                                                      self.onBtnHelp)
            self.cfgWin.getWidget('chk-downloadCovers').connect(
                'toggled', self.onDownloadCoversToggled)
            self.cfgWin.getWidget('btn-cancel').connect(
                'clicked', lambda btn: self.cfgWin.hide())

        if not self.cfgWin.isVisible():
            downloadCovers = prefs.get(__name__, 'download-covers',
                                       PREFS_DFT_DOWNLOAD_COVERS)
            preferUserCovers = prefs.get(__name__, 'prefer-user-covers',
                                         PREFS_DFT_PREFER_USER_COVERS)
            userCoverFilenames = prefs.get(__name__, 'user-cover-filenames',
                                           PREFS_DFT_USER_COVER_FILENAMES)

            self.cfgWin.getWidget('btn-ok').grab_focus()
            self.cfgWin.getWidget('txt-filenames').set_text(
                ', '.join(userCoverFilenames))
            self.cfgWin.getWidget('chk-downloadCovers').set_active(
                downloadCovers)
            self.cfgWin.getWidget('chk-preferUserCovers').set_active(
                preferUserCovers)
            self.cfgWin.getWidget('chk-preferUserCovers').set_sensitive(
                downloadCovers)

        self.cfgWin.show()

    def onBtnOk(self, btn):
        """ Save configuration """
        downloadCovers = self.cfgWin.getWidget(
            'chk-downloadCovers').get_active()
        preferUserCovers = self.cfgWin.getWidget(
            'chk-preferUserCovers').get_active()
        userCoverFilenames = [
            word.strip() for word in self.cfgWin.getWidget(
                'txt-filenames').get_text().split(',')
        ]

        prefs.set(__name__, 'download-covers', downloadCovers)
        prefs.set(__name__, 'prefer-user-covers', preferUserCovers)
        prefs.set(__name__, 'user-cover-filenames', userCoverFilenames)

        self.cfgWin.hide()

    def onDownloadCoversToggled(self, downloadCovers):
        """ Toggle the "prefer user covers" checkbox according to the state of the "download covers" one """
        self.cfgWin.getWidget('chk-preferUserCovers').set_sensitive(
            downloadCovers.get_active())

    def onBtnHelp(self, btn):
        """ Display a small help message box """
        from gui import help

        helpDlg = help.HelpDlg(MOD_INFO[modules.MODINFO_L10N])
        helpDlg.addSection(
            _('Description'),
            _('This module displays the cover of the album the current track comes from. Covers '
              'may be loaded from local pictures, located in the same directory as the current '
              'track, or may be downloaded from the Internet.'))
        helpDlg.addSection(
            _('User Covers'),
            _('A user cover is a picture located in the same directory as the current track. '
              'When specifying filenames, you do not need to provide file extensions, supported '
              'file formats (%s) are automatically used.' %
              ', '.join(ACCEPTED_FILE_FORMATS.keys())))
        helpDlg.addSection(
            _('Internet Covers'),
            _('Covers may be downloaded from the Internet, based on the tags of the current track. '
              'You can ask to always prefer user covers to Internet ones. In this case, if a user '
              'cover exists for the current track, it is used. If there is none, the cover is downloaded.'
              ))
        helpDlg.show(self.cfgWin)
Пример #34
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from PyQt5 import QtWidgets

from gui.window import Window

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())
Пример #35
0
 def OnInit(self):
     window = Window(title="MusicFun", size=(880, 480))
     window.Show()
     return True
Пример #36
0
class TwissSetup:
    """GUI window to setup a beam according to 2D Twiss parameterisation"""
    def __init__(self, beam_setup, root_frame):
        """Initialise the window"""
        self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable = E1101
                             root_frame,
                             SHARE_DIR+"twiss_setup.json")
        self.beam_setup = beam_setup
        self.window.set_button_action("&Okay", self.okay_action)
        self.window.set_button_action("&Cancel", self.cancel_action)

    def okay_action(self):
        """Handle a click on the Okay button, building the beam matrix"""
        ref = self.beam_setup.get_reference()
        matrix = maus_cpp.covariance_matrix.create_from_twiss_parameters(
          mass = ref['mass'],
          momentum = ref['p'],
          emittance_x = self.window.get_text_entry("emittance_x", type(1.)),
          beta_x = self.window.get_text_entry("beta_x", type(1.)),
          emittance_y = self.window.get_text_entry("emittance_y", type(1.)),
          beta_y = self.window.get_text_entry("beta_y", type(1.)),
          emittance_l = self.window.get_text_entry("emittance_l", type(1.)),
          beta_l = self.window.get_text_entry("beta_l", type(1.)),
          alpha_x = self.window.get_text_entry("alpha_x", type(1.)),
          alpha_y = self.window.get_text_entry("alpha_y", type(1.)),
          alpha_l = self.window.get_text_entry("alpha_l", type(1.)),
          dispersion_x = self.window.get_text_entry("disp_x", type(1.)),
          dispersion_prime_x = self.window.get_text_entry("disp_prime_x",
                                                          type(1.)),
          dispersion_y = self.window.get_text_entry("disp_y", type(1.)),
          dispersion_prime_y = self.window.get_text_entry("disp_prime_y",
                                                          type(1.))
        )
        self.beam_setup.set_matrix(matrix)
        self.beam_setup.get_matrix() # check for consistency
        self.window.close_window()
        self.beam_setup.matrix_select = None

    def cancel_action(self):
        """Handle a click on the Cancel button"""
        self.window.close_window()
        self.beam_setup.matrix_select = None
Пример #37
0
class PlotSetup():
    """
    GUI handler for defining data to be plotted
    """
    def __init__(self, main_window, parent, selected):
        """
        Initialise the window
        """
        self.main_window = main_window
        self.parent = parent
        self.selected = selected
        self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable = E1101
                             parent,
                             self.share_dir+"plot_setup.json")
        for i, item in enumerate(self.selected):
            self.window.set_action("variable_type_"+str(i), "drop_down",
                                  "Selected(Int_t)", self.select_action)
            type_frame = self.window.get_frame("variable_type_"+str(i),
                                               "drop_down")
            type_frame.Select(item["variable_type"])
        self.window.set_button_action("&Okay", self.okay_action)
        self.window.set_button_action("&Cancel", self.cancel_action)

    def okay_action(self):
        """
        Handle Okay button press; get the plot selection and push it to the
        main window
        """
        type_int = self.window.get_frame_dict("variable_type_0",
                                             "drop_down")["frame"].GetSelected()
        first_int = self.window.get_frame_dict("first_var_0",
                                            "drop_down")["frame"].GetSelected()
        plot_apertures = self.window.get_frame("plot_apertures",
                                               "check_button").IsOn()
        if type_int != 0 and first_int == 0:
            raise GuiError("Please select plot variable")
        self.main_window.plot_setup_options = [{
            "variable_type":type_int,
            "first_var":first_int,
            "plot_apertures":plot_apertures
        }]
        self.main_window.update_plot()
        self.window.close_window()
        self.main_window.plot_setup = None
    
    def cancel_action(self):
        """
        Handle Cancel button press; just close the window
        """
        self.window.close_window()
        self.main_window.plot_setup = None

    def select_action(self):
        """
        Dynamically change the list of items in first_var depending on
        variable_type
        """
        for i, item in enumerate(self.selected):
            type_select = self.window.get_frame_dict("variable_type_"+str(i),
                                                     "drop_down")["frame"]
            first_var_select = self.window.get_frame_dict("first_var_"+str(i),
                                                    "drop_down")["frame"]
            selected_type_int = type_select.GetSelected()
            selected_type_str = self.type_list[selected_type_int]
            var_list_name = self.type_variables_dict[selected_type_str][0]
            var_list = self.select_lists[var_list_name]
            first_var_select.RemoveAll()
            for i, entry in enumerate(var_list):
                first_var_select.AddEntry(entry, i)
            first_var_select.Select(item["first_var"])

    @staticmethod
    def get_variable_type(options):
        """
        Return a string corresponding to integer variable_type selected
        """
        var_type_int = options[0]["variable_type"]
        return PlotSetup.type_list[var_type_int]

    @staticmethod
    def get_first_var(options):
        """
        Return a string corresponding to integer first_var selected
        """
        var_type_string = PlotSetup.get_variable_type(options)
        select_list_key = PlotSetup.type_variables_dict[var_type_string][0]
        select_list = PlotSetup.select_lists[select_list_key]
        first_var_int = options[0]["first_var"]
        return select_list[first_var_int]

    my_hit_get_variables = [var for var in Hit.get_variables() if len(var)]

    type_list = [
        "<Select plot type>",
        "mean",
        "envelope",
        "RMS",
        "beta",
        "alpha",
        "gamma",
        "emittance",
        "dispersion",
        "dispersion_prime"
    ]

    select_lists = {
        "no_var":[
            "",
        ], "optics_var":[
            "<Select plot variable>",
            "x",
            "y",
            "transverse",
            "longitudinal"
        ], "physics_var":[
            "<Select plot variable>"
        ]+my_hit_get_variables, "kinematic_var":[
            "<Select plot variable>",
            "x",
            "y",
            "px",
            "py",
            "t",
            "energy"
        ], "disp_var":[
            "<Select plot variable>",
            "x",
            "y"
        ]
    }

    type_variables_dict = {
        "<Select plot type>":["no_var"],
        "mean":["physics_var"],
        "envelope":["kinematic_var"],
        "RMS":["kinematic_var"],
        "beta":["optics_var"],
        "alpha":["optics_var"],
        "gamma":["optics_var"],
        "emittance":["optics_var"],
        "dispersion":["disp_var"],
        "dispersion_prime":["disp_var"],
    }

    share_dir = ""
Пример #38
0
class PlotSetup():
    """
    GUI handler for defining data to be plotted
    """
    def __init__(self, main_window, parent, selected):
        """
        Initialise the window
        """
        self.main_window = main_window
        self.parent = parent
        self.selected = selected
        self.window = Window(
            ROOT.gClient.GetRoot(),  # pylint: disable = E1101
            parent,
            self.share_dir + "plot_setup.json")
        for i, item in enumerate(self.selected):
            self.window.set_action("variable_type_" + str(i), "drop_down",
                                   "Selected(Int_t)", self.select_action)
            type_frame = self.window.get_frame("variable_type_" + str(i),
                                               "drop_down")
            type_frame.Select(item["variable_type"])
        self.window.set_button_action("&Okay", self.okay_action)
        self.window.set_button_action("&Cancel", self.cancel_action)

    def okay_action(self):
        """
        Handle Okay button press; get the plot selection and push it to the
        main window
        """
        type_int = self.window.get_frame_dict(
            "variable_type_0", "drop_down")["frame"].GetSelected()
        first_int = self.window.get_frame_dict(
            "first_var_0", "drop_down")["frame"].GetSelected()
        plot_apertures = self.window.get_frame("plot_apertures",
                                               "check_button").IsOn()
        if type_int != 0 and first_int == 0:
            raise GuiError("Please select plot variable")
        self.main_window.plot_setup_options = [{
            "variable_type": type_int,
            "first_var": first_int,
            "plot_apertures": plot_apertures
        }]
        self.main_window.update_plot()
        self.window.close_window()
        self.main_window.plot_setup = None

    def cancel_action(self):
        """
        Handle Cancel button press; just close the window
        """
        self.window.close_window()
        self.main_window.plot_setup = None

    def select_action(self):
        """
        Dynamically change the list of items in first_var depending on
        variable_type
        """
        for i, item in enumerate(self.selected):
            type_select = self.window.get_frame_dict("variable_type_" + str(i),
                                                     "drop_down")["frame"]
            first_var_select = self.window.get_frame_dict(
                "first_var_" + str(i), "drop_down")["frame"]
            selected_type_int = type_select.GetSelected()
            selected_type_str = self.type_list[selected_type_int]
            var_list_name = self.type_variables_dict[selected_type_str][0]
            var_list = self.select_lists[var_list_name]
            first_var_select.RemoveAll()
            for i, entry in enumerate(var_list):
                first_var_select.AddEntry(entry, i)
            first_var_select.Select(item["first_var"])

    @staticmethod
    def get_variable_type(options):
        """
        Return a string corresponding to integer variable_type selected
        """
        var_type_int = options[0]["variable_type"]
        return PlotSetup.type_list[var_type_int]

    @staticmethod
    def get_first_var(options):
        """
        Return a string corresponding to integer first_var selected
        """
        var_type_string = PlotSetup.get_variable_type(options)
        select_list_key = PlotSetup.type_variables_dict[var_type_string][0]
        select_list = PlotSetup.select_lists[select_list_key]
        first_var_int = options[0]["first_var"]
        return select_list[first_var_int]

    my_hit_get_variables = [var for var in Hit.get_variables() if len(var)]

    type_list = [
        "<Select plot type>", "mean", "envelope", "RMS", "beta", "alpha",
        "gamma", "emittance", "dispersion", "dispersion_prime"
    ]

    select_lists = {
        "no_var": [
            "",
        ],
        "optics_var":
        ["<Select plot variable>", "x", "y", "transverse", "longitudinal"],
        "physics_var": ["<Select plot variable>"] + my_hit_get_variables,
        "kinematic_var":
        ["<Select plot variable>", "x", "y", "px", "py", "t", "energy"],
        "disp_var": ["<Select plot variable>", "x", "y"]
    }

    type_variables_dict = {
        "<Select plot type>": ["no_var"],
        "mean": ["physics_var"],
        "envelope": ["kinematic_var"],
        "RMS": ["kinematic_var"],
        "beta": ["optics_var"],
        "alpha": ["optics_var"],
        "gamma": ["optics_var"],
        "emittance": ["optics_var"],
        "dispersion": ["disp_var"],
        "dispersion_prime": ["disp_var"],
    }

    share_dir = ""
Пример #39
0
from pyglet import app

from gui.models.movable import MovableMixin
from gui.window import Window

if __name__ == "__main__":
    win = Window(width=1024, height=768)
    button = MovableMixin(10, 100, 10, 100)
    win.add_component(button)
    app.run()
Пример #40
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "JuanDavid"
__date__ = "$29/07/2015 08:44:56 PM$"

from gui.window import Window

if __name__ == "__main__":
    try:
        window = Window()
    except Exception as e:
        print e.message
Пример #41
0
 def plot_window_provider(title):
     return Window(title, 3, 4 + len("Plot"), 0, 5 + len("Back"),
                   self.window.internal_renderer)
Пример #42
0
class BeamSetup:
    """GUI window to setup a reference particle and beam ellipse"""
    def __init__(self, main_window, parent):
        """Initialise the window"""
        self.window = Window(
            ROOT.gClient.GetRoot(),  # pylint: disable = E1101
            parent,
            SHARE_DIR + "beam_setup.json")
        self.main_window = main_window
        self.parent = parent
        self.matrix_select = None
        self.matrix = None

        self.window.set_button_action("&Penn", self.penn_action)
        self.window.set_button_action("&Twiss", self.twiss_action)
        self.window.set_button_action("&Okay", self.okay_action)
        self.window.set_button_action("&Cancel", self.cancel_action)

    def twiss_action(self):
        """Handle Twiss button - open a window to set up Twiss parameters"""
        if self.matrix_select == None:
            self.matrix_select = TwissSetup(self, self.parent)

    def penn_action(self):
        """Handle Penn button - open a window to set up Penn parameters"""
        if self.matrix_select == None:
            self.matrix_select = PennSetup(self, self.parent)

    def okay_action(self):
        """
        Handle Okay button - set the beam in lattice and then close the window
        """
        if self.matrix_select != None:
            print "Close the matrix_select window"
            return
        self.main_window.lattice.set_beam(self.get_reference(),
                                          self.get_matrix())
        self.main_window.lattice.run_lattice()
        self.main_window.update_plot()
        self.window.close_window()
        self.main_window.beam_setup = None

    def cancel_action(self):
        """
        Handle Cancel button - just close the window
        """
        if self.matrix_select != None:
            print "Close the matrix_select window"
            return
        self.window.close_window()
        self.main_window.beam_setup = None

    def set_matrix(self, matrix):
        """
        Set the beam matrix (updating GUI elements)
        - matrix a maus_cpp.covariance_matrix.CovarianceMatrix object
        """
        self.matrix = matrix
        for i, var_i in enumerate(["t", "e", "x", "px", "y", "py"]):
            for j, var_j in enumerate(["t", "e", "x", "px", "y", "py"]):
                value = matrix.get_element(i + 1, j + 1)
                self.window.set_text_entry(var_i + var_j, value)

    def get_matrix(self):
        """
        Get the beam matrix (reading from GUI elements)

        Returns a maus_cpp.covariance_matrix.CovarianceMatrix object
        """
        np_matrix = numpy.zeros([6, 6])
        for i, var_i in enumerate(["t", "e", "x", "px", "y", "py"]):
            for j, var_j in enumerate(["t", "e", "x", "px", "y", "py"]):
                value1 = self.window.get_text_entry(var_i + var_j, type(1.))
                value2 = self.window.get_text_entry(var_j + var_i, type(1.))
                delta = abs(value1 - value2)
                if delta > 1e-6:
                    err = "Matrix has non-symmetric element Cov("+\
                            var_i+","+var_j+") with delta "+str(delta)+"."
                    err += "This element must be symmetric - upper "+\
                             "diagonal should be equal to lower diagonal."
                    raise GuiError(err)
                else:
                    np_matrix[i, j] = value1
        evals = numpy.linalg.eigvals(np_matrix)
        if not numpy.all(evals > 0):
            evals = [i for i in evals]
            raise GuiError("Beam ellipse should be positive definite but "+\
                           " eigenvalues were not all positive: "+str(evals))
        return maus_cpp.covariance_matrix.create_from_matrix(np_matrix)

    def set_reference(self, ref_hit):
        """
        Get the reference particle (writing to GUI elements)
        - ref_hit an xboa.Hit.Hit object
        """
        for var in ["x", "y", "z", "px", "py", "pz", "pid"]:
            self.window.set_text_entry(var, ref_hit[var])

    def get_reference(self):
        """
        Get the reference particle (reading from GUI elements)

        Returns an xboa.Hit.Hit object
        """
        ref_dict = {}
        for var in ["x", "y", "z", "px", "py", "pz"]:
            var_dict = self.window.get_frame_dict(var, "named_text_entry")
            ref_dict[var] = float(var_dict["text_entry"].text_entry.GetText())
        pid_dict = self.window.get_frame_dict("pid", "named_text_entry")
        try:
            ref_dict["pid"] = int(pid_dict["text_entry"].text_entry.GetText())
            ref_dict["mass"] = common.pdg_pid_to_mass[abs(ref_dict["pid"])]
            ref_dict["charge"] = common.pdg_pid_to_charge[abs(ref_dict["pid"])]
        except KeyError:
            raise GuiError("Did not recognise reference particle pid")
        try:
            hit = Hit.new_from_dict(ref_dict, "energy")
        except Exception:
            raise GuiError("Failed to generate a reference particle")
        return hit
Пример #43
0
    def run(self):
        print("Initialized the application @app class")
        window_generator = WindowGenerator()
        windows = window_generator.define_windows()
        # set main menu as starting window
        current_params = window_generator.get_windowparameters_by_title(windows, "Raspberry Pi Gaming Station")
        # initalize pygame submodules
        os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0"
        pygame.init()
        # disable mouse cursor
        pygame.mouse.set_visible(0)
        # create a pygame default window
        info = pygame.display.Info()
        screen = pygame.display.set_mode((info.current_w, info.current_h), pygame.NOFRAME)
        while True:
            current_window = Window(screen=screen, 
                                    title=current_params.title, 
                                    choices=current_params.options, 
                                    extend_window=current_params.extend_window)
            result = current_window.display()
            if result == "Exit":
                current_params = window_generator.get_windowparameters_by_id(windows, current_params.previous_id)
                if current_params == None:
                    #TODO: ask to shutdown the system
                    break
            elif '.' in result:
                cm = ControlManager(platform=current_params.title.lower())
                cm.restore_control_config()
                # run a game
                gm = GameRunner(platform=current_params.title, file_name=result)
                gm.run()
            else:
                if result == "Start":
                    result = "Platforms"
                new_params = window_generator.get_windowparameters_by_title(windows, result)
                if new_params != None:
                    # if the window is a control window
                    current_params = new_params
                # figure out how to distinguish control from hotkeys
                elif current_params.title == "Hotkeys":
                    current_params.refresh_hotkeys()
                    # run control prompt
                    cw = ControlPrompt(screen, control_to_change=result)
                    cw.display()
                    # detect pressed control
                    control = ControlDetector.detect_control()
                    # run HotkeyManager to configure the json with hotkeys
                    hm = create_hotkey_manager()
                    hm.change_hotkey(opt=result, new_control=control)
                    cw.destroy()
                    current_params.refresh_hotkeys()

                elif current_params.extend_window:
                    # show a new window to prompt for controls
                    current_params.refresh_options(platform=current_params.title.replace(' ', '').lower())
                    cw = ControlPrompt(screen=screen,
                                        control_to_change=result)
                    cw.display()
                    # detect pressed control
                    control = ControlDetector.detect_control()
                    # platform is current window title minus the trailing space
                    cm = ControlManager(platform=current_params.title.replace(' ', '').lower())
                    cm.update_control_value(result, control)
                    # run ControlManager to configure the cfg file
                    # destroy the screen
                    cw.destroy()
                    current_params.refresh_options(platform=current_params.title.replace(' ', '').lower())

        pygame.display.quit()
        pygame.quit()
Пример #44
0
def main():
    with qt_application():
        window = Window()
        controller = WindowController(window)
        window.show()
Пример #45
0
def main(world):
    window = Window(width=800, height=600, caption='mine.py',
                    resizable=True, world=world)
    window.set_exclusive_mouse(True)
    setup()
    pyglet.app.run()
Пример #46
0
class TwissSetup:
    """GUI window to setup a beam according to 2D Twiss parameterisation"""
    def __init__(self, beam_setup, root_frame):
        """Initialise the window"""
        self.window = Window(
            ROOT.gClient.GetRoot(),  # pylint: disable = E1101
            root_frame,
            SHARE_DIR + "twiss_setup.json")
        self.beam_setup = beam_setup
        self.window.set_button_action("&Okay", self.okay_action)
        self.window.set_button_action("&Cancel", self.cancel_action)

    def okay_action(self):
        """Handle a click on the Okay button, building the beam matrix"""
        ref = self.beam_setup.get_reference()
        matrix = maus_cpp.covariance_matrix.create_from_twiss_parameters(
            mass=ref['mass'],
            momentum=ref['p'],
            emittance_x=self.window.get_text_entry("emittance_x", type(1.)),
            beta_x=self.window.get_text_entry("beta_x", type(1.)),
            emittance_y=self.window.get_text_entry("emittance_y", type(1.)),
            beta_y=self.window.get_text_entry("beta_y", type(1.)),
            emittance_l=self.window.get_text_entry("emittance_l", type(1.)),
            beta_l=self.window.get_text_entry("beta_l", type(1.)),
            alpha_x=self.window.get_text_entry("alpha_x", type(1.)),
            alpha_y=self.window.get_text_entry("alpha_y", type(1.)),
            alpha_l=self.window.get_text_entry("alpha_l", type(1.)),
            dispersion_x=self.window.get_text_entry("disp_x", type(1.)),
            dispersion_prime_x=self.window.get_text_entry(
                "disp_prime_x", type(1.)),
            dispersion_y=self.window.get_text_entry("disp_y", type(1.)),
            dispersion_prime_y=self.window.get_text_entry(
                "disp_prime_y", type(1.)))
        self.beam_setup.set_matrix(matrix)
        self.beam_setup.get_matrix()  # check for consistency
        self.window.close_window()
        self.beam_setup.matrix_select = None

    def cancel_action(self):
        """Handle a click on the Cancel button"""
        self.window.close_window()
        self.beam_setup.matrix_select = None
Пример #47
0
 def quick_actions(title):
     return Window(title, 3, 0, 0, 0, self)
Пример #48
0
class PennSetup:
    """GUI window to setup a beam according to 4D Penn parameterisation"""
    def __init__(self, beam_setup, root_frame):
        """Initialise the window"""
        self.window = Window(ROOT.gClient.GetRoot(), # pylint: disable = E1101
                             root_frame,
                             SHARE_DIR+"penn_setup.json")
        self.beam_setup = beam_setup
        self.window.set_button_action("&Okay", self.okay_action)
        self.window.set_button_action("&Cancel", self.cancel_action)
        self.window.set_button_action("Get &B0", self.get_b0_action)
        self.window.set_button_action("&Constant Beta",
                                      self.constant_beta_action)

    def okay_action(self):
        """Handle a click on the Okay button, building the beam matrix"""
        ref = self.beam_setup.get_reference()
        matrix = maus_cpp.covariance_matrix.create_from_penn_parameters(
          mass = ref['mass'],
          momentum = ref['p'],
          emittance_t = self.window.get_text_entry("emittance_trans", type(1.)),
          beta_t = self.window.get_text_entry("beta_trans", type(1.)),
          emittance_l = self.window.get_text_entry("emittance_l", type(1.)),
          beta_l = self.window.get_text_entry("beta_l", type(1.)),
          alpha_t = self.window.get_text_entry("alpha_trans", type(1.)),
          alpha_l = self.window.get_text_entry("alpha_l", type(1.)),
          charge = ref["charge"],
          # BUG - multiply by -1 to fix BUG in source code
          bz = -self.window.get_text_entry("B0", type(1.))*common.units['T'],
          ltwiddle = self.window.get_text_entry("Lc", type(1.)),
          dispersion_x = self.window.get_text_entry("disp_x", type(1.)),
          dispersion_prime_x = self.window.get_text_entry("disp_prime_x",
                                                          type(1.)),
          dispersion_y = self.window.get_text_entry("disp_y", type(1.)),
          dispersion_prime_y = self.window.get_text_entry("disp_prime_y",
                                                          type(1.))
        )
        self.beam_setup.set_matrix(matrix)
        self.beam_setup.get_matrix() # check for consistency
        self.window.close_window()
        self.beam_setup.matrix_select = None

    def cancel_action(self):
        """Handle a click on the Cancel button"""
        self.window.close_window()
        self.beam_setup.matrix_select = None

    def get_b0_action(self):
        """
        Handle a click on the Get B0 button, getting B magnitude at the location
        of the reference particle
        """
        ref = self.beam_setup.get_reference()
        b_vec = maus_cpp.field.get_field_value(ref['x'], ref['y'], ref['z'],
                                               ref['t'])
        _b0 = (b_vec[0]**2+b_vec[1]**2+b_vec[2]**2)**0.5
        self.window.set_text_entry('B0', _b0*common.units['T'])

    def constant_beta_action(self):
        """
        Handle a click on the Constant Beta button, getting beta function that
        would be required to get a constant beta function, given other settings
        (reference particle, B0, Lc)
        """
        _b0 = abs(self.window.get_text_entry("B0", type(1.))*1e-3) # kT
        if abs(_b0) < 1e-9:
            raise ValueError(
              "Constant beta requires B0 is not 0. "+\
              "Modify the B0 field and try again."
            )
        _lc = self.window.get_text_entry("Lc", type(1.)) # kT
        mom = self.beam_setup.get_reference()['p'] # MeV/c
        charge = abs(self.beam_setup.get_reference()['charge']) # eplus
        beta = (1+_lc**2)**0.5 * 2.*charge*mom/common.constants['c_light']/_b0
        self.window.set_text_entry('alpha_trans', 0.0)
        self.window.set_text_entry('beta_trans', beta) # beta in mm