Exemple #1
0
    def build_dialog(self,
                     on_submit: Callable[[Dict[int, Tuple[Any]]],
                                         Any] = CommonFunctionUtils.noop,
                     sim_info: SimInfo = None) -> Union[UiDialogBase, None]:
        """build_dialog(\
            on_submit=CommonFunctionUtils.noop,\
            sim_info=None\
        )

        Build the dialog and invoke the callbacks upon the player submitting their selections.

        :param on_submit: A callback invoked upon the player submitting the dialog and the choices within it.\
            Default is CommonFunctionUtils.noop. Each choice is mapped as follows The key is the dialog index starting at 0. The value is the choice made within that sub dialog. Default is CommonFunctionUtils.noop.
        :type on_submit: Callable[[Dict[int, Tuple[Any]]], Any], optional
        :param sim_info: The SimInfo of the Sim that will appear in the dialog image. The default Sim is the active Sim. Default is None.
        :type sim_info: SimInfo, optional
        """
        try:
            return self._internal_dialog.build_dialog(
                on_submit=self._on_submit(on_submit=on_submit),
                sim_info=sim_info)
        except Exception as ex:
            CommonExceptionHandler.log_exception(
                self.mod_identity,
                'multi_pane_choose_option.build_dialog',
                exception=ex)
        return None
Exemple #2
0
    def show(
        self,
        on_chosen: Callable[[Union[Tuple[Any], None], CommonChoiceOutcome], Any]=CommonFunctionUtils.noop,
        sim_info: SimInfo=None,
        should_show_names: bool=True,
        hide_row_descriptions: bool=False,
        column_count: int=3,
        min_selectable: int=1,
        max_selectable: int=1
    ):
        """Show the dialog and invoke the callbacks upon the player submitting their selection.

        :param on_chosen: A callback invoked upon the player submitting their chosen Sims from the list.
        :param sim_info: The SimInfo of the Sim that will appear in the dialog image. The default Sim is the active Sim.
        :param should_show_names: If True, then the names of the Sims will display in the dialog.
        :param hide_row_descriptions: A flag to hide the row descriptions.
        :param column_count: The number of columns to display Sims in.
        :param min_selectable: The minimum number of Sims that must be chosen.
        :param max_selectable: The maximum number of Sims that can be chosen.
        """
        try:
            return self._show(
                on_chosen=on_chosen,
                sim_info=sim_info,
                should_show_names=should_show_names,
                hide_row_descriptions=hide_row_descriptions,
                column_count=column_count,
                min_selectable=min_selectable,
                max_selectable=max_selectable
            )
        except Exception as ex:
            CommonExceptionHandler.log_exception(self.mod_identity.name, 'show', exception=ex)
    def set_current_progress_bar(self,
                                 percent: float,
                                 rate_change: float,
                                 start_message: bool = True):
        """set_current_progress_bar(initial_value, progress_rate)

        Set the current progress rate of the interaction.

        :param percent: A percentage indicating the starting progress.
        :type percent: float
        :param rate_change: A value that indicates how fast progress will be made.
        :type rate_change: float
        :param start_message: If True, progress will begin changing immediately. If False, it will not. Default is True.
        :type start_message: bool, optional
        """
        try:
            self._send_progress_bar_update_msg(percent,
                                               rate_change,
                                               start_msg=start_message)
        except Exception as ex:
            CommonExceptionHandler.log_exception(
                self.mod_identity.name,
                'Error occurred while running interaction \'{}\' set_current_progress_bar.'
                .format(self.__class__.__name__),
                exception=ex)
    def add_row(self,
                choice: ObjectPickerRow,
                *_,
                always_visible: bool = False,
                **__):
        """add_row(row, *_, always_on_visible=False, **__)

        Add a row to the dialog.

        :param choice: The row to add.
        :type choice: ObjectPickerRow
        :param always_visible: If set to True, the row will always appear in the dialog no matter which page. If False, the row will act as normal.
        :type always_visible: bool, optional
        """
        if not always_visible:
            super().add_row(choice, *_, **__)
            return
        try:
            self._always_visible_rows += (choice, )
        except Exception as ex:
            CommonExceptionHandler.log_exception(
                self.mod_identity,
                'An error occurred while running \'{}\''.format(
                    CommonChooseObjectsDialog.add_row.__name__),
                exception=ex)
 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 _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)))
    def show(
        self,
        sim_info: SimInfo,
        target_sim_info: SimInfo,
        on_ok_selected: Callable[[UiDialogOkCancel], Any]=CommonFunctionUtils.noop,
        on_cancel_selected: Callable[[UiDialogOkCancel], Any]=CommonFunctionUtils.noop
    ):
        """show(\
            sim_info,\
            target_sim_info,\
            on_ok_selected=CommonFunctionUtils.noop,\
            on_cancel_selected=CommonFunctionUtils.noop\
        )

        Show the dialog and invoke the callbacks upon the player making a choice.

        :param sim_info: The Sim that is the source of the question.
        :type sim_info: SimInfo
        :param target_sim_info: The Sim that is the target of the question.
        :type target_sim_info: SimInfo
        :param on_ok_selected: Invoked upon the player clicking the Ok button in the dialog.
        :type on_ok_selected: Callable[[UiDialogOkCancel], Any], optional
        :param on_cancel_selected: Invoked upon the player clicking the Cancel button in the dialog.
        :type on_cancel_selected: Callable[[UiDialogOkCancel], Any], optional
        """
        try:
            return self._show(
                sim_info,
                target_sim_info,
                on_ok_selected=on_ok_selected,
                on_cancel_selected=on_cancel_selected
            )
        except Exception as ex:
            CommonExceptionHandler.log_exception(self.mod_identity.name, 'show', exception=ex)
 def apply_posture_state(
         self,
         posture_state: PostureState,
         participant_type: ParticipantType = ParticipantType.Actor,
         sim: Sim = DEFAULT):
     """
         Apply a posture to a sim.
     :param posture_state: The posture state to apply.
     :param participant_type: The ParticipantType of the actor.
     :param sim: The sim to apply posture states to.
     :return: Unknown
     """
     try:
         (new_posture_state, new_participant_type,
          new_sim) = self.modify_posture_state(
              posture_state, participant_type=participant_type, sim=sim)
     except Exception as ex:
         CommonExceptionHandler.log_exception(
             self.mod_identity.name,
             'Error occurred while running interaction \'{}\' modify_posture_state.'
             .format(self.__class__.__name__),
             exception=ex)
         return None, None, None
     return super().apply_posture_state(
         new_posture_state,
         participant_type=new_participant_type,
         sim=new_sim)
Exemple #9
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.')
Exemple #10
0
 def safe_run(mod_identity: CommonModIdentity,
              primary_function: Callable[..., Any],
              fallback_function: Callable[...,
                                          Any], *args, **kwargs) -> Any:
     """
         Safely run a function, if the primary function throws an exception, the fallback function will be run instead.
     :param mod_identity: The identity of the mod running a function safely.
     :param primary_function: The primary function to safely run.
     :param fallback_function: A function called when the primary function throws an exception.
     :param args: Arguments to pass to both the primary function and fallback function.
     :param kwargs: Keyword Arguments to pass to both the primary function and fallback function.
     :return: The result of either the primary function or the fallback function if the primary threw an exception.
     """
     try:
         return primary_function(*args, **kwargs)
     except Exception as ex:
         # noinspection PyBroadException
         try:
             from sims4communitylib.exceptions.common_exceptions_handler import CommonExceptionHandler
             CommonExceptionHandler.log_exception(
                 mod_identity.name,
                 'Error occurred while running \'{}\''.format(
                     primary_function.__name__),
                 exception=ex)
         except Exception:
             pass
         return fallback_function(*args, **kwargs)
Exemple #11
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
Exemple #12
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
Exemple #13
0
    def show(self,
             on_submit: Callable[[Dict[int, Tuple[Any]], CommonChoiceOutcome],
                                 Any] = CommonFunctionUtils.noop,
             sim_info: SimInfo = None):
        """show(\
            on_submit=CommonFunctionUtils.noop,\
            sim_info=None\
        )

        Show the dialog and invoke the callbacks upon the player making a choice.

        :param on_submit: A callback invoked upon the player submitting the dialog and the choices within it.\
            Default is CommonFunctionUtils.noop. Each choice is mapped as follows The key is the dialog index starting at 0. The value is the choice made within that sub dialog.
        :type on_submit: Callable[[Dict[int, Tuple[Any]], CommonChoiceOutcome], Any], optional
        :param sim_info: The Sim that will appear in the dialog image. The default Sim is the Active Sim. Default is None.
        :type sim_info: SimInfo, optional
        """
        try:
            return self._show(on_submit=on_submit, sim_info=sim_info)
        except Exception as ex:
            CommonExceptionHandler.log_exception(
                self.mod_identity,
                'An error occurred while running \'{}\''.format(
                    CommonMultiPaneChooseDialog.show.__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
Exemple #15
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
 def _create_dialog(
     self,
     sim_info: SimInfo=None,
     should_show_names: bool=True,
     hide_row_descriptions: bool=False,
     column_count: int=3,
     min_selectable: int=1,
     max_selectable: int=1
 ) -> Union[UiSimPicker, None]:
     if column_count < 3:
         raise AttributeError('\'column_count\' must be at least 3 columns.')
     if column_count > 8:
         raise AttributeError('\'column_count\' can be no more than 8 columns.')
     try:
         return UiSimPicker.TunableFactory().default(
             sim_info or CommonSimUtils.get_active_sim_info(),
             title=lambda *_, **__: self.title,
             text=lambda *_, **__: self.description,
             min_selectable=min_selectable,
             max_selectable=max_selectable,
             should_show_names=should_show_names,
             hide_row_description=hide_row_descriptions,
             column_count=column_count
         )
     except Exception as ex:
         CommonExceptionHandler.log_exception(self.mod_identity.name, '_create_dialog', exception=ex)
     return None
Exemple #17
0
 def _run_interaction_gen(self, timeline: Timeline):
     super()._run_interaction_gen(timeline)
     try:
         return self.on_run(self.sim, self.target, timeline)
     except Exception as ex:
         CommonExceptionHandler.log_exception(self.mod_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
Exemple #19
0
def _common_testing_show_input_float_dialog(_connection: int = None):
    output = sims4.commands.CheatOutput(_connection)
    output('Showing test input float dialog.')

    def _on_chosen(choice: float, outcome: CommonChoiceOutcome):
        output('Chose {} with result: {}.'.format(pformat(choice),
                                                  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 = CommonInputFloatDialog(
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            CommonStringId.TESTING_TEST_TEXT_WITH_STRING_TOKEN,
            2.0,
            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.')
    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_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 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
 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 _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 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 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
    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 _dispatch(self, event: CommonEvent) -> 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(
                     event_handler.mod_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(),
             'Failed to dispatch event \'{}\''.format(event),
             exception=ex)
         return False
     return result
Exemple #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.')
    def show(
        self,
        on_chosen: Callable[[Any, CommonChoiceOutcome], Any]=CommonFunctionUtils.noop,
        sim_info: SimInfo=None,
        should_show_names: bool=True,
        hide_row_descriptions: bool=False,
        column_count: int=3
    ):
        """Show the dialog and invoke the callbacks upon the player making a choice.

        :param on_chosen: A callback invoked upon the player choosing a Sim from the list.
        :param sim_info: The SimInfo of the Sim that will appear in the dialog image. The default Sim is the active Sim.
        :param should_show_names: If True, then the names of the Sims will display in the dialog.
        :param hide_row_descriptions: A flag to hide the row descriptions.
        :param column_count: The number of columns to display Sims in.
        """
        try:
            return self._show(
                on_chosen=on_chosen,
                sim_info=sim_info,
                should_show_names=should_show_names,
                hide_row_descriptions=hide_row_descriptions,
                column_count=column_count
            )
        except Exception as ex:
            CommonExceptionHandler.log_exception(self.mod_identity.name, 'show', exception=ex)