コード例 #1
0
    def save_and_close(self, force: bool = False):
        # TODO: update GUI scale immediately if possible (and anything else if needed)
        self.fix_blank_spinboxes()
        settings_to_save: Dict[str, str] = self.get_working_settings()
        settings_changed = settings.compare_settings(self.settings_loaded,
                                                     settings_to_save)
        self.log.debug(f"Setting(s) changed: {settings_changed}")
        self.log.info("Saving and closing settings menu")
        settings.access_registry(save=settings_to_save)
        self.log.info(f"Settings have been saved as: {settings_to_save}")

        if not force:
            if 'gui_scale' in settings_changed:
                messagebox.showinfo(
                    self.loc.text("TF2 Rich Presence"),
                    self.loc.text(
                        "Changing GUI scale requires a restart to take effect."
                    ))
            if 'language' in settings_changed:
                messagebox.showinfo(
                    self.loc.text("TF2 Rich Presence"),
                    self.loc.text(
                        "Changing language requires a restart to take effect.")
                )

        self.master.destroy()  # closes window
コード例 #2
0
ファイル: tests.py プロジェクト: Kataiser/tf2-rich-presence
 def test_fix_settings(self):
     broken = settings.defaults()
     del broken['wait_time']
     broken['fake'] = True
     settings.access_registry(save=broken)
     settings.fix_settings(self.log)
     self.assertEqual(settings.access_registry(), settings.defaults())
コード例 #3
0
ファイル: tests.py プロジェクト: Kataiser/tf2-rich-presence
    def setUp(self):
        settings.access_registry(
            save=settings.defaults())  # sorry if this changes your settings
        settings.change('request_timeout', 30)

        self.dir = os.getcwd()
        self.log = logger.Log('logs\\tests.log')
        self.log.force_disabled = True
        self.log.to_stderr = False
        self.log.sentry_enabled = False
        self.log.info(f"Starting test: {self.id()}")

        gc.enable()  # because main may have disabled it
コード例 #4
0
ファイル: gui.py プロジェクト: Kataiser/tf2-rich-presence
    def menu_restore_defaults(self, *args):
        self.log.info("GUI: Restoring default settings")
        # TODO: consider sharing code between this and settings GUI restore defaults button
        settings.fix_settings(self.log)
        default_settings: dict = settings.defaults()
        current_settings: dict = settings.access_registry()
        self.pause()

        if current_settings == default_settings:
            self.log.debug("Current settings are default")
            messagebox.showinfo(
                self.loc.text("Restore defaults"),
                self.loc.text("Current settings are already default."))
        else:
            changed_settings: dict = {
                s: current_settings[s]
                for s in current_settings
                if current_settings[s] != default_settings[s]
            }
            self.log.debug(f"Changed settings: {changed_settings}")
            allowed_reset: str = "yes"

            if len(changed_settings) == 1:
                allowed_reset = messagebox.askquestion(
                    self.loc.text("Restore defaults"),
                    self.loc.text("Restore 1 setting to default?"))
            elif len(changed_settings) > 1:
                allowed_reset = messagebox.askquestion(
                    self.loc.text("Restore defaults"),
                    self.loc.text("Restore {0} settings to defaults?").format(
                        len(changed_settings)))

            if allowed_reset == "yes":
                settings.access_registry(save=default_settings)
                self.log.debug("Restored default settings")
            else:
                self.log.debug("Didn't restore default settings")

        self.unpause()
コード例 #5
0
    def __init__(self,
                 master: tk.Toplevel,
                 log: logger.Log,
                 position: Optional[tuple] = None,
                 reload_settings: Optional[tuple] = None):
        self.log: logger.Log = log
        self.log.info(
            f"Opening settings menu for TF2 Rich Presence {launcher.VERSION}")
        self.gui_language: Optional[str] = localization.langs[
            localization.langs.index(
                reload_settings[8].get())] if reload_settings else None
        self.loc: localization.Localizer = localization.Localizer(
            self.log, self.gui_language
            if self.gui_language else settings.get('language'))

        self.log_levels: Tuple[str, ...] = ('Debug', 'Info', 'Error',
                                            'Critical', 'Off')
        self.sentry_levels: Tuple[str,
                                  ...] = ('All errors', 'Crashes', 'Never')
        self.rpc_lines: Tuple[str, ...] = ('Server name', 'Player count',
                                           'Time on map', 'Kills', 'Class')

        self.log_levels_display: List[str] = [
            self.loc.text(item) for item in self.log_levels
        ]
        self.sentry_levels_display: List[str] = [
            self.loc.text(item) for item in self.sentry_levels
        ]
        self.rpc_lines_display: List[str] = [
            self.loc.text(item) for item in self.rpc_lines
        ]

        if reload_settings:
            # the GUI was reloaded with a new language, so persist the currently selected (but not saved) settings
            self.sentry_level, self.wait_time, self.wait_time_slow, self.check_updates, self.request_timeout, self.hide_queued_gamemode, self.log_level, self.console_scan_kb, \
            self.language, self.top_line, self.bottom_line, self.trim_console_log, self.server_rate_limit, self.gui_scale, self.drawing_gamemodes, self.preserve_window_pos = reload_settings
        else:
            # create every setting variable without values
            self.sentry_level: tk.StringVar = tk.StringVar()
            self.wait_time: tk.IntVar = tk.IntVar()
            self.wait_time_slow: tk.IntVar = tk.IntVar()
            self.check_updates: tk.BooleanVar = tk.BooleanVar()
            self.request_timeout: tk.IntVar = tk.IntVar()
            self.hide_queued_gamemode: tk.BooleanVar = tk.BooleanVar()
            self.log_level: tk.StringVar = tk.StringVar()
            self.console_scan_kb: tk.IntVar = tk.IntVar()
            self.language: tk.StringVar = tk.StringVar()
            self.top_line: tk.StringVar = tk.StringVar()
            self.bottom_line: tk.StringVar = tk.StringVar()
            self.trim_console_log: tk.BooleanVar = tk.BooleanVar()
            self.server_rate_limit: tk.IntVar = tk.IntVar()
            self.gui_scale: tk.IntVar = tk.IntVar()
            self.drawing_gamemodes: tk.BooleanVar = tk.BooleanVar()
            self.preserve_window_pos: tk.BooleanVar = tk.BooleanVar()

            try:
                # load settings from registry
                settings.fix_settings(self.log)
                self.settings_loaded: dict = settings.access_registry()
                self.log.debug(f"Current settings: {self.settings_loaded}")
                self.log.debug(
                    f"Are default: {self.settings_loaded == settings.defaults()}"
                )

                self.sentry_level.set(self.settings_loaded['sentry_level'])
                self.wait_time.set(self.settings_loaded['wait_time'])
                self.wait_time_slow.set(self.settings_loaded['wait_time_slow'])
                self.check_updates.set(self.settings_loaded['check_updates'])
                self.request_timeout.set(
                    self.settings_loaded['request_timeout'])
                self.hide_queued_gamemode.set(
                    self.settings_loaded['hide_queued_gamemode'])
                self.log_level.set(self.settings_loaded['log_level'])
                self.console_scan_kb.set(
                    self.settings_loaded['console_scan_kb'])
                self.language.set(self.gui_language if self.gui_language else
                                  self.settings_loaded['language'])
                self.top_line.set(self.settings_loaded['top_line'])
                self.bottom_line.set(self.settings_loaded['bottom_line'])
                self.trim_console_log.set(
                    self.settings_loaded['trim_console_log'])
                self.server_rate_limit.set(
                    self.settings_loaded['server_rate_limit'])
                self.gui_scale.set(self.settings_loaded['gui_scale'])
                self.drawing_gamemodes.set(
                    self.settings_loaded['drawing_gamemodes'])
                self.preserve_window_pos.set(
                    self.settings_loaded['preserve_window_pos'])
            except Exception:
                # probably a json decode error
                formatted_exception: str = traceback.format_exc()
                self.log.error(
                    f"Error in loading settings, defaulting: \n{formatted_exception}"
                )
                messagebox.showerror(
                    self.loc.text("Error"),
                    self.loc.text(
                        "Couldn't load settings, reverting to defaults.{0}").
                    format(f'\n\n{formatted_exception}'))

                self.restore_defaults()
                self.settings_loaded: dict = settings.defaults()

        # account for localization
        self.localization_compensate()
        actual_language: str = self.language.get()
        actual_top_line: str = self.top_line.get()
        actual_bottom_line: str = self.bottom_line.get()

        # actually create the settings window fairly late to reduce time with a tiny window visible
        self.master: Union[tk.Toplevel, tk.Tk] = master
        tk.Frame.__init__(self, self.master)
        if position:
            gui.pos_window_by_center(self.master, *position)
        check_int_command: str = self.register(check_int)
        self.master.protocol('WM_DELETE_WINDOW', self.close_window)
        self.master.title(
            self.loc.text("TF2 Rich Presence ({0}) settings").format(
                launcher.VERSION))
        self.master.resizable(False, False)  # disables resizing
        gui.set_window_icon(self.log, self.master, True)
        if not reload_settings:
            self.window_x: Optional[int] = None
            self.window_y: Optional[int] = None

        # create label frames
        self.lf_main: ttk.Labelframe = ttk.Labelframe(
            self.master, text=self.loc.text("Main"))
        self.lf_advanced: ttk.Labelframe = ttk.Labelframe(
            self.master, text=self.loc.text("Advanced"))

        # create settings widgets
        setting1_frame = ttk.Frame(self.lf_advanced)
        setting1_text = ttk.Label(
            setting1_frame,
            text="{}".format(self.loc.text("Log reporting frequency: ")))
        setting1_radiobuttons = []
        for sentry_level_text in self.sentry_levels_display:
            setting1_radiobuttons.append(
                ttk.Radiobutton(setting1_frame,
                                variable=self.sentry_level,
                                text=sentry_level_text,
                                value=sentry_level_text,
                                command=self.setting_changed))
        setting3_frame = ttk.Frame(self.lf_main)
        setting3_text = ttk.Label(
            setting3_frame,
            text="{}".format(
                self.loc.text("Delay between refreshes, in seconds: ")))
        setting3_option = ttk.Spinbox(setting3_frame,
                                      textvariable=self.wait_time,
                                      width=6,
                                      from_=0,
                                      to=float('inf'),
                                      validate='all',
                                      validatecommand=(check_int_command,
                                                       '%P'),
                                      command=self.setting_changed)
        setting5 = ttk.Checkbutton(
            self.lf_main,
            variable=self.check_updates,
            command=self.setting_changed,
            text="{}".format(
                self.loc.text("Check for program updates when launching")))
        setting6_frame = ttk.Frame(self.lf_advanced)
        setting6_text = ttk.Label(
            setting6_frame,
            text="{}".format(
                self.loc.text(
                    "Internet connection timeout (for updater and server querying): "
                )))
        setting6_option = ttk.Spinbox(setting6_frame,
                                      textvariable=self.request_timeout,
                                      width=6,
                                      from_=0,
                                      to=float('inf'),
                                      validate='all',
                                      validatecommand=(check_int_command,
                                                       '%P'),
                                      command=self.setting_changed)
        setting8 = ttk.Checkbutton(
            self.lf_main,
            variable=self.hide_queued_gamemode,
            command=self.setting_changed,
            text="{}".format(
                self.loc.text(
                    "Hide game type (Casual, Comp, MvM) queued for")))
        setting9_frame = ttk.Frame(self.lf_advanced)
        setting9_text = ttk.Label(setting9_frame,
                                  text="{}".format(
                                      self.loc.text("Max log level: ")))
        setting9_radiobuttons = []
        for log_level_text in self.log_levels_display:
            setting9_radiobuttons.append(
                ttk.Radiobutton(setting9_frame,
                                variable=self.log_level,
                                text=log_level_text,
                                value=log_level_text,
                                command=self.setting_changed))
        setting10_frame = ttk.Frame(self.lf_advanced)
        setting10_text = ttk.Label(
            setting10_frame,
            text="{}".format(
                self.loc.text("Max kilobytes of console.log to scan: ")))
        setting10_option = ttk.Spinbox(setting10_frame,
                                       textvariable=self.console_scan_kb,
                                       width=8,
                                       from_=0,
                                       to=float('inf'),
                                       validate='all',
                                       validatecommand=(check_int_command,
                                                        '%P'),
                                       command=self.setting_changed)
        setting13_frame = ttk.Frame(self.lf_main)
        setting13_text = ttk.Label(setting13_frame,
                                   text="{}".format(
                                       self.loc.text("Language: ")))
        setting13_options = ttk.OptionMenu(setting13_frame,
                                           self.language,
                                           localization.langs[0],
                                           *localization.langs_localized,
                                           command=self.update_language)
        setting14_frame = ttk.Frame(self.lf_main)
        setting14_text = ttk.Label(setting14_frame,
                                   text="{}".format(
                                       self.loc.text("Bottom line: ")))
        setting14_radiobuttons = []
        for rpc_line_text in self.rpc_lines_display:
            setting14_radiobuttons.append(
                ttk.Radiobutton(setting14_frame,
                                variable=self.bottom_line,
                                text=rpc_line_text,
                                value=rpc_line_text,
                                command=self.setting_changed))
        setting15 = ttk.Checkbutton(
            self.lf_advanced,
            variable=self.trim_console_log,
            command=self.setting_changed,
            text="{}".format(
                self.loc.text(
                    "Occasionally limit console.log's size and remove empty lines and common errors"
                )))
        setting16_frame = ttk.Frame(self.lf_main)
        setting16_text = ttk.Label(
            setting16_frame,
            text="{}".format(
                self.loc.text(
                    "Delay between refreshes when TF2 and Discord aren't running: "
                )))  # and Steam but whatever
        setting16_option = ttk.Spinbox(setting16_frame,
                                       textvariable=self.wait_time_slow,
                                       width=6,
                                       from_=0,
                                       to=float('inf'),
                                       validate='all',
                                       validatecommand=(check_int_command,
                                                        '%P'),
                                       command=self.setting_changed)
        setting17_frame = ttk.Frame(self.lf_advanced)
        setting17_text = ttk.Label(
            setting17_frame,
            text="{}".format(self.loc.text("Server querying rate limit: ")))
        setting17_option = ttk.Spinbox(setting17_frame,
                                       textvariable=self.server_rate_limit,
                                       width=6,
                                       from_=0,
                                       to=float('inf'),
                                       validate='all',
                                       validatecommand=(check_int_command,
                                                        '%P'),
                                       command=self.setting_changed)
        setting18_frame = ttk.Frame(self.lf_main)
        setting18_text = ttk.Label(setting18_frame,
                                   text="{}".format(
                                       self.loc.text("GUI scale: ")))
        setting18_option = tk.Scale(setting18_frame,
                                    variable=self.gui_scale,
                                    from_=50,
                                    to=200,
                                    resolution=5,
                                    length=150,
                                    orient=tk.HORIZONTAL,
                                    command=self.setting_changed)
        setting19_frame = ttk.Frame(self.lf_main)
        setting19_text = ttk.Label(setting19_frame,
                                   text="{}".format(
                                       self.loc.text("Top line: ")))
        setting19_radiobuttons = []
        for rpc_line_text in self.rpc_lines_display:
            setting19_radiobuttons.append(
                ttk.Radiobutton(setting19_frame,
                                variable=self.top_line,
                                text=rpc_line_text,
                                value=rpc_line_text,
                                command=self.setting_changed))
        setting20 = ttk.Checkbutton(
            self.lf_main,
            variable=self.drawing_gamemodes,
            command=self.setting_changed,
            text="{}".format(
                self.loc.text("Use classic gamemode images in the GUI")))
        setting21 = ttk.Checkbutton(
            self.lf_main,
            variable=self.preserve_window_pos,
            command=self.setting_changed,
            text="{}".format(
                self.loc.text("Remember previous window position")))

        # more localization compensation
        self.language.set(actual_language)
        self.top_line.set(actual_top_line)
        self.bottom_line.set(actual_bottom_line)

        # prepare widgets to be added
        setting1_text.pack(side='left', fill='none', expand=False)
        for setting1_radiobutton in setting1_radiobuttons:
            setting1_radiobutton.pack(side='left',
                                      fill='none',
                                      expand=False,
                                      padx=(0, 5))
        setting3_text.pack(side='left', fill='none', expand=False)
        setting3_option.pack(side='left', fill='none', expand=False)
        setting6_text.pack(side='left', fill='none', expand=False)
        setting6_option.pack(side='left', fill='none', expand=False)
        setting9_text.pack(side='left', fill='none', expand=False)
        for setting9_radiobutton in setting9_radiobuttons:
            setting9_radiobutton.pack(side='left',
                                      fill='none',
                                      expand=False,
                                      padx=(0, 5))
        setting10_text.pack(side='left', fill='none', expand=False)
        setting10_option.pack(side='left', fill='none', expand=False)
        setting13_text.pack(side='left', fill='none', expand=False)
        setting13_options.pack(side='left', fill='none', expand=False)
        setting14_text.pack(side='left', fill='none', expand=False)
        for setting14_radiobutton in setting14_radiobuttons:
            setting14_radiobutton.pack(side='left',
                                       fill='none',
                                       expand=False,
                                       padx=(0, 5))
        setting16_text.pack(side='left', fill='none', expand=False)
        setting16_option.pack(side='left', fill='none', expand=False)
        setting17_text.pack(side='left', fill='none', expand=False)
        setting17_option.pack(side='left', fill='none', expand=False)
        setting18_text.pack(side='left', fill='none', expand=False)
        setting18_option.pack(side='left', padx=5)
        setting19_text.pack(side='left', fill='none', expand=False)
        for setting19_radiobutton in setting19_radiobuttons:
            setting19_radiobutton.pack(side='left',
                                       fill='none',
                                       expand=False,
                                       padx=(0, 5))

        # add widgets to the labelframes and main window
        setting13_frame.grid(row=0,
                             columnspan=2,
                             sticky=tk.W,
                             padx=(20, 40),
                             pady=(9, 0))
        setting3_frame.grid(row=1,
                            columnspan=2,
                            sticky=tk.W,
                            padx=(20, 40),
                            pady=(3, 0))
        setting16_frame.grid(row=2,
                             columnspan=2,
                             sticky=tk.W,
                             padx=(20, 40),
                             pady=(3, 0))
        setting19_frame.grid(row=3,
                             columnspan=2,
                             sticky=tk.W,
                             padx=(20, 40),
                             pady=(3, 0))
        setting14_frame.grid(row=4,
                             columnspan=2,
                             sticky=tk.W,
                             padx=(20, 40),
                             pady=(3, 0))
        setting18_frame.grid(row=5,
                             columnspan=2,
                             sticky=tk.W,
                             padx=(20, 40),
                             pady=(0, 0))
        setting10_frame.grid(row=6,
                             columnspan=2,
                             sticky=tk.W,
                             padx=(20, 40),
                             pady=(11, 0))
        setting20.grid(row=7,
                       sticky=tk.W,
                       columnspan=2,
                       padx=(20, 40),
                       pady=(4, 0))
        setting8.grid(row=8,
                      sticky=tk.W,
                      columnspan=2,
                      padx=(20, 40),
                      pady=(4, 0))
        setting21.grid(row=9,
                       sticky=tk.W,
                       columnspan=2,
                       padx=(20, 40),
                       pady=(4, 0))
        setting15.grid(row=10,
                       sticky=tk.W,
                       columnspan=2,
                       padx=(20, 40),
                       pady=(4, 0))
        setting5.grid(row=11,
                      sticky=tk.W,
                      columnspan=2,
                      padx=(20, 40),
                      pady=(4, 10))
        setting6_frame.grid(row=12,
                            columnspan=2,
                            sticky=tk.W,
                            padx=(20, 40),
                            pady=(4, 0))
        setting17_frame.grid(row=13,
                             columnspan=2,
                             sticky=tk.W,
                             padx=(20, 40),
                             pady=(3, 0))
        setting1_frame.grid(row=14,
                            columnspan=2,
                            sticky=tk.W,
                            padx=(20, 40),
                            pady=(4, 0))
        setting9_frame.grid(row=15,
                            columnspan=2,
                            sticky=tk.W,
                            padx=(20, 40),
                            pady=(4, 10))

        self.lf_main.grid(row=0, padx=30, pady=15, sticky=tk.W + tk.E)
        self.lf_advanced.grid(row=1, padx=30, pady=0, sticky=tk.W + tk.E)

        self.buttons_frame = ttk.Frame(self.master)
        self.restore_button = ttk.Button(
            self.buttons_frame,
            text=self.loc.text("Restore defaults"),
            command=self.restore_defaults)
        self.restore_button.grid(row=0, column=1, padx=(10, 0), pady=(20, 20))
        cancel_button = ttk.Button(self.buttons_frame,
                                   text=self.loc.text("Close without saving"),
                                   command=self.close_without_saving)
        cancel_button.grid(row=0, column=2, padx=10, pady=(20, 20))
        self.ok_button = ttk.Button(self.buttons_frame,
                                    text=self.loc.text("Save and close"),
                                    command=self.save_and_close,
                                    default=tk.ACTIVE)
        self.ok_button.grid(row=0,
                            column=3,
                            sticky=tk.W,
                            padx=0,
                            pady=(20, 20))
        self.buttons_frame.grid(row=100, columnspan=3)

        self.defaults_button_enabled: bool = True
        self.setting_changed()
        self.master.update()
        self.window_dimensions = self.master.winfo_width(
        ), self.master.winfo_height()
        self.log.debug(f"Window size: {self.window_dimensions}")
        self.master.focus_force()
        self.master.grab_set()
        if position:
            gui.pos_window_by_center(self.master, *position)
コード例 #6
0
    def __init__(self,
                 log: Optional[logger.Log] = None,
                 set_process_priority: bool = True):
        if log:
            self.log: logger.Log = log
        else:
            self.log = logger.Log()
            self.log.error(
                f"Initialized main.TF2RichPresense without a log, defaulting to one at {self.log.filename}"
            )

        settings.fix_settings(self.log)
        default_settings: dict = settings.defaults()
        current_settings: dict = settings.access_registry()

        if current_settings == default_settings:
            self.log.debug("Current settings are default")
        else:
            self.log.debug(
                f"Non-default settings: {settings.compare_settings(default_settings, current_settings)}"
            )

        self.gui: gui.GUI = gui.GUI(self.log, main_controlled=True)
        self.process_scanner: processes.ProcessScanner = processes.ProcessScanner(
            self.log)
        self.loc: localization.Localizer = localization.Localizer(self.log)
        self.game_state: game_state.GameState = game_state.GameState(
            self.log, self.loc)
        self.rpc_client: Optional[ipc.DiscordIPC] = None
        self.client_connected: bool = False
        self.rpc_connected: bool = False
        self.test_state: str = 'init'
        self.activity: dict = {}
        self.should_mention_discord: bool = True
        self.should_mention_tf2: bool = True
        self.should_mention_steam: bool = True
        self.has_checked_class_configs: bool = False
        self.has_seen_kataiser: bool = False
        self.console_log_mtime: Optional[int] = None
        self.old_console_log_mtime: Optional[int] = None
        self.loop_iteration: int = 0
        self.custom_functions = None
        self.usernames: Set[str] = set()
        self.last_name_scan_time: float = time.time()  # close enough
        self.steam_config_mtimes: Dict[str, int] = {}
        self.cleanup_primed: bool = True
        self.slow_sleep_time: bool = False
        self.has_set_process_priority: bool = not set_process_priority
        self.kataiser_scan_loop: int = 0
        self.did_init_operations: bool = False
        self.no_condebug: bool = False
        self.fast_next_loop: bool = False
        self.reset_launched_with_button: bool = False
        self.last_console_log_size: Optional[int] = None

        try:
            self.log.cleanup(20 if launcher.DEBUG else 10)
        except (FileNotFoundError, PermissionError):
            self.log.error(
                f"Couldn't clean up logs folder:\n{traceback.format_exc()}")

        self.log.debug(
            f"CPU: {psutil.cpu_count(logical=False)} cores, {psutil.cpu_count()} threads, {round(psutil.cpu_freq().max / 1000, 1)} GHz"
        )

        platform_info: Dict[str, Any] = {
            'architecture': platform.architecture,
            'machine': platform.machine,
            'system': platform.system,
            'platform': platform.platform,
            'processor': platform.processor,
            'python_version_tuple': platform.python_version_tuple
        }
        for platform_part in platform_info:
            try:
                if platform_part == 'platform':
                    platform_info[platform_part] = platform_info[
                        platform_part](aliased=True)
                else:
                    platform_info[platform_part] = platform_info[
                        platform_part]()
            except Exception:
                self.log.error(
                    f"Exception during platform.{platform_part}(), skipping\n{traceback.format_exc()}"
                )
        self.log.debug(f"Platform: {platform_info}")

        if not os.path.supports_unicode_filenames:
            self.log.error(
                "Looks like the OS doesn't support unicode filenames. This might cause problems"
            )

        self.import_custom()
コード例 #7
0
ファイル: tests.py プロジェクト: Kataiser/tf2-rich-presence
    def test_game_state(self):
        game_state_test = game_state.GameState(self.log)
        game_state_test.force_zero_map_time = True
        self.assertTrue(game_state_test.update_rpc)
        self.assertEqual(str(game_state_test), 'in menus, queued="Not queued"')

        game_state_test.set_bulk((True, '', '', '', 'Not queued', False))
        self.assertTrue(game_state_test.update_rpc)
        self.assertEqual(str(game_state_test), 'in menus, queued="Not queued"')
        self.assertEqual(
            fix_activity_dict(game_state_test.activity()), {
                'details': 'In menus',
                'state': 'Not queued',
                'timestamps': {
                    'start': 0
                },
                'assets': {
                    'large_image': 'main_menu',
                    'large_text': 'In menus - TF2 Rich Presence {tf2rpvnum}',
                    'small_image': 'tf2_logo',
                    'small_text': 'Team Fortress 2'
                }
            })
        self.assertFalse(game_state_test.update_rpc)

        game_state_test.set_bulk(
            (False, 'koth_highpass', 'Demoman', '', 'Not queued', True))
        self.assertTrue(game_state_test.update_rpc)
        self.assertEqual(
            str(game_state_test),
            'Demoman on Highpass, gamemode=koth, hosting=True, queued="Not queued", server='
        )
        self.assertEqual(
            fix_activity_dict(game_state_test.activity()), {
                'details': 'Map: Highpass (hosting)',
                'state': 'Time on map: 0:00',
                'timestamps': {
                    'start': 0
                },
                'assets': {
                    'large_image': 'z_koth_highpass',
                    'large_text': 'Highpass - TF2 Rich Presence {tf2rpvnum}',
                    'small_image': 'demoman',
                    'small_text': 'Demoman'
                }
            })
        self.assertTrue(game_state_test.update_rpc)

        settings.change('bottom_line', 'Class')
        game_state_test.set_bulk(
            (False, 'koth_highpass', 'Demoman', '', 'Not queued', True))
        self.assertTrue(game_state_test.update_rpc)
        self.assertEqual(
            str(game_state_test),
            'Demoman on Highpass, gamemode=koth, hosting=True, queued="Not queued", server='
        )
        self.assertEqual(
            fix_activity_dict(game_state_test.activity()), {
                'details': 'Map: Highpass (hosting)',
                'state': 'Class: Demoman',
                'timestamps': {
                    'start': 0
                },
                'assets': {
                    'large_image': 'z_koth_highpass',
                    'large_text': 'Highpass - TF2 Rich Presence {tf2rpvnum}',
                    'small_image': 'demoman',
                    'small_text': 'Demoman'
                }
            })
        self.assertFalse(game_state_test.update_rpc)

        settings.access_registry(save=settings.defaults())
        game_state_test.set_bulk(
            (False, 'pl_snowycoast', 'Pyro', '162.254.192.155:27053',
             'Not queued', False))
        self.assertTrue(game_state_test.update_rpc)
        game_state_test.update_server_data(['Player count'], {'Kataiser'})
        self.assertEqual(
            str(game_state_test),
            'Pyro on Snowycoast, gamemode=payload, hosting=False, queued="Not queued", server=162.254.192.155:27053'
        )
        self.assertEqual(
            fix_activity_dict(game_state_test.activity()), {
                'details': 'Players: 0/0',
                'state': 'Time on map: 0:00',
                'timestamps': {
                    'start': 0
                },
                'assets': {
                    'large_image': 'z_pl_snowycoast',
                    'large_text': 'Snowycoast - TF2 Rich Presence {tf2rpvnum}',
                    'small_image': 'pyro',
                    'small_text': 'Pyro'
                }
            })
        self.assertTrue(game_state_test.update_rpc)

        settings.change('bottom_line', 'Kills')
        settings.change('server_rate_limit', 0)
        game_state_test.update_server_data(['Player count', 'Kills'],
                                           {'Kataiser'})
        self.assertEqual(
            fix_activity_dict(game_state_test.activity()), {
                'details': 'Players: 0/0',
                'state': 'Kills: 0',
                'timestamps': {
                    'start': 0
                },
                'assets': {
                    'large_image': 'z_pl_snowycoast',
                    'large_text': 'Snowycoast - TF2 Rich Presence {tf2rpvnum}',
                    'small_image': 'pyro',
                    'small_text': 'Pyro'
                }
            })
        self.assertFalse(game_state_test.update_rpc)

        settings.access_registry(save=settings.defaults())
        game_state_test.set_bulk((False, 'cp_catwalk_a5c', 'Soldier', '',
                                  'Queued for Casual', True))
        self.assertTrue(game_state_test.update_rpc)
        self.assertEqual(
            str(game_state_test),
            'Soldier on cp_catwalk_a5c, gamemode=control-point, hosting=True, queued="Queued for Casual", server='
        )
        self.assertEqual(
            fix_activity_dict(game_state_test.activity()), {
                'details': 'Map: cp_catwalk_a5c (hosting)',
                'state': 'Queued for Casual',
                'timestamps': {
                    'start': 0
                },
                'assets': {
                    'large_image': 'control-point',
                    'large_text':
                    'Control Point - TF2 Rich Presence {tf2rpvnum}',
                    'small_image': 'soldier',
                    'small_text': 'Soldier'
                }
            })
        self.assertFalse(game_state_test.update_rpc)

        game_state_test.set_bulk(
            (False, 'arena_badlands', 'Engineer', '', 'Not queued', True))
        self.assertTrue(game_state_test.update_rpc)
        self.assertEqual(
            str(game_state_test),
            'Engineer on Badlands (Arena), gamemode=arena, hosting=True, queued="Not queued", server='
        )
        self.assertEqual(
            fix_activity_dict(game_state_test.activity()), {
                'details': 'Map: Badlands (Arena) (hosting)',
                'state': 'Time on map: 0:00',
                'timestamps': {
                    'start': 0
                },
                'assets': {
                    'large_image': 'z_cp_badlands',
                    'large_text':
                    'Badlands (Arena) - TF2 Rich Presence {tf2rpvnum}',
                    'small_image': 'engineer',
                    'small_text': 'Engineer'
                }
            })
        self.assertTrue(game_state_test.update_rpc)
コード例 #8
0
ファイル: tests.py プロジェクト: Kataiser/tf2-rich-presence
 def tearDown(self):
     os.chdir(self.dir)
     del self.log
     settings.access_registry(
         save=settings.defaults())  # sorry if this changes your settings