def _common_testing_show_choose_outfit_dialog(_connection: int=None):
    output = sims4.commands.CheatOutput(_connection)
    output('Showing test choose outfit dialog.')

    def _on_chosen(choice: Tuple[OutfitCategory, int], outcome: CommonChoiceOutcome):
        output('Chose {} with result: {}.'.format(pformat(choice), pformat(outcome)))

    try:
        sim_info = CommonSimUtils.get_active_sim_info()
        # LocalizedStrings within other LocalizedStrings
        title_tokens = (CommonLocalizationUtils.create_localized_string(CommonStringId.TESTING_SOME_TEXT_FOR_TESTING, text_color=CommonLocalizedStringColor.GREEN),)
        description_tokens = (CommonLocalizationUtils.create_localized_string(CommonStringId.TESTING_TEST_TEXT_WITH_SIM_FIRST_AND_LAST_NAME, tokens=(sim_info,), text_color=CommonLocalizedStringColor.BLUE),)
        from sims4communitylib.utils.common_icon_utils import CommonIconUtils
        dialog = CommonChooseOutfitDialog(
            ModInfo.get_identity(),
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            title_tokens=title_tokens,
            description_tokens=description_tokens
        )
        outfit_list = (OutfitCategory.EVERYDAY, 0)
        dialog.show(sim_info, outfit_list=outfit_list, on_chosen=_on_chosen)
    except Exception as ex:
        CommonExceptionHandler.log_exception(ModInfo.get_identity(), 'Failed to show dialog', exception=ex)
        output('Failed to show dialog, please locate your exception log file.')
    output('Done showing.')
    def dispatch(self, event: CommonEvent) -> bool:
        """dispatch(event)

        Dispatch an event to any event handlers listening for it.

        :param event: An instance of the event to dispatch to listeners.
        :type event: CommonEvent
        :return: True, if the event was dispatched successfully. False, if not.
        :rtype: bool
        """
        event_handlers = list(self._event_handlers)
        result = True
        try:
            for event_handler in event_handlers:
                if not event_handler.can_handle_event(event):
                    continue
                try:
                    handle_result = event_handler.handle_event(event)
                    if not handle_result:
                        result = False
                except Exception as ex:
                    CommonExceptionHandler.log_exception(ModInfo.get_identity(), 'Error occurred when attempting to handle event type \'{}\' via event handler \'{}\''.format(type(event), str(event_handler)), exception=ex)
                    continue
        except Exception as ex:
            CommonExceptionHandler.log_exception(ModInfo.get_identity(), 'Failed to dispatch event \'{}\''.format(event), exception=ex)
            return False
        return result
Пример #3
0
    def dispatch(self, event: CommonEvent) -> bool:
        """Dispatch an event to any event handlers listening for it.

        """
        event_handlers = list(self._event_handlers)
        result = True
        try:
            for event_handler in event_handlers:
                if not event_handler.can_handle_event(event):
                    continue
                try:
                    handle_result = event_handler.handle_event(event)
                    if not handle_result:
                        result = False
                except Exception as ex:
                    CommonExceptionHandler.log_exception(
                        ModInfo.get_identity().name,
                        'Error occurred when attempting to handle event type \'{}\' via event handler \'{}\''
                        .format(type(event), str(event_handler)),
                        exception=ex)
                    continue
        except Exception as ex:
            CommonExceptionHandler.log_exception(
                ModInfo.get_identity().name,
                'Failed to dispatch event \'{}\''.format(event),
                exception=ex)
            return False
        return result
 def _wrapper(*_: Any, **__: Any):
     if all_must_pass:
         for primary_function in predicate_functions:
             if primary_function is None:
                 continue
             try:
                 if not primary_function(*_, **__):
                     func_utils_log.format_with_message('Function failed.', function_name=primary_function.__name__)
                     return False
             except Exception as ex:
                 CommonExceptionHandler.log_exception(ModInfo.get_identity().name, 'Error occurred while running function: {}'.format(primary_function.__name__), exception=ex)
                 return False
         return True
     else:
         for primary_function in predicate_functions:
             if primary_function is None:
                 continue
             try:
                 if primary_function(*_, **__):
                     func_utils_log.format_with_message('Function passed.', function_name=primary_function.__name__)
                     return True
             except Exception as ex:
                 CommonExceptionHandler.log_exception(ModInfo.get_identity().name, 'Error occurred while running function: {}'.format(primary_function.__name__), exception=ex)
                 return False
         return False
def _common_testing_show_input_text_dialog(_connection: int = None):
    output = sims4.commands.CheatOutput(_connection)
    output('Showing test input text dialog.')

    def _on_chosen(input_value: str, outcome: CommonChoiceOutcome):
        output('Input {} with result: {}.'.format(pformat(input_value),
                                                  pformat(outcome)))

    try:
        # LocalizedStrings within other LocalizedStrings
        title_tokens = (CommonLocalizationUtils.create_localized_string(
            CommonStringId.TESTING_SOME_TEXT_FOR_TESTING,
            text_color=CommonLocalizedStringColor.GREEN), )
        description_tokens = (CommonLocalizationUtils.create_localized_string(
            CommonStringId.TESTING_TEST_TEXT_WITH_SIM_FIRST_AND_LAST_NAME,
            tokens=(CommonSimUtils.get_active_sim_info(), ),
            text_color=CommonLocalizedStringColor.BLUE), )
        from sims4communitylib.utils.common_icon_utils import CommonIconUtils
        dialog = CommonInputTextDialog(
            ModInfo.get_identity(),
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            'default_text',
            title_tokens=title_tokens,
            description_tokens=description_tokens)
        dialog.show(on_submit=_on_chosen)
    except Exception as ex:
        CommonExceptionHandler.log_exception(ModInfo.get_identity(),
                                             'Failed to show dialog',
                                             exception=ex)
        output('Failed to show dialog, please locate your exception log file.')
    output('Done showing.')
Пример #6
0
def _common_testing_show_choose_sim_option_dialog(_connection: int=None):
    output = sims4.commands.CheatOutput(_connection)
    output('Showing test choose sim option dialog.')

    def _on_chosen(_sim_info: SimInfo):
        output('Chose Sim with name \'{}\''.format(CommonSimNameUtils.get_full_name(_sim_info)))

    try:
        # LocalizedStrings within other LocalizedStrings
        title_tokens = (
            CommonLocalizationUtils.create_localized_string(
                CommonStringId.TESTING_SOME_TEXT_FOR_TESTING,
                text_color=CommonLocalizedStringColor.GREEN
            ),
        )
        description_tokens = (
            CommonLocalizationUtils.create_localized_string(
                CommonStringId.TESTING_TEST_TEXT_WITH_SIM_FIRST_AND_LAST_NAME,
                tokens=(CommonSimUtils.get_active_sim_info(),),
                text_color=CommonLocalizedStringColor.BLUE
            ),
        )

        # Create the dialog and show a number of Sims in 4 columns.
        option_dialog = CommonChooseSimOptionDialog(
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            title_tokens=title_tokens,
            description_tokens=description_tokens,
            mod_identity=ModInfo.get_identity()
        )

        current_count = 0
        count = 25

        for sim_info in CommonSimUtils.get_sim_info_for_all_sims_generator():
            if current_count >= count:
                break
            should_select = random.choice((True, False))
            is_enabled = random.choice((True, False))
            option_dialog.add_option(
                CommonDialogSimOption(
                    sim_info,
                    CommonDialogSimOptionContext(
                        is_enabled=is_enabled,
                        is_selected=should_select
                    ),
                    on_chosen=_on_chosen
                )
            )

        option_dialog.show(
            sim_info=CommonSimUtils.get_active_sim_info(),
            column_count=4
        )
    except Exception as ex:
        CommonExceptionHandler.log_exception(ModInfo.get_identity(), 'Failed to show dialog', exception=ex)
        output('Failed to show dialog, please locate your exception log file.')
    output('Done showing.')
Пример #7
0
class S4CLDebugShowActiveBuffsInteraction(CommonImmediateSuperInteraction):
    """S4CLDebugShowActiveBuffsInteraction(*_, **__)

    Show the currently active Buffs of a Sim.
    """

    # noinspection PyMissingOrEmptyDocstring
    @classmethod
    def get_mod_identity(cls) -> CommonModIdentity:
        return ModInfo.get_identity()

    # noinspection PyMissingOrEmptyDocstring
    @classmethod
    def get_log_identifier(cls) -> str:
        return 's4cl_debug_show_active_buffs'

    # noinspection PyMissingOrEmptyDocstring
    @classmethod
    @CommonExceptionHandler.catch_exceptions(ModInfo.get_identity().name,
                                             fallback_return=TestResult.NONE)
    def on_test(cls, interaction_sim: Sim, interaction_target: Any,
                interaction_context: InteractionContext,
                **kwargs) -> TestResult:
        cls.get_log().format_with_message(
            'Running \'{}\' on_test.'.format(cls.__name__),
            interaction_sim=interaction_sim,
            interaction_target=interaction_target,
            interaction_context=interaction_context,
            kwargles=kwargs)
        if interaction_target is None or not CommonTypeUtils.is_sim_or_sim_info(
                interaction_target):
            cls.get_log().debug('Failed, Target is not a Sim.')
            return TestResult.NONE
        cls.get_log().debug('Success, can show active Buffs.')
        return TestResult.TRUE

    # noinspection PyMissingOrEmptyDocstring
    @CommonExceptionHandler.catch_exceptions(ModInfo.get_identity().name,
                                             fallback_return=False)
    def on_started(self, interaction_sim: Sim,
                   interaction_target: Sim) -> bool:
        self.log.format_with_message('Running \'{}\' on_started.'.format(
            self.__class__.__name__),
                                     interaction_sim=interaction_sim,
                                     interaction_target=interaction_target)
        target_sim_info = CommonSimUtils.get_sim_info(interaction_target)
        target_sim_name = CommonSimNameUtils.get_full_name(target_sim_info)
        sim_buffs = ', '.join(
            CommonBuffUtils.get_buff_names(
                CommonBuffUtils.get_buffs(target_sim_info)))
        text = ''
        text += 'Active Buffs:\n{}\n\n'.format(sim_buffs)
        CommonBasicNotification(
            CommonLocalizationUtils.create_localized_string(
                '{} Active Buffs'.format(target_sim_name)),
            CommonLocalizationUtils.create_localized_string(text)).show(
                icon=IconInfoData(obj_instance=interaction_target))
        return True
Пример #8
0
class CommonOkCancelDialog:
    """
        Use to create a prompt dialog.
    """
    def __init__(self,
                 title_identifier: Union[int, LocalizedString],
                 description_identifier: Union[int, LocalizedString],
                 title_tokens: Tuple[Any]=(),
                 description_tokens: Tuple[Any]=(),
                 ok_text_identifier: Union[int, LocalizedString]=CommonStringId.OK,
                 ok_text_tokens: Tuple[Any]=(),
                 cancel_text_identifier: Union[int, LocalizedString]=CommonStringId.CANCEL,
                 cancel_text_tokens: Tuple[Any]=()):
        """
            Create a dialog with two buttons: Ok and Cancel.
        :param title_identifier: A decimal identifier of the title text.
        :param description_identifier: A decimal identifier of the description text.
        :param title_tokens: Tokens to format into the title.
        :param description_tokens: Tokens to format into the description.
        :param ok_text_identifier: A decimal identifier for the Ok text.
        :param ok_text_tokens: Tokens to format into the Ok text.
        :param cancel_text_identifier: A decimal identifier for the Cancel text.
        :param cancel_text_tokens: Tokens to format into the Cancel text.
        """
        self.title = CommonLocalizationUtils.create_localized_string(title_identifier, tokens=title_tokens)
        self.description = CommonLocalizationUtils.create_localized_string(description_identifier, tokens=description_tokens)
        self.ok_text = CommonLocalizationUtils.create_localized_string(ok_text_identifier, tokens=ok_text_tokens)
        self.cancel_text = CommonLocalizationUtils.create_localized_string(cancel_text_identifier, tokens=cancel_text_tokens)

    @CommonExceptionHandler.catch_exceptions(ModInfo.get_identity().name)
    def show(self, on_ok_selected: Callable[[UiDialogOkCancel], Any]=CommonFunctionUtils.noop, on_cancel_selected: Callable[[UiDialogOkCancel], Any]=CommonFunctionUtils.noop):
        """
            Show the dialog and invoke the callbacks upon the player selecting an option.
        :param on_ok_selected: Invoked upon the player selecting Ok in the dialog.
        :param on_cancel_selected: Invoked upon the player selecting Cancel in the dialog.
        """
        _dialog = self._create_dialog()
        if _dialog is None:
            return

        def _on_option_selected(dialog: UiDialogOkCancel):
            if dialog.accepted:
                return on_ok_selected(dialog)
            return on_cancel_selected(dialog)

        _dialog.add_listener(_on_option_selected)
        _dialog.show_dialog()

    @CommonExceptionHandler.catch_exceptions(ModInfo.get_identity().name, fallback_return=None)
    def _create_dialog(self) -> Union[UiDialogOkCancel, None]:
        return UiDialogOkCancel.TunableFactory().default(CommonSimUtils.get_active_sim_info(),
                                                         text=lambda *_, **__: self.description,
                                                         title=lambda *_, **__: self.title,
                                                         text_ok=lambda *_, **__: self.ok_text,
                                                         text_cancel=lambda *_, **__: self.cancel_text)
def _common_broadcaster_apply(original, self: Broadcaster, *_, **__) -> None:
    try:
        return original(self, *_, **__)
    except Exception as ex:
        if self.interaction is not None:
            interaction = self.interaction
            CommonExceptionHandler.log_exception(ModInfo.get_identity(), 'Error occurred while running apply_broadcaster_effect for broadcaster {} for interaction {} with short name {} and display name {}'.format(pformat(self), pformat(interaction), CommonInteractionUtils.get_interaction_short_name(interaction), CommonInteractionUtils.get_interaction_display_name(interaction)), exception=ex)
        elif self.broadcasting_object is not None:
            broadcasting_object = self.broadcasting_object
            CommonExceptionHandler.log_exception(ModInfo.get_identity(), 'Error occurred while running apply_broadcaster_effect for broadcaster {} from object {}'.format(pformat(self), pformat(broadcasting_object)), exception=ex)
        else:
            CommonExceptionHandler.log_exception(ModInfo.get_identity(), 'Error occurred while running apply_broadcaster_effect for broadcaster {}'.format(pformat(self)), exception=ex)
    return None
Пример #10
0
def _common_testing_show_choose_response_dialog(_connection: int = None):
    output = sims4.commands.CheatOutput(_connection)
    output('Showing test choose response dialog.')

    def _on_chosen(choice: str, outcome: CommonChoiceOutcome):
        output('Chose {} with result: {}.'.format(pformat(choice),
                                                  pformat(outcome)))

    try:
        responses: Tuple[CommonUiDialogResponse] = (
            CommonUiDialogResponse(
                1,
                'Value 1',
                text=CommonLocalizationUtils.create_localized_string(
                    CommonStringId.TESTING_TEST_BUTTON_ONE)),
            CommonUiDialogResponse(
                2,
                'Value 2',
                text=CommonLocalizationUtils.create_localized_string(
                    CommonStringId.TESTING_TEST_BUTTON_TWO)),
            CommonUiDialogResponse(
                3,
                'Value 3',
                text=CommonLocalizationUtils.create_localized_string(
                    'Test Button 3')))
        title_tokens = (CommonLocalizationUtils.create_localized_string(
            CommonStringId.TESTING_SOME_TEXT_FOR_TESTING,
            text_color=CommonLocalizedStringColor.GREEN), )
        description_tokens = (CommonLocalizationUtils.create_localized_string(
            CommonStringId.TESTING_TEST_TEXT_WITH_SIM_FIRST_AND_LAST_NAME,
            tokens=(CommonSimUtils.get_active_sim_info(), ),
            text_color=CommonLocalizedStringColor.BLUE), )

        active_sim_info = CommonSimUtils.get_active_sim_info()
        dialog = CommonChooseResponseDialog(
            ModInfo.get_identity(),
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            responses,
            title_tokens=title_tokens,
            description_tokens=description_tokens,
            per_page=2)
        dialog.show(sim_info=active_sim_info,
                    on_chosen=_on_chosen,
                    include_previous_button=False)
    except Exception as ex:
        CommonExceptionHandler.log_exception(ModInfo.get_identity(),
                                             'Failed to show dialog',
                                             exception=ex)
        output('Failed to show dialog, please locate your exception log file.')
    output('Done showing.')
    def get_enum_by_name(name: str,
                         enum_type: Any,
                         default_value: Any = None) -> Any:
        """get_enum_by_name(name, enum_type, default_value=None)

        Retrieve an enum value by its a name.

        :param name: The name of an outfit category.
        :type name: str
        :param enum_type: The type of enum to retrieve.
        :type enum_type: Any
        :param default_value: The default value to return if an enum value was not found using the specified name. Default is None.
        :type default_value: Any, optional
        :return: The enum value with a name matching the specified name.
        :rtype: Any
        """
        try:
            if hasattr(enum_type, name):
                return getattr(enum_type, name)
            if name in enum_type:
                return enum_type[name]
            if hasattr(enum_type,
                       'name_to_value') and name in enum_type.name_to_value:
                return enum_type.name_to_value.get(name)
            return default_value
        except Exception as ex:
            CommonExceptionHandler.log_exception(
                ModInfo.get_identity(),
                'Failed to retrieve enum with name {} within type {}'.format(
                    name, enum_type),
                exception=ex)
            return default_value
    def run(
        self,
        sim_info: SimInfo,
        on_completed: Callable[[bool],
                               None] = CommonFunctionUtils.noop) -> bool:
        def _on_chosen(chosen_sim_info: SimInfo) -> None:
            if chosen_sim_info is None:
                on_completed(False)
                return
            self.run_with_sims(sim_info,
                               chosen_sim_info,
                               on_completed=on_completed)

        def _is_allowed(target_sim_info: SimInfo):
            return self.can_run_with_sims(sim_info, target_sim_info)

        dialog = CommonPremadeChooseSimOptionDialog(
            S4CMSimControlMenuStringId.SET_FAMILY_RELATIONS,
            0,
            title_tokens=(sim_info, ),
            include_sim_callback=_is_allowed,
            instanced_sims_only=False,
            mod_identity=ModInfo.get_identity(),
            on_sim_chosen=_on_chosen,
            on_close=lambda: on_completed(False))
        if not dialog.has_options():
            on_completed(False)
            return False
        # Sort the Sims in the dialog by their name.
        dialog._internal_dialog._rows = tuple(
            sorted(dialog._internal_dialog._rows,
                   key=lambda row: CommonSimNameUtils.get_full_name(
                       CommonSimUtils.get_sim_info(row.sim_id))))
        dialog.show(sim_info=sim_info)
        return True
 def _wrapper(*_: Any, **__: Any) -> Any:
     if primary_function is None:
         return False
     try:
         return primary_function(*_, *args, **__, **kwargs)
     except Exception as ex:
         CommonExceptionHandler.log_exception(ModInfo.get_identity().name, 'Error occurred while running function: {}'.format(primary_function.__name__), exception=ex)
 def _on_interaction_cancelled(self,
                               interaction: Interaction,
                               finishing_type: FinishingType,
                               cancel_reason_msg: str,
                               ignore_must_run: bool = False,
                               **kwargs) -> Union[bool, None]:
     if finishing_type is None:
         return None
     try:
         if not CommonEventRegistry.get().dispatch(
                 S4CLInteractionCancelledEvent(
                     interaction,
                     finishing_type,
                     cancel_reason_msg,
                     ignore_must_run=ignore_must_run,
                     **kwargs)):
             return False
     except Exception as ex:
         CommonExceptionHandler.log_exception(
             ModInfo.get_identity(),
             'Error occurred while running _on_interaction_cancelled for interaction {} with short name {} and display name {}'
             .format(
                 pformat(interaction),
                 CommonInteractionUtils.get_interaction_short_name(
                     interaction),
                 CommonInteractionUtils.get_interaction_display_name(
                     interaction)),
             exception=ex)
     return None
def _common_testing_show_targeted_question_dialog(_connection: int=None):
    output = sims4.commands.CheatOutput(_connection)
    output('Showing test targeted question dialog.')

    def _ok_chosen(_: UiDialogOkCancel):
        output('Ok option chosen.')

    def _cancel_chosen(_: UiDialogOkCancel):
        output('Cancel option chosen.')

    try:
        # LocalizedStrings within other LocalizedStrings
        description_tokens = (CommonLocalizationUtils.create_localized_string(CommonStringId.TESTING_TEST_TEXT_WITH_SIM_FIRST_AND_LAST_NAME, tokens=(CommonSimUtils.get_active_sim_info(),), text_color=CommonLocalizedStringColor.BLUE),)
        dialog = CommonTargetedQuestionDialog(
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            question_tokens=description_tokens,
            ok_text_identifier=CommonLocalizationUtils.create_localized_string(CommonStringId.TESTING_TEST_BUTTON_ONE, text_color=CommonLocalizedStringColor.RED),
            cancel_text_identifier=CommonStringId.TESTING_TEST_BUTTON_TWO
        )
        dialog.show(
            CommonSimUtils.get_active_sim_info(),
            tuple(CommonSimUtils.get_sim_info_for_all_sims_generator())[0],
            on_ok_selected=_ok_chosen,
            on_cancel_selected=_cancel_chosen
        )
    except Exception as ex:
        CommonExceptionHandler.log_exception(ModInfo.get_identity().name, 'Failed to show dialog', exception=ex)
        output('Failed to show ok cancel dialog, please locate your exception log file.')
    output('Done showing.')
    def remove_buff(sim_info: SimInfo, *buff_ids: int) -> bool:
        """remove_buff(sim_info, *buff_ids)

        Remove the specified buffs from a sim.

        :param sim_info: The sim to remove the specified buffs from.
        :type sim_info: SimInfo
        :param buff_ids: The decimal identifiers of Buffs to remove.
        :type buff_ids: int
        :return: True, if all of the specified buffs were successfully removed. False, if not.
        :rtype: bool
        """
        if sim_info is None:
            CommonExceptionHandler.log_exception(ModInfo.get_identity().name, 'Argument \'sim_info\' was \'None\' for \'{}\' of class \'{}\''.format(CommonBuffUtils.remove_buff.__name__, CommonBuffUtils.__name__))
            return False
        if not CommonComponentUtils.has_component(sim_info, CommonComponentType.BUFF):
            return False
        success = True
        for buff_identifier in buff_ids:
            buff_instance = CommonBuffUtils._load_buff_instance(buff_identifier)
            if buff_instance is None:
                continue
            if not sim_info.remove_buff_by_type(buff_instance):
                success = False
        return success
def _common_on_interaction_queued(original, self, interaction: Interaction, *_,
                                  **__) -> TestResult:
    try:
        result = CommonInteractionEventDispatcherService(
        )._on_interaction_queued(self, interaction, *_, **__)
        if result is None or result is True:
            original_result = original(self, interaction, *_, **__)
            CommonInteractionEventDispatcherService(
            )._on_interaction_post_queued(self, interaction, original_result,
                                          *_, **__)
            return original_result
        return result
    except Exception as ex:
        CommonExceptionHandler.log_exception(
            ModInfo.get_identity(),
            'Error occurred while running _on_interaction_queued for interaction {} with short name \'{}\' and display name {}. Args: {}, Kwargs: {}'
            .format(
                pformat(interaction),
                CommonInteractionUtils.get_interaction_short_name(interaction),
                CommonInteractionUtils.get_interaction_display_name(
                    interaction), _, __),
            exception=ex)
    return TestResult(
        False,
        'Interaction \'{}\' with short name \'{}\' Failed to Queue'.format(
            pformat(interaction),
            CommonInteractionUtils.get_interaction_short_name(interaction)))
Пример #18
0
    def generate_outfit(
            sim_info: SimInfo, outfit_category_and_index: Tuple[OutfitCategory,
                                                                int]) -> bool:
        """generate_outfit(sim_info, outfit_category_and_index)

        Generate an outfit for a Sim for the specified OutfitCategory and Index.

        .. note:: If an outfit exists in the specified OutfitCategory and Index, already, it will be overridden.

        :param sim_info: The Sim to generate an outfit for.
        :type sim_info: SimInfo
        :param outfit_category_and_index: The OutfitCategory and Index of the outfit to generate.
        :type outfit_category_and_index: Tuple[OutfitCategory, int]
        :return: True, if an outfit was generated successfully. False, if not.
        :rtype: bool
        """
        try:
            sim_info.on_outfit_generated(
                sim_info, CommonOutfitUtils.get_current_outfit(sim_info))
            sim_info.generate_outfit(*outfit_category_and_index)
            return True
        except Exception as ex:
            CommonExceptionHandler.log_exception(
                ModInfo.get_identity().name,
                'Problem occurred running function \'{}\'.'.format(
                    CommonOutfitUtils.generate_outfit.__name__),
                exception=ex)
        return False
Пример #19
0
    def spawn_sim(sim_info: SimInfo,
                  location: CommonLocation = None,
                  position: CommonVector3 = None,
                  **kwargs) -> bool:
        """spawn_sim(sim_info, location=None, position=None, **kwargs)

        Spawn a Sim.

        ..note:: Do not provide sim_position or sim_location in kwargs as they are already specified as location and position.

        :param sim_info: The Sim to Spawn.
        :type sim_info: SimInfo
        :param location: The location to spawn the Sim at. Default is None.
        :type location: CommonLocation, optional
        :param position: The position to spawn the Sim at. Default is None.
        :type position: CommonVector3, optional
        :return: True, if the Sim was spawned successfully. False, if not.
        :rtype: bool
        """
        try:
            SimSpawner.spawn_sim(sim_info,
                                 sim_location=location,
                                 sim_position=position,
                                 **kwargs)
        except Exception as ex:
            CommonExceptionHandler.log_exception(
                ModInfo.get_identity(),
                'Failed to spawn Sim with SimInfo \'{}\' at location \'{}\'.'.
                format(sim_info, location),
                exception=ex)
            return False
        return True
Пример #20
0
def _common_testing_spawn_object_on_lot(object_id: str = '20359',
                                        _connection: Any = None):
    output = CheatOutput(_connection)
    # noinspection PyBroadException
    try:
        object_id = int(object_id)
    except Exception:
        output('object_id must be an number.')
    output(
        'Attempting to spawn object on the current lot with id \'{}\'.'.format(
            object_id))
    from sims4communitylib.utils.sims.common_sim_location_utils import CommonSimLocationUtils
    from sims4communitylib.utils.sims.common_sim_utils import CommonSimUtils
    from sims4communitylib.utils.objects.common_object_utils import CommonObjectUtils
    active_sim_info = CommonSimUtils.get_active_sim_info()
    location = CommonSimLocationUtils.get_location(active_sim_info)
    try:
        game_object = CommonObjectSpawnUtils.spawn_object_on_lot(
            object_id, location)
        if game_object is None:
            output('Failed to spawn object.')
        else:
            output(
                'Object spawned successfully. Can you see it? Object Id: {}'.
                format(CommonObjectUtils.get_object_id(game_object)))
    except Exception as ex:
        CommonExceptionHandler.log_exception(
            ModInfo.get_identity(),
            'Error occurred trying to spawn object.',
            exception=ex)
    output('Done spawning object.')
Пример #21
0
    def get_buffs(sim_info: SimInfo) -> List[Buff]:
        """get_buffs(sim_info)

        Retrieve all buffs currently active on a Sim.

        :param sim_info: The Sim to retrieve the buffs of.
        :type sim_info: SimInfo
        :return: A collection of currently active buffs on the Sim.
        :rtype: Tuple[Buff]
        """
        if sim_info is None:
            CommonExceptionHandler.log_exception(
                ModInfo.get_identity(),
                'Argument \'sim_info\' was \'None\' for \'{}\' of class \'{}\''
                .format(CommonBuffUtils.get_buffs.__name__,
                        CommonBuffUtils.__name__))
            return list()
        if not CommonComponentUtils.has_component(sim_info,
                                                  CommonComponentType.BUFF):
            return list()
        from objects.components.buff_component import BuffComponent
        buff_component: BuffComponent = CommonComponentUtils.get_component(
            sim_info, CommonComponentType.BUFF)
        buffs = list()
        for buff in buff_component:
            if buff is None or not isinstance(buff, Buff):
                continue
            buffs.append(buff)
        return buffs
    def write_to_file(file_path: str, obj: Any, buffering: int=1, encoding: str= 'utf-8') -> bool:
        """write_to_file(file_path, obj, buffering=1, encoding='utf-8')

        Serialize an object to a file as JSON.

        :param file_path: The file to write to.
        :type file_path: str
        :param obj: The object to write as JSON.
        :type obj: Any
        :param buffering: See the built-in python :func:`~open` function documentation for more details.
        :type buffering: int, optional
        :param encoding: See the built-in python :func:`~open` function documentation for more details.
        :type encoding: str, optional
        :return: True if successful. False if not.
        :rtype: bool
        """
        if file_path is None or obj is None:
            return False
        try:
            with open(file_path, mode='w+', buffering=buffering, encoding=encoding) as file:
                json.dump(obj, file)
        except Exception as ex:
            CommonExceptionHandler.log_exception(ModInfo.get_identity().name, 'Error occurred while writing JSON to file \'{}\''.format(file_path), exception=ex)
            return False
        return True
 def _constraint_gen(cls, inst: Interaction, sim: Sim, target: Any, participant_type: ParticipantType=ParticipantType.Actor, **kwargs) -> Constraint:
     interaction_instance = inst if inst is not None else cls
     try:
         yield cls.on_constraint_gen(interaction_instance, sim or interaction_instance.sim, target or interaction_instance.target)
     except Exception as ex:
         CommonExceptionHandler.log_exception(ModInfo.get_identity(), 'Error occurred while running interaction \'{}\' _on_constraint_gen.'.format(cls.__name__), exception=ex)
     return super(CommonConstrainedSuperInteraction, interaction_instance)._constraint_gen(sim, interaction_instance.get_constraint_target(target), participant_type=participant_type)
    def has_buff(sim_info: SimInfo, *buff_ids: int) -> bool:
        """has_buff(sim_info, *buff_ids)

        Determine if any of the specified buffs are currently active on a sim.

        :param sim_info: The sim being checked.
        :type sim_info: SimInfo
        :param buff_ids: The decimal identifiers of Buffs.
        :type buff_ids: int
        :return: True if the sim has any of the specified buffs.
        :rtype: int
        """
        if sim_info is None:
            CommonExceptionHandler.log_exception(ModInfo.get_identity().name, 'Argument \'sim_info\' was \'None\' for \'{}\' of class \'{}\''.format(CommonBuffUtils.has_buff.__name__, CommonBuffUtils.__name__))
            return False
        if not CommonComponentUtils.has_component(sim_info, CommonComponentType.BUFF):
            return False
        if not buff_ids:
            return False
        sim_buffs = CommonBuffUtils.get_buffs(sim_info)
        for buff in sim_buffs:
            buff_id = getattr(buff, 'guid64', None)
            if buff_id in buff_ids:
                return True
        return False
Пример #25
0
 def inject_into(target_object: Any, target_function_name: str) -> Callable:
     """
         Obsolete: Please use inject_safely_into instead.
     """
     return CommonInjectionUtils.inject_safely_into(ModInfo.get_identity(),
                                                    target_object,
                                                    target_function_name)
Пример #26
0
    def run(
        self,
        sim_info: SimInfo,
        on_completed: Callable[[bool],
                               None] = CommonFunctionUtils.noop) -> bool:
        if not CommonHouseholdUtils.has_household(sim_info):
            on_completed(False)
            return False

        def _on_submit(amount: int, outcome: CommonChoiceOutcome):
            if outcome == CommonChoiceOutcome.ERROR:
                self.run(sim_info, on_completed=on_completed)
                return
            elif CommonChoiceOutcome.is_error_or_cancel(outcome):
                on_completed(False)
                return
            CommonHouseholdUtils.get_household(sim_info).funds.try_remove(
                amount,
                Consts_pb2.FUNDS_MONEY_CHEAT,
                sim=CommonSimUtils.get_sim_instance(sim_info),
                require_full_amount=False)
            on_completed(True)
            return True

        from sims4communitylib.dialogs.common_input_integer_dialog import CommonInputIntegerDialog
        dialog = CommonInputIntegerDialog(
            S4CMSimControlMenuStringId.HOW_MANY_SIMOLEONS,
            0,
            1000,
            min_value=1,
            mod_identity=ModInfo.get_identity())
        dialog.show(on_submit=_on_submit)
        return True
 def _run_interaction_gen(self, timeline: Any):
     super()._run_interaction_gen(timeline)
     try:
         return self.on_run(self.sim, self.target, timeline)
     except Exception as ex:
         CommonExceptionHandler.log_exception(ModInfo.get_identity(), 'Error occurred while running interaction \'{}\' on_run.'.format(self.__class__.__name__), exception=ex)
     return False
    def add_buff(sim_info: SimInfo, *buff_ids: int, buff_reason: Union[int, str, LocalizedString]=None) -> bool:
        """add_buff(sim_info, *buff_ids, buff_reason=None)

        Add the specified buffs to a sim.

        :param sim_info: The sim to add the specified buffs to.
        :type sim_info: SimInfo
        :param buff_ids: The decimal identifiers of buffs to add.
        :type buff_ids: int
        :param buff_reason: The text that will display when the player hovers over the buffs. What caused the buffs to be added.
        :type buff_reason: Union[int, str, LocalizedString], optional
        :return: True, if all of the specified buffs were successfully added. False, if not.
        :rtype: bool
        """
        if sim_info is None:
            CommonExceptionHandler.log_exception(ModInfo.get_identity().name, 'Argument \'sim_info\' was \'None\' for \'{}\' of class \'{}\''.format(CommonBuffUtils.add_buff.__name__, CommonBuffUtils.__name__))
            return False
        if not CommonComponentUtils.has_component(sim_info, CommonComponentType.BUFF):
            return False
        localized_buff_reason = CommonLocalizationUtils.create_localized_string(buff_reason)
        success = True
        for buff_identifier in buff_ids:
            buff_instance = CommonBuffUtils._load_buff_instance(buff_identifier)
            if buff_instance is None:
                continue
            if not sim_info.add_buff_from_op(buff_instance, buff_reason=localized_buff_reason):
                success = False
        return success
Пример #29
0
def _common_testing_show_ok_dialog(_connection: int=None):
    output = sims4.commands.CheatOutput(_connection)
    output('Showing test ok dialog.')

    def _on_acknowledged(_dialog: UiDialogOk):
        if _dialog.accepted:
            output('Ok option chosen.')
        else:
            output('Dialog closed.')

    try:
        # LocalizedStrings within other LocalizedStrings
        title_tokens = (CommonLocalizationUtils.create_localized_string(CommonStringId.TESTING_SOME_TEXT_FOR_TESTING, text_color=CommonLocalizedStringColor.GREEN),)
        description_tokens = (CommonLocalizationUtils.create_localized_string(CommonStringId.TESTING_TEST_TEXT_WITH_SIM_FIRST_AND_LAST_NAME, tokens=(CommonSimUtils.get_active_sim_info(),), text_color=CommonLocalizedStringColor.BLUE),)
        dialog = CommonOkDialog(
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            title_tokens=title_tokens,
            description_tokens=description_tokens,
            ok_text_identifier=CommonLocalizationUtils.create_localized_string(CommonStringId.TESTING_TEST_BUTTON_ONE, text_color=CommonLocalizedStringColor.RED)
        )
        dialog.show(on_acknowledged=_on_acknowledged)
    except Exception as ex:
        CommonExceptionHandler.log_exception(ModInfo.get_identity(), 'Failed to show dialog', exception=ex)
        output('Failed to show ok dialog, please locate your exception log file.')
    output('Done showing.')
class CommonSuperInteraction(CommonInteraction, SuperInteraction):
    """ A base for accessing super interaction hooks. """
    def _run_interaction_gen(self, timeline):
        super()._run_interaction_gen(timeline)
        try:
            return self.on_run(self.sim, self.target, timeline)
        except Exception as ex:
            CommonExceptionHandler.log_exception(
                ModInfo.get_identity().name,
                'Error occurred while running interaction \'{}\' on_run.'.
                format(self.__class__.__name__),
                exception=ex)
        return False

    # noinspection PyUnusedLocal
    @CommonExceptionHandler.catch_exceptions(ModInfo.get_identity().name,
                                             fallback_return=True)
    def on_run(self, interaction_sim: Sim, interaction_target: Any,
               timeline) -> bool:
        """
            Occurs upon the interaction being run.
        :param interaction_sim: The sim performing the interaction.
        :param interaction_target: The target of the interaction.
        :param timeline: The timeline the interaction is running on.
        :return: True if the interaction hook was executed successfully.
        """
        return True