text,length,is_long_context,metric_val,label_metric "CLASS zcl_abapgit_object_tabl DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super FINAL CREATE PUBLIC . PUBLIC SECTION. INTERFACES zif_abapgit_object . ALIASES mo_files FOR zif_abapgit_object~mo_files . PROTECTED SECTION. TYPES: BEGIN OF ty_segment_definition, segmentheader TYPE edisegmhd, segmentdefinition TYPE edisegmdef, segmentstructures TYPE STANDARD TABLE OF edisegstru WITH DEFAULT KEY, END OF ty_segment_definition. TYPES: ty_segment_definitions TYPE STANDARD TABLE OF ty_segment_definition WITH DEFAULT KEY. TYPES: BEGIN OF ty_tabl_extras, tddat TYPE tddat, END OF ty_tabl_extras. ""! get additional data like table authorization group ""! @parameter iv_tabname | name of the table METHODS read_extras IMPORTING iv_tabname TYPE ddobjname RETURNING VALUE(rs_tabl_extras) TYPE ty_tabl_extras. ""! Update additional data ""! @parameter iv_tabname | name of the table ""! @parameter is_tabl_extras | additional table data METHODS update_extras IMPORTING iv_tabname TYPE ddobjname is_tabl_extras TYPE ty_tabl_extras. ""! Delete additional data ""! @parameter iv_tabname | name of the table METHODS delete_extras IMPORTING iv_tabname TYPE ddobjname. ""! Serialize IDoc Segment type/definition if exits ""! @parameter io_xml | XML writer ""! @raising zcx_abapgit_exception | Exceptions METHODS serialize_idoc_segment IMPORTING io_xml TYPE REF TO zif_abapgit_xml_output RAISING zcx_abapgit_exception. ""! Deserialize IDoc Segment type/definition if exits ""! @parameter io_xml | XML writer ""! @parameter iv_package | Target package ""! @parameter rv_deserialized | It's a segment and was desserialized ""! @raising zcx_abapgit_exception | Exceptions METHODS deserialize_idoc_segment IMPORTING io_xml TYPE REF TO zif_abapgit_xml_input iv_package TYPE devclass RETURNING VALUE(rv_deserialized) TYPE abap_bool RAISING zcx_abapgit_exception. ""! Delete the IDoc Segment type if exists ""! @parameter rv_deleted | It's a segment and was deleted ""! @raising zcx_abapgit_exception | Exceptions METHODS delete_idoc_segment RETURNING VALUE(rv_deleted) TYPE abap_bool RAISING zcx_abapgit_exception. PRIVATE SECTION. TYPES: ty_dd03p_tt TYPE STANDARD TABLE OF dd03p . TYPES: BEGIN OF ty_dd02_text, ddlanguage TYPE dd02t-ddlanguage, ddtext TYPE dd02t-ddtext, END OF ty_dd02_text, ty_dd02_texts TYPE STANDARD TABLE OF ty_dd02_text. CONSTANTS c_longtext_id_tabl TYPE dokil-id VALUE 'TB' ##NO_TEXT. CONSTANTS: BEGIN OF c_s_dataname, segment_definition TYPE string VALUE 'SEGMENT_DEFINITION', tabl_extras TYPE string VALUE 'TABL_EXTRAS', END OF c_s_dataname. METHODS clear_dd03p_fields CHANGING !ct_dd03p TYPE ty_dd03p_tt . ""! Check if structure is an IDoc segment ""! @parameter rv_is_idoc_segment | It's an IDoc segment or not METHODS is_idoc_segment RETURNING VALUE(rv_is_idoc_segment) TYPE abap_bool. METHODS clear_dd03p_fields_common CHANGING !cs_dd03p TYPE dd03p . METHODS clear_dd03p_fields_dataelement CHANGING !cs_dd03p TYPE dd03p . METHODS: serialize_texts IMPORTING io_xml TYPE REF TO zif_abapgit_xml_output RAISING zcx_abapgit_exception, deserialize_texts IMPORTING io_xml TYPE REF TO zif_abapgit_xml_input is_dd02v TYPE dd02v RAISING zcx_abapgit_exception, is_db_table_category IMPORTING iv_tabclass TYPE dd02l-tabclass RETURNING VALUE(rv_is_db_table_type) TYPE dd02l-tabclass. ENDCLASS. CLASS ZCL_ABAPGIT_OBJECT_TABL IMPLEMENTATION. METHOD clear_dd03p_fields. CONSTANTS lc_comptype_dataelement TYPE comptype VALUE 'E'. DATA: lv_masklen TYPE c LENGTH 4. FIELD-SYMBOLS: TYPE dd03p. * remove nested structures DELETE ct_dd03p WHERE depth <> '00'. * remove fields from .INCLUDEs DELETE ct_dd03p WHERE adminfield <> '0'. LOOP AT ct_dd03p ASSIGNING WHERE NOT rollname IS INITIAL. clear_dd03p_fields_common( CHANGING cs_dd03p = ). lv_masklen = -masklen. IF lv_masklen = '' OR NOT lv_masklen CO '0123456789'. * make sure the field contains valid data, or the XML will dump CLEAR -masklen. ENDIF. IF -comptype = lc_comptype_dataelement. clear_dd03p_fields_dataelement( CHANGING cs_dd03p = ). ENDIF. IF -shlporigin = 'D'. * search help from domain CLEAR: -shlpfield, -shlpname. ENDIF. * XML output assumes correct field content IF -routputlen = ' '. CLEAR -routputlen. ENDIF. ENDLOOP. ENDMETHOD. METHOD clear_dd03p_fields_common. CLEAR: cs_dd03p-ddlanguage, cs_dd03p-dtelmaster, cs_dd03p-logflag, cs_dd03p-ddtext, cs_dd03p-reservedte, cs_dd03p-reptext, cs_dd03p-scrtext_s, cs_dd03p-scrtext_m, cs_dd03p-scrtext_l. ENDMETHOD. METHOD clear_dd03p_fields_dataelement. * type specified via data element CLEAR: cs_dd03p-domname, cs_dd03p-inttype, cs_dd03p-intlen, cs_dd03p-mask, cs_dd03p-memoryid, cs_dd03p-headlen, cs_dd03p-scrlen1, cs_dd03p-scrlen2, cs_dd03p-scrlen3, cs_dd03p-datatype, cs_dd03p-leng, cs_dd03p-outputlen, cs_dd03p-deffdname, cs_dd03p-convexit, cs_dd03p-entitytab, cs_dd03p-dommaster, cs_dd03p-domname3l, cs_dd03p-decimals, cs_dd03p-lowercase, cs_dd03p-signflag. ENDMETHOD. METHOD delete_extras. DELETE FROM tddat WHERE tabname = iv_tabname. ENDMETHOD. METHOD delete_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. DATA lv_result LIKE sy-subrc. IF is_idoc_segment( ) = abap_false. rv_deleted = abap_false. RETURN. ""previous XML version or no IDoc segment ENDIF. rv_deleted = abap_true. lv_segment_type = ms_item-obj_name. CALL FUNCTION 'SEGMENT_DELETE' EXPORTING segmenttyp = lv_segment_type IMPORTING result = lv_result EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDMETHOD. METHOD deserialize_idoc_segment. DATA lv_result LIKE sy-subrc. DATA lt_segment_definitions TYPE ty_segment_definitions. DATA lv_package TYPE devclass. DATA lv_uname TYPE sy-uname. FIELD-SYMBOLS TYPE ty_segment_definition. rv_deserialized = abap_false. TRY. io_xml->read( EXPORTING iv_name = c_s_dataname-segment_definition CHANGING cg_data = lt_segment_definitions ). CATCH zcx_abapgit_exception. RETURN. ""previous XML version or no IDoc segment ENDTRY. IF lines( lt_segment_definitions ) = 0. RETURN. ""no IDoc segment ENDIF. rv_deserialized = abap_true. lv_package = iv_package. LOOP AT lt_segment_definitions ASSIGNING . -segmentheader-presp = -segmentheader-pwork = cl_abap_syst=>get_user_name( ). CALL FUNCTION 'SEGMENT_READ' EXPORTING segmenttyp = -segmentheader-segtyp IMPORTING result = lv_result EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. CALL FUNCTION 'SEGMENT_CREATE' IMPORTING segmentdefinition = -segmentdefinition TABLES segmentstructure = -segmentstructures CHANGING segmentheader = -segmentheader devclass = lv_package EXCEPTIONS OTHERS = 1. ELSE. CALL FUNCTION 'SEGMENT_MODIFY' CHANGING segmentheader = -segmentheader devclass = lv_package EXCEPTIONS OTHERS = 1. IF sy-subrc = 0. CALL FUNCTION 'SEGMENTDEFINITION_MODIFY' TABLES segmentstructure = -segmentstructures CHANGING segmentdefinition = -segmentdefinition EXCEPTIONS OTHERS = 1. ENDIF. ENDIF. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDLOOP. lv_uname = cl_abap_syst=>get_user_name( ). CALL FUNCTION 'TR_TADIR_INTERFACE' EXPORTING wi_test_modus = abap_false wi_tadir_pgmid = 'R3TR' wi_tadir_object = ms_item-obj_type wi_tadir_obj_name = ms_item-obj_name wi_tadir_author = lv_uname wi_tadir_devclass = iv_package wi_tadir_masterlang = mv_language iv_set_edtflag = abap_true iv_delflag = abap_false EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from TR_TADIR_INTERFACE' ). ENDIF. ENDMETHOD. METHOD deserialize_texts. DATA: lv_name TYPE ddobjname, ls_dd02v_tmp TYPE dd02v, lt_i18n_langs TYPE TABLE OF langu, lt_dd02_texts TYPE ty_dd02_texts. FIELD-SYMBOLS: LIKE LINE OF lt_i18n_langs, LIKE LINE OF lt_dd02_texts. lv_name = ms_item-obj_name. io_xml->read( EXPORTING iv_name = 'I18N_LANGS' CHANGING cg_data = lt_i18n_langs ). io_xml->read( EXPORTING iv_name = 'DD02_TEXTS' CHANGING cg_data = lt_dd02_texts ). SORT lt_i18n_langs. SORT lt_dd02_texts BY ddlanguage. "" Optimization LOOP AT lt_i18n_langs ASSIGNING . "" Table description ls_dd02v_tmp = is_dd02v. READ TABLE lt_dd02_texts ASSIGNING WITH KEY ddlanguage = . IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |DD02_TEXTS cannot find lang { } in XML| ). ENDIF. MOVE-CORRESPONDING TO ls_dd02v_tmp. CALL FUNCTION 'DDIF_TABL_PUT' EXPORTING name = lv_name dd02v_wa = ls_dd02v_tmp EXCEPTIONS tabl_not_found = 1 name_inconsistent = 2 tabl_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |error from DDIF_TABL_PUT @TEXTS, { sy-subrc }| ). ENDIF. ENDLOOP. ENDMETHOD. METHOD is_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. lv_segment_type = ms_item-obj_name. SELECT SINGLE segtyp FROM edisegment INTO lv_segment_type WHERE segtyp = lv_segment_type. rv_is_idoc_segment = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD read_extras. SELECT SINGLE * FROM tddat INTO rs_tabl_extras-tddat WHERE tabname = iv_tabname. ENDMETHOD. METHOD serialize_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. DATA lv_result LIKE sy-subrc. DATA lv_devclass TYPE devclass. DATA lt_segmentdefinitions TYPE STANDARD TABLE OF edisegmdef. DATA ls_segment_definition TYPE ty_segment_definition. DATA lt_segment_definitions TYPE ty_segment_definitions. FIELD-SYMBOLS: TYPE edisegmdef. IF is_idoc_segment( ) = abap_false. RETURN. ENDIF. lv_segment_type = ms_item-obj_name. CALL FUNCTION 'SEGMENT_READ' EXPORTING segmenttyp = lv_segment_type IMPORTING result = lv_result TABLES segmentdefinition = lt_segmentdefinitions EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. LOOP AT lt_segmentdefinitions ASSIGNING . CLEAR ls_segment_definition. CALL FUNCTION 'SEGMENTDEFINITION_READ' EXPORTING segmenttyp = -segtyp IMPORTING result = lv_result devclass = lv_devclass segmentheader = ls_segment_definition-segmentheader segmentdefinition = ls_segment_definition-segmentdefinition TABLES segmentstructure = ls_segment_definition-segmentstructures CHANGING version = -version EXCEPTIONS no_authority = 1 segment_not_existing = 2 OTHERS = 3. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. zcl_abapgit_object_idoc=>clear_idoc_segement_fields( CHANGING cg_structure = ls_segment_definition-segmentdefinition ). zcl_abapgit_object_idoc=>clear_idoc_segement_fields( CHANGING cg_structure = ls_segment_definition-segmentheader ). APPEND ls_segment_definition TO lt_segment_definitions. ENDLOOP. io_xml->add( iv_name = c_s_dataname-segment_definition ig_data = lt_segment_definitions ). ENDMETHOD. METHOD serialize_texts. DATA: lv_name TYPE ddobjname, lv_index TYPE i, ls_dd02v TYPE dd02v, lt_dd02_texts TYPE ty_dd02_texts, lt_i18n_langs TYPE TABLE OF langu. FIELD-SYMBOLS: LIKE LINE OF lt_i18n_langs, LIKE LINE OF lt_dd02_texts. IF io_xml->i18n_params( )-serialize_master_lang_only = abap_true. RETURN. ENDIF. lv_name = ms_item-obj_name. "" Collect additional languages, skip master lang - it was serialized already SELECT DISTINCT ddlanguage AS langu INTO TABLE lt_i18n_langs FROM dd02v WHERE tabname = lv_name AND ddlanguage <> mv_language. ""#EC CI_SUBRC LOOP AT lt_i18n_langs ASSIGNING . lv_index = sy-tabix. CALL FUNCTION 'DDIF_TABL_GET' EXPORTING name = lv_name langu = IMPORTING dd02v_wa = ls_dd02v EXCEPTIONS illegal_input = 1 OTHERS = 2. IF sy-subrc <> 0 OR ls_dd02v-ddlanguage IS INITIAL. DELETE lt_i18n_langs INDEX lv_index. "" Don't save this lang CONTINUE. ENDIF. APPEND INITIAL LINE TO lt_dd02_texts ASSIGNING . MOVE-CORRESPONDING ls_dd02v TO . ENDLOOP. SORT lt_i18n_langs ASCENDING. SORT lt_dd02_texts BY ddlanguage ASCENDING. IF lines( lt_i18n_langs ) > 0. io_xml->add( iv_name = 'I18N_LANGS' ig_data = lt_i18n_langs ). io_xml->add( iv_name = 'DD02_TEXTS' ig_data = lt_dd02_texts ). ENDIF. ENDMETHOD. METHOD update_extras. IF is_tabl_extras-tddat IS INITIAL. delete_extras( iv_tabname = iv_tabname ). ELSE. MODIFY tddat FROM is_tabl_extras-tddat. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~changed_by. TYPES: BEGIN OF ty_data, as4user TYPE dd02l-as4user, as4date TYPE dd02l-as4date, as4time TYPE dd02l-as4time, END OF ty_data. DATA: lt_data TYPE STANDARD TABLE OF ty_data WITH DEFAULT KEY, ls_data LIKE LINE OF lt_data. SELECT as4user as4date as4time FROM dd02l INTO TABLE lt_data WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SELECT as4user as4date as4time APPENDING TABLE lt_data FROM dd09l WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SELECT as4user as4date as4time APPENDING TABLE lt_data FROM dd12l WHERE sqltab = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SORT lt_data BY as4date DESCENDING as4time DESCENDING. READ TABLE lt_data INDEX 1 INTO ls_data. IF sy-subrc = 0. rv_user = ls_data-as4user. ELSE. rv_user = c_user_unknown. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: lv_objname TYPE rsedd0-ddobjname, lv_no_ask TYPE abap_bool, lv_subrc TYPE sy-subrc, BEGIN OF ls_dd02l, tabname TYPE dd02l-tabname, tabclass TYPE dd02l-tabclass, sqltab TYPE dd02l-sqltab, END OF ls_dd02l. IF zif_abapgit_object~exists( ) = abap_false. "" Proxies e.g. delete on its own, nothing todo here then. RETURN. ENDIF. lv_objname = ms_item-obj_name. IF delete_idoc_segment( ) = abap_false. lv_no_ask = abap_true. SELECT SINGLE tabname tabclass sqltab FROM dd02l INTO CORRESPONDING FIELDS OF ls_dd02l WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. IF sy-subrc = 0 AND is_db_table_category( ls_dd02l-tabclass ) = abap_true. CALL FUNCTION 'DD_EXISTS_DATA' EXPORTING reftab = ls_dd02l-sqltab tabclass = ls_dd02l-tabclass tabname = ls_dd02l-tabname IMPORTING subrc = lv_subrc EXCEPTIONS missing_reftab = 1 sql_error = 2 buffer_overflow = 3 unknown_error = 4 OTHERS = 5. IF sy-subrc = 0 AND lv_subrc = 0. lv_no_ask = abap_false. ENDIF. ENDIF. delete_ddic( iv_objtype = 'T' iv_no_ask = lv_no_ask ). delete_longtexts( c_longtext_id_tabl ). delete_extras( iv_tabname = lv_objname ). ENDIF. ENDMETHOD. METHOD zif_abapgit_object~deserialize. DATA: lv_name TYPE ddobjname, lv_tname TYPE trobj_name, ls_dd02v TYPE dd02v, ls_dd09l TYPE dd09l, lt_dd03p TYPE TABLE OF dd03p, lt_dd05m TYPE TABLE OF dd05m, lt_dd08v TYPE TABLE OF dd08v, lt_dd12v TYPE dd12vtab, lt_dd17v TYPE dd17vtab, ls_dd17v LIKE LINE OF lt_dd17v, lt_secondary LIKE lt_dd17v, lt_dd35v TYPE TABLE OF dd35v, lt_dd36m TYPE dd36mttyp, ls_dd12v LIKE LINE OF lt_dd12v, lv_refs TYPE abap_bool, ls_extras TYPE ty_tabl_extras. FIELD-SYMBOLS: TYPE dd03p. IF deserialize_idoc_segment( io_xml = io_xml iv_package = iv_package ) = abap_false. io_xml->read( EXPORTING iv_name = 'DD02V' CHANGING cg_data = ls_dd02v ). io_xml->read( EXPORTING iv_name = 'DD09L' CHANGING cg_data = ls_dd09l ). io_xml->read( EXPORTING iv_name = 'DD03P_TABLE' CHANGING cg_data = lt_dd03p ). "" DDIC Step: Replace REF TO class/interface with generic reference to avoid cyclic dependency LOOP AT lt_dd03p ASSIGNING WHERE datatype = 'REF'. IF iv_step = zif_abapgit_object=>gc_step_id-ddic. -rollname = 'OBJECT'. ELSE. lv_refs = abap_true. ENDIF. ENDLOOP. io_xml->read( EXPORTING iv_name = 'DD05M_TABLE' CHANGING cg_data = lt_dd05m ). io_xml->read( EXPORTING iv_name = 'DD08V_TABLE' CHANGING cg_data = lt_dd08v ). io_xml->read( EXPORTING iv_name = 'DD12V' CHANGING cg_data = lt_dd12v ). io_xml->read( EXPORTING iv_name = 'DD17V' CHANGING cg_data = lt_dd17v ). io_xml->read( EXPORTING iv_name = 'DD35V_TALE' CHANGING cg_data = lt_dd35v ). io_xml->read( EXPORTING iv_name = 'DD36M' CHANGING cg_data = lt_dd36m ). "" DDIC Step: Remove references to search helps and foreign keys IF iv_step = zif_abapgit_object=>gc_step_id-ddic. CLEAR: lt_dd08v, lt_dd35v, lt_dd36m. ENDIF. IF iv_step = zif_abapgit_object=>gc_step_id-late AND lv_refs = abap_false AND lines( lt_dd35v ) = 0 AND lines( lt_dd08v ) = 0. RETURN. "" already active ENDIF. corr_insert( iv_package = iv_package ig_object_class = 'DICT' ). lv_name = ms_item-obj_name. "" type conversion CALL FUNCTION 'DDIF_TABL_PUT' EXPORTING name = lv_name dd02v_wa = ls_dd02v dd09l_wa = ls_dd09l TABLES dd03p_tab = lt_dd03p dd05m_tab = lt_dd05m dd08v_tab = lt_dd08v dd35v_tab = lt_dd35v dd36m_tab = lt_dd36m EXCEPTIONS tabl_not_found = 1 name_inconsistent = 2 tabl_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_TABL_PUT' ). ENDIF. zcl_abapgit_objects_activation=>add_item( ms_item ). * handle indexes LOOP AT lt_dd12v INTO ls_dd12v. * todo, call corr_insert? CLEAR lt_secondary. LOOP AT lt_dd17v INTO ls_dd17v WHERE sqltab = ls_dd12v-sqltab AND indexname = ls_dd12v-indexname. APPEND ls_dd17v TO lt_secondary. ENDLOOP. CALL FUNCTION 'DDIF_INDX_PUT' EXPORTING name = ls_dd12v-sqltab id = ls_dd12v-indexname dd12v_wa = ls_dd12v TABLES dd17v_tab = lt_secondary EXCEPTIONS indx_not_found = 1 name_inconsistent = 2 indx_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_INDX_PUT' ). ENDIF. CALL FUNCTION 'DD_DD_TO_E071' EXPORTING type = 'INDX' name = ls_dd12v-sqltab id = ls_dd12v-indexname IMPORTING obj_name = lv_tname. zcl_abapgit_objects_activation=>add( iv_type = 'INDX' iv_name = lv_tname ). ENDLOOP. deserialize_texts( io_xml = io_xml is_dd02v = ls_dd02v ). deserialize_longtexts( io_xml ). io_xml->read( EXPORTING iv_name = c_s_dataname-tabl_extras CHANGING cg_data = ls_extras ). update_extras( iv_tabname = lv_name is_tabl_extras = ls_extras ). ENDIF. ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: lv_tabname TYPE dd02l-tabname. lv_tabname = ms_item-obj_name. "" Check nametab because it's fast CALL FUNCTION 'DD_GET_NAMETAB_HEADER' EXPORTING tabname = lv_tabname EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc <> 0. "" Check for new, inactive, or modified versions that might not be in nametab SELECT SINGLE tabname FROM dd02l INTO lv_tabname WHERE tabname = lv_tabname. ENDIF. rv_bool = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. DATA: li_local_version_output TYPE REF TO zif_abapgit_xml_output, li_local_version_input TYPE REF TO zif_abapgit_xml_input. CREATE OBJECT li_local_version_output TYPE zcl_abapgit_xml_output. me->zif_abapgit_object~serialize( li_local_version_output ). CREATE OBJECT li_local_version_input TYPE zcl_abapgit_xml_input EXPORTING iv_xml = li_local_version_output->render( ). CREATE OBJECT ri_comparator TYPE zcl_abapgit_object_tabl_compar EXPORTING ii_local = li_local_version_input. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-ddic TO rt_steps. APPEND zif_abapgit_object=>gc_step_id-late TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). rs_metadata-ddic = abap_true. ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. rv_is_locked = exists_a_lock_entry_for( iv_lock_object = 'ESDICT' iv_argument = |{ ms_item-obj_type }{ ms_item-obj_name }| ). ENDMETHOD. METHOD zif_abapgit_object~jump. jump_se11( iv_radio = 'RSRD1-DDTYPE' iv_field = 'RSRD1-DDTYPE_VAL' ). ENDMETHOD. METHOD zif_abapgit_object~serialize. DATA: lv_name TYPE ddobjname, ls_dd02v TYPE dd02v, ls_dd09l TYPE dd09l, lt_dd03p TYPE ty_dd03p_tt, lt_dd05m TYPE TABLE OF dd05m, lt_dd08v TYPE TABLE OF dd08v, lt_dd12v TYPE dd12vtab, lt_dd17v TYPE dd17vtab, lt_dd35v TYPE TABLE OF dd35v, lv_index LIKE sy-index, lt_dd36m TYPE dd36mttyp, ls_extras TYPE ty_tabl_extras. FIELD-SYMBOLS: LIKE LINE OF lt_dd12v, LIKE LINE OF lt_dd05m, LIKE LINE OF lt_dd36m, TYPE any. lv_name = ms_item-obj_name. CALL FUNCTION 'DDIF_TABL_GET' EXPORTING name = lv_name langu = mv_language IMPORTING dd02v_wa = ls_dd02v dd09l_wa = ls_dd09l TABLES dd03p_tab = lt_dd03p dd05m_tab = lt_dd05m dd08v_tab = lt_dd08v dd12v_tab = lt_dd12v dd17v_tab = lt_dd17v dd35v_tab = lt_dd35v dd36m_tab = lt_dd36m EXCEPTIONS illegal_input = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_TABL_GET' ). ENDIF. IF ls_dd02v IS INITIAL. RETURN. "" object does not exits ENDIF. CLEAR: ls_dd02v-as4user, ls_dd02v-as4date, ls_dd02v-as4time. * reset numeric field, so XML does not crash IF ls_dd02v-prozpuff = ''. CLEAR ls_dd02v-prozpuff. ENDIF. IF ls_dd02v-datmin = ''. CLEAR ls_dd02v-datmin. ENDIF. IF ls_dd02v-datmax = ''. CLEAR ls_dd02v-datmax. ENDIF. IF ls_dd02v-datavg = ''. CLEAR ls_dd02v-datavg. ENDIF. CLEAR: ls_dd09l-as4user, ls_dd09l-as4date, ls_dd09l-as4time. ASSIGN COMPONENT 'ROWORCOLST' OF STRUCTURE ls_dd09l TO . IF sy-subrc = 0 AND = 'C'. CLEAR . ""To avoid diff errors. This field doesn't exists in all releases ENDIF. LOOP AT lt_dd12v ASSIGNING . CLEAR: -as4user, -as4date, -as4time. ENDLOOP. clear_dd03p_fields( CHANGING ct_dd03p = lt_dd03p ). * remove foreign keys inherited from .INCLUDEs DELETE lt_dd08v WHERE noinherit = 'N'. LOOP AT lt_dd05m ASSIGNING . lv_index = sy-tabix. READ TABLE lt_dd08v WITH KEY fieldname = -fieldname TRANSPORTING NO FIELDS. IF sy-subrc <> 0. DELETE lt_dd05m INDEX lv_index. ENDIF. ENDLOOP. * remove inherited search helps DELETE lt_dd35v WHERE shlpinher = abap_true. LOOP AT lt_dd36m ASSIGNING . lv_index = sy-tabix. READ TABLE lt_dd35v WITH KEY fieldname = -fieldname TRANSPORTING NO FIELDS. IF sy-subrc <> 0. DELETE lt_dd36m INDEX lv_index. ENDIF. ENDLOOP. io_xml->add( iv_name = 'DD02V' ig_data = ls_dd02v ). IF NOT ls_dd09l IS INITIAL. io_xml->add( iv_name = 'DD09L' ig_data = ls_dd09l ). ENDIF. io_xml->add( iv_name = 'DD03P_TABLE' ig_data = lt_dd03p ). io_xml->add( iv_name = 'DD05M_TABLE' ig_data = lt_dd05m ). io_xml->add( iv_name = 'DD08V_TABLE' ig_data = lt_dd08v ). io_xml->add( iv_name = 'DD12V' ig_data = lt_dd12v ). io_xml->add( iv_name = 'DD17V' ig_data = lt_dd17v ). io_xml->add( iv_name = 'DD35V_TALE' ig_data = lt_dd35v ). io_xml->add( iv_name = 'DD36M' ig_data = lt_dd36m ). serialize_texts( io_xml ). serialize_longtexts( ii_xml = io_xml iv_longtext_id = c_longtext_id_tabl ). serialize_idoc_segment( io_xml ). ls_extras = read_extras( iv_tabname = lv_name ). io_xml->add( iv_name = c_s_dataname-tabl_extras ig_data = ls_extras ). ENDMETHOD. METHOD is_db_table_category. "" values from domain TABCLASS rv_is_db_table_type = boolc( iv_tabclass = 'TRANSP' OR iv_tabclass = 'CLUSTER' OR iv_tabclass = 'POOL' ). ENDMETHOD. ENDCLASS. ",8419,False,1907.6292352124126,median "CLASS zcl_abapgit_html_form DEFINITION PUBLIC FINAL CREATE PRIVATE. PUBLIC SECTION. CONSTANTS c_rows TYPE string VALUE 'rows'. CONSTANTS: BEGIN OF c_cmd_type, input TYPE i VALUE 1, link TYPE i VALUE 2, button TYPE i VALUE 3, END OF c_cmd_type. CLASS-METHODS create IMPORTING !iv_form_id TYPE csequence OPTIONAL !iv_help_page TYPE csequence OPTIONAL RETURNING VALUE(ro_form) TYPE REF TO zcl_abapgit_html_form. METHODS render IMPORTING !iv_form_class TYPE csequence !io_values TYPE REF TO zcl_abapgit_string_map !io_validation_log TYPE REF TO zcl_abapgit_string_map OPTIONAL RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html. METHODS command IMPORTING !iv_label TYPE csequence !iv_action TYPE csequence !iv_is_main TYPE abap_bool DEFAULT abap_false !iv_cmd_type TYPE i DEFAULT 1 RETURNING VALUE(ro_self) TYPE REF TO zcl_abapgit_html_form. METHODS text IMPORTING !iv_label TYPE csequence !iv_name TYPE csequence !iv_hint TYPE csequence OPTIONAL !iv_required TYPE abap_bool DEFAULT abap_false !iv_upper_case TYPE abap_bool DEFAULT abap_false !iv_readonly TYPE abap_bool DEFAULT abap_false !iv_password TYPE abap_bool DEFAULT abap_false !iv_placeholder TYPE csequence OPTIONAL !iv_side_action TYPE csequence OPTIONAL !iv_min TYPE i DEFAULT cl_abap_math=>min_int4 !iv_max TYPE i DEFAULT cl_abap_math=>max_int4 RETURNING VALUE(ro_self) TYPE REF TO zcl_abapgit_html_form. METHODS textarea IMPORTING !iv_label TYPE csequence !iv_name TYPE csequence !iv_hint TYPE csequence OPTIONAL !iv_required TYPE abap_bool DEFAULT abap_false !iv_readonly TYPE abap_bool DEFAULT abap_false !iv_placeholder TYPE csequence OPTIONAL RETURNING VALUE(ro_self) TYPE REF TO zcl_abapgit_html_form. METHODS number IMPORTING !iv_label TYPE csequence !iv_name TYPE csequence !iv_hint TYPE csequence OPTIONAL !iv_required TYPE abap_bool DEFAULT abap_false !iv_readonly TYPE abap_bool DEFAULT abap_false !iv_min TYPE i DEFAULT cl_abap_math=>min_int4 !iv_max TYPE i DEFAULT cl_abap_math=>max_int4 RETURNING VALUE(ro_self) TYPE REF TO zcl_abapgit_html_form. METHODS checkbox IMPORTING !iv_label TYPE csequence !iv_name TYPE csequence !iv_hint TYPE csequence OPTIONAL RETURNING VALUE(ro_self) TYPE REF TO zcl_abapgit_html_form. METHODS radio IMPORTING !iv_label TYPE csequence !iv_name TYPE csequence !iv_default_value TYPE csequence OPTIONAL !iv_hint TYPE csequence OPTIONAL RETURNING VALUE(ro_self) TYPE REF TO zcl_abapgit_html_form. METHODS option IMPORTING !iv_label TYPE csequence !iv_value TYPE csequence RETURNING VALUE(ro_self) TYPE REF TO zcl_abapgit_html_form. METHODS table IMPORTING !iv_label TYPE csequence !iv_name TYPE csequence !iv_hint TYPE csequence OPTIONAL RETURNING VALUE(ro_self) TYPE REF TO zcl_abapgit_html_form. METHODS column IMPORTING !iv_label TYPE csequence !iv_width TYPE csequence OPTIONAL !iv_readonly TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ro_self) TYPE REF TO zcl_abapgit_html_form. METHODS start_group IMPORTING !iv_label TYPE csequence !iv_name TYPE csequence !iv_hint TYPE csequence OPTIONAL RETURNING VALUE(ro_self) TYPE REF TO zcl_abapgit_html_form. METHODS normalize_form_data IMPORTING !io_form_data TYPE REF TO zcl_abapgit_string_map RETURNING VALUE(ro_form_data) TYPE REF TO zcl_abapgit_string_map RAISING zcx_abapgit_exception. METHODS validate_required_fields IMPORTING !io_form_data TYPE REF TO zcl_abapgit_string_map RETURNING VALUE(ro_validation_log) TYPE REF TO zcl_abapgit_string_map RAISING zcx_abapgit_exception. METHODS is_empty IMPORTING !io_form_data TYPE REF TO zcl_abapgit_string_map RETURNING VALUE(rv_empty) TYPE abap_bool RAISING zcx_abapgit_exception. METHODS hidden IMPORTING !iv_name TYPE csequence RETURNING VALUE(ro_self) TYPE REF TO zcl_abapgit_html_form. PROTECTED SECTION. PRIVATE SECTION. TYPES: BEGIN OF ty_subitem, label TYPE string, value TYPE string, readonly TYPE abap_bool, END OF ty_subitem. TYPES: ty_subitems TYPE STANDARD TABLE OF ty_subitem WITH DEFAULT KEY. TYPES: BEGIN OF ty_field, type TYPE i, name TYPE string, label TYPE string, hint TYPE string, dblclick TYPE string, placeholder TYPE string, required TYPE string, upper_case TYPE abap_bool, item_class TYPE string, error TYPE string, default_value TYPE string, side_action TYPE string, subitems TYPE ty_subitems, readonly TYPE abap_bool, password TYPE abap_bool, min TYPE i, max TYPE i, * onclick ??? END OF ty_field. TYPES: BEGIN OF ty_command, label TYPE string, action TYPE string, is_main TYPE abap_bool, cmd_type TYPE i, * onclick ??? END OF ty_command. TYPES: BEGIN OF ty_attr, value TYPE string, error TYPE string, hint TYPE string, readonly TYPE string, placeholder TYPE string, required TYPE string, END OF ty_attr. CONSTANTS: BEGIN OF c_field_type, text TYPE i VALUE 1, radio TYPE i VALUE 2, checkbox TYPE i VALUE 3, field_group TYPE i VALUE 4, number TYPE i VALUE 5, textarea TYPE i VALUE 6, table TYPE i VALUE 7, hidden TYPE i VALUE 8, END OF c_field_type. DATA: mt_fields TYPE STANDARD TABLE OF ty_field WITH UNIQUE SORTED KEY by_name COMPONENTS name. DATA: mt_commands TYPE STANDARD TABLE OF ty_command. DATA mv_form_id TYPE string. DATA mv_help_page TYPE string. METHODS render_field IMPORTING !ii_html TYPE REF TO zif_abapgit_html !io_values TYPE REF TO zcl_abapgit_string_map !io_validation_log TYPE REF TO zcl_abapgit_string_map !is_field TYPE ty_field. METHODS render_field_text IMPORTING !ii_html TYPE REF TO zif_abapgit_html !is_field TYPE ty_field !is_attr TYPE ty_attr. METHODS render_field_textarea IMPORTING !ii_html TYPE REF TO zif_abapgit_html !is_field TYPE ty_field !is_attr TYPE ty_attr. METHODS render_field_checkbox IMPORTING !ii_html TYPE REF TO zif_abapgit_html !is_field TYPE ty_field !is_attr TYPE ty_attr. METHODS render_field_radio IMPORTING !ii_html TYPE REF TO zif_abapgit_html !is_field TYPE ty_field !is_attr TYPE ty_attr. METHODS render_field_table IMPORTING !ii_html TYPE REF TO zif_abapgit_html !is_field TYPE ty_field !is_attr TYPE ty_attr !io_values TYPE REF TO zcl_abapgit_string_map. METHODS render_command IMPORTING !ii_html TYPE REF TO zif_abapgit_html !is_cmd TYPE ty_command. METHODS render_field_hidden IMPORTING !ii_html TYPE REF TO zif_abapgit_html !is_field TYPE ty_field !is_attr TYPE ty_attr. ENDCLASS. CLASS zcl_abapgit_html_form IMPLEMENTATION. METHOD checkbox. DATA ls_field LIKE LINE OF mt_fields. ls_field-type = c_field_type-checkbox. ls_field-name = iv_name. ls_field-label = iv_label. ls_field-hint = iv_hint. APPEND ls_field TO mt_fields. ro_self = me. ENDMETHOD. METHOD column. FIELD-SYMBOLS LIKE LINE OF mt_fields. DATA ls_column LIKE LINE OF -subitems. DATA lv_size TYPE i. lv_size = lines( mt_fields ). ASSERT lv_size > 0. "" Exception ? Maybe add zcx_no_check ? READ TABLE mt_fields INDEX lv_size ASSIGNING . ASSERT sy-subrc = 0. ASSERT -type = c_field_type-table. ls_column-label = iv_label. ls_column-value = iv_width. ls_column-readonly = iv_readonly. APPEND ls_column TO -subitems. ro_self = me. ENDMETHOD. METHOD command. DATA ls_cmd LIKE LINE OF mt_commands. ASSERT iv_cmd_type BETWEEN 1 AND 3. ls_cmd-label = iv_label. ls_cmd-action = iv_action. ls_cmd-is_main = iv_is_main. ls_cmd-cmd_type = iv_cmd_type. APPEND ls_cmd TO mt_commands. ro_self = me. ENDMETHOD. METHOD create. DATA lv_ts TYPE timestampl. CREATE OBJECT ro_form. ro_form->mv_form_id = iv_form_id. ro_form->mv_help_page = iv_help_page. IF ro_form->mv_form_id IS INITIAL. GET TIME STAMP FIELD lv_ts. ro_form->mv_form_id = |form_{ lv_ts }|. ENDIF. ENDMETHOD. METHOD hidden. DATA ls_field LIKE LINE OF mt_fields. ls_field-type = c_field_type-hidden. ls_field-name = iv_name. APPEND ls_field TO mt_fields. ENDMETHOD. METHOD is_empty. DATA: lv_value TYPE string, lv_rows TYPE i, lv_row TYPE i. FIELD-SYMBOLS LIKE LINE OF mt_fields. rv_empty = abap_true. LOOP AT mt_fields ASSIGNING WHERE type <> c_field_type-field_group. lv_value = condense( val = io_form_data->get( -name ) del = ` ` ). IF -type = c_field_type-number. rv_empty = boolc( lv_value IS INITIAL OR lv_value = '0' ). ELSEIF -type = c_field_type-table. lv_rows = io_form_data->get( |{ -name }-{ c_rows }| ). DO lv_rows TIMES. lv_row = sy-index. DO lines( -subitems ) TIMES. lv_value = io_form_data->get( |{ -name }-{ lv_row }-{ sy-index }| ). rv_empty = boolc( lv_value IS INITIAL ). IF rv_empty <> abap_true. RETURN. ENDIF. ENDDO. ENDDO. ELSEIF -type = c_field_type-textarea. REPLACE ALL OCCURRENCES OF zif_abapgit_definitions=>c_crlf IN lv_value WITH ''. REPLACE ALL OCCURRENCES OF zif_abapgit_definitions=>c_newline IN lv_value WITH ''. rv_empty = boolc( lv_value IS INITIAL ). ELSE. rv_empty = boolc( lv_value IS INITIAL ). ENDIF. IF rv_empty <> abap_true. RETURN. ENDIF. ENDLOOP. ENDMETHOD. METHOD normalize_form_data. DATA: lv_value TYPE string, lv_rows TYPE i, lv_row TYPE i, lv_len TYPE i. FIELD-SYMBOLS LIKE LINE OF mt_fields. CREATE OBJECT ro_form_data. LOOP AT mt_fields ASSIGNING WHERE type <> c_field_type-field_group. CLEAR lv_value. lv_value = io_form_data->get( -name ). IF -type = c_field_type-checkbox. ro_form_data->set( iv_key = -name iv_val = boolc( lv_value = 'on' ) ). ELSEIF -type = c_field_type-text AND -upper_case = abap_true. ro_form_data->set( iv_key = -name iv_val = to_upper( lv_value ) ). ELSEIF -type = c_field_type-number. "" Numeric value is checked in validation ro_form_data->set( iv_key = -name iv_val = condense( val = lv_value del = ` ` ) ). ELSEIF -type = c_field_type-table. lv_rows = io_form_data->get( |{ -name }-{ c_rows }| ). DO lv_rows TIMES. lv_row = sy-index. DO lines( -subitems ) TIMES. lv_value = io_form_data->get( |{ -name }-{ lv_row }-{ sy-index }| ). ro_form_data->set( iv_key = |{ -name }-{ lv_row }-{ sy-index }| iv_val = lv_value ). ENDDO. ENDDO. ro_form_data->set( iv_key = |{ -name }-{ c_rows }| iv_val = |{ lv_rows }| ). ELSEIF -type = c_field_type-textarea. REPLACE ALL OCCURRENCES OF zif_abapgit_definitions=>c_crlf IN lv_value WITH zif_abapgit_definitions=>c_newline. "" Remove last line if empty (ie 2x newline) lv_len = strlen( lv_value ) - 2. IF lv_len >= 0 AND lv_value+lv_len(1) = zif_abapgit_definitions=>c_newline. lv_len = lv_len + 1. lv_value = lv_value(lv_len). ENDIF. ro_form_data->set( iv_key = -name iv_val = lv_value ). ELSE. ro_form_data->set( iv_key = -name iv_val = lv_value ). ENDIF. ENDLOOP. ENDMETHOD. METHOD number. DATA ls_field LIKE LINE OF mt_fields. ls_field-type = c_field_type-number. ls_field-name = iv_name. ls_field-label = iv_label. ls_field-readonly = iv_readonly. ls_field-min = iv_min. ls_field-max = iv_max. ls_field-hint = iv_hint. ls_field-required = iv_required. APPEND ls_field TO mt_fields. ro_self = me. ENDMETHOD. METHOD option. FIELD-SYMBOLS LIKE LINE OF mt_fields. DATA ls_option LIKE LINE OF -subitems. DATA lv_size TYPE i. lv_size = lines( mt_fields ). ASSERT lv_size > 0. "" Exception ? Maybe add zcx_no_check ? READ TABLE mt_fields INDEX lv_size ASSIGNING . ASSERT sy-subrc = 0. ASSERT -type = c_field_type-radio. "" Or dropdown - TODO in future ls_option-label = iv_label. ls_option-value = iv_value. APPEND ls_option TO -subitems. ro_self = me. ENDMETHOD. METHOD radio. DATA ls_field LIKE LINE OF mt_fields. ls_field-type = c_field_type-radio. ls_field-name = iv_name. ls_field-label = iv_label. ls_field-default_value = iv_default_value. ls_field-hint = iv_hint. APPEND ls_field TO mt_fields. ro_self = me. ENDMETHOD. METHOD render. FIELD-SYMBOLS LIKE LINE OF mt_fields. FIELD-SYMBOLS LIKE LINE OF mt_commands. DATA lv_hint TYPE string. DATA ls_form_id TYPE string. DATA lv_cur_group TYPE string. DATA lv_url TYPE string. IF mv_form_id IS NOT INITIAL. ls_form_id = | id=""{ mv_form_id }""|. ENDIF. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( |
| ). ri_html->add( |
| ). "" Add hidden button that triggers main command when pressing enter LOOP AT mt_commands ASSIGNING WHERE is_main = abap_true. ri_html->add( || ). EXIT. ENDLOOP. LOOP AT mt_fields ASSIGNING . AT FIRST. IF -type <> c_field_type-field_group. ri_html->add( |
    | ). ENDIF. ENDAT. IF -type = c_field_type-field_group. IF lv_cur_group IS NOT INITIAL AND lv_cur_group <> -name. ri_html->add( |
| ). ri_html->add( || ). ENDIF. IF -hint IS NOT INITIAL. lv_hint = | title=""{ -hint }""|. ELSE. lv_hint = ''. ENDIF. lv_cur_group = -name. ri_html->add( |
-name }"">| ). ri_html->add( |{ -label }| ). ri_html->add( |
    | ). CONTINUE. ENDIF. render_field( ii_html = ri_html io_values = io_values io_validation_log = io_validation_log is_field = ). AT LAST. ri_html->add( |
| ). IF lv_cur_group IS NOT INITIAL. ri_html->add( |
| ). ENDIF. ENDAT. ENDLOOP. ri_html->add( |
    | ). ri_html->add( |
  • | ). IF mv_help_page IS NOT INITIAL. lv_url = escape( val = mv_help_page format = cl_abap_format=>e_url ). ri_html->add_a( iv_txt = zcl_abapgit_gui_buttons=>help( ) iv_act = |{ zif_abapgit_definitions=>c_action-url }?url={ lv_url }| iv_class = 'dialog-help' iv_title = 'Help' ). ENDIF. LOOP AT mt_commands ASSIGNING . render_command( ii_html = ri_html is_cmd = ). ENDLOOP. ri_html->add( |
  • | ). ri_html->add( |
| ). ri_html->add( || ). ri_html->add( |
| ). ENDMETHOD. METHOD render_command. DATA lv_main_submit TYPE string. CASE is_cmd-cmd_type. WHEN c_cmd_type-link. ii_html->add_a( iv_txt = is_cmd-label iv_act = is_cmd-action iv_class = 'dialog-commands' ). WHEN c_cmd_type-button. ii_html->add( || ). WHEN c_cmd_type-input. IF is_cmd-is_main = abap_true. lv_main_submit = ' class=""main""'. ELSE. CLEAR lv_main_submit. ENDIF. ii_html->add( || ). WHEN OTHERS. ASSERT 0 = 1. ENDCASE. ENDMETHOD. METHOD render_field. DATA: ls_attr TYPE ty_attr, lv_item_class TYPE string. "" Get value and validation error ls_attr-value = escape( val = io_values->get( is_field-name ) format = cl_abap_format=>e_html_attr ). IF io_validation_log IS BOUND. ls_attr-error = io_validation_log->get( is_field-name ). IF ls_attr-error IS NOT INITIAL. ls_attr-error = escape( val = ls_attr-error format = cl_abap_format=>e_html_text ). ls_attr-error = |{ ls_attr-error }|. ENDIF. ENDIF. "" Prepare field attributes IF is_field-required = abap_true. ls_attr-required = ' *'. ENDIF. IF is_field-hint IS NOT INITIAL. ls_attr-hint = escape( val = is_field-hint format = cl_abap_format=>e_html_attr ). ls_attr-hint = | title=""{ ls_attr-hint }""|. ENDIF. IF is_field-placeholder IS NOT INITIAL. ls_attr-placeholder = escape( val = is_field-placeholder format = cl_abap_format=>e_html_attr ). ls_attr-placeholder = | placeholder=""{ ls_attr-placeholder }""|. ENDIF. IF is_field-readonly = abap_true. ls_attr-readonly = ' readonly'. ENDIF. "" Prepare item class lv_item_class = is_field-item_class. IF ls_attr-error IS NOT INITIAL. lv_item_class = condense( lv_item_class && ' error' ). ENDIF. IF is_field-type = c_field_type-text AND is_field-max BETWEEN 1 AND 20. "" Reduced width for short fields lv_item_class = lv_item_class && ' w40'. ENDIF. IF lv_item_class IS NOT INITIAL. lv_item_class = | class=""{ lv_item_class }""|. ENDIF. "" Render field ii_html->add( || ). CASE is_field-type. WHEN c_field_type-text OR c_field_type-number. render_field_text( ii_html = ii_html is_field = is_field is_attr = ls_attr ). WHEN c_field_type-textarea. render_field_textarea( ii_html = ii_html is_field = is_field is_attr = ls_attr ). WHEN c_field_type-checkbox. render_field_checkbox( ii_html = ii_html is_field = is_field is_attr = ls_attr ). WHEN c_field_type-radio. render_field_radio( ii_html = ii_html is_field = is_field is_attr = ls_attr ). WHEN c_field_type-table. render_field_table( ii_html = ii_html is_field = is_field is_attr = ls_attr io_values = io_values ). WHEN c_field_type-hidden. render_field_hidden( ii_html = ii_html is_field = is_field is_attr = ls_attr ). WHEN OTHERS. ASSERT 1 = 0. ENDCASE. ii_html->add( '' ). ENDMETHOD. METHOD render_field_checkbox. DATA lv_checked TYPE string. IF is_attr-error IS NOT INITIAL. ii_html->add( is_attr-error ). ENDIF. IF is_attr-value = abap_true OR is_attr-value = 'on'. "" boolc return ` ` which is not initial -> bug after 1st validation lv_checked = ' checked'. ENDIF. ii_html->add( || ). ii_html->add( || ). ENDMETHOD. METHOD render_field_hidden. ii_html->add( || ). ENDMETHOD. METHOD render_field_radio. DATA: lv_value TYPE string, lv_checked TYPE string, lv_opt_id TYPE string, lv_opt_value TYPE string. FIELD-SYMBOLS LIKE LINE OF is_field-subitems. ii_html->add( |{ is_field-label }| ). IF is_attr-error IS NOT INITIAL. ii_html->add( is_attr-error ). ENDIF. ii_html->add( |
| ). LOOP AT is_field-subitems ASSIGNING . lv_opt_value = escape( val = -value format = cl_abap_format=>e_html_attr ). CLEAR lv_checked. IF is_attr-value = lv_opt_value OR ( is_attr-value IS INITIAL AND lv_opt_value = is_field-default_value ). lv_checked = ' checked'. ENDIF. lv_opt_id = |{ is_field-name }{ sy-tabix }|. ii_html->add( || ). ii_html->add( || ). ENDLOOP. ii_html->add( '
' ). ENDMETHOD. METHOD render_field_table. DATA: lv_value TYPE string, lv_readonly TYPE string, lv_rows TYPE i, lv_cell_id TYPE string, lv_opt_value TYPE string. FIELD-SYMBOLS LIKE LINE OF is_field-subitems. ii_html->add( || ). IF is_attr-error IS NOT INITIAL. ii_html->add( is_attr-error ). ENDIF. ii_html->add( || ). ii_html->add( || ). ii_html->add( || ). LOOP AT is_field-subitems ASSIGNING . CLEAR lv_value. IF -value IS NOT INITIAL. lv_value = escape( val = -value format = cl_abap_format=>e_html_attr ). lv_value = | width=""{ lv_value }""|. ENDIF. ii_html->add( |{ -label }| ). ENDLOOP. ii_html->add( || ). ii_html->add( || ). lv_rows = io_values->get( |{ is_field-name }-{ c_rows }| ). ii_html->add( || ). DO lv_rows TIMES. lv_rows = sy-index. ii_html->add( || ). LOOP AT is_field-subitems ASSIGNING . lv_cell_id = |{ is_field-name }-{ lv_rows }-{ sy-tabix }|. lv_value = escape( val = io_values->get( lv_cell_id ) format = cl_abap_format=>e_html_attr ). CLEAR lv_readonly. IF -readonly = abap_true. lv_readonly = | readonly|. ENDIF. ii_html->add( || ). ENDLOOP. ii_html->add( || ). ENDDO. ii_html->add( || ). ii_html->add( |
| ). "" Hidden field with number of rows to simplify getting values from form lv_value = |{ is_field-name }-{ c_rows }|. ii_html->add( || ). ENDMETHOD. METHOD render_field_text. DATA lv_type TYPE string. ii_html->add( || ). IF is_attr-error IS NOT INITIAL. ii_html->add( is_attr-error ). ENDIF. IF is_field-side_action IS NOT INITIAL. ii_html->add( '
' ). "" Ugly :( ENDIF. IF is_field-type = c_field_type-number. lv_type = 'number'. ELSEIF is_field-password = abap_true. lv_type = 'password'. ELSE. lv_type = 'text'. ENDIF. ii_html->add( || ). IF is_field-side_action IS NOT INITIAL. ii_html->add( '
' ). ii_html->add( '
' ). ii_html->add( || ). ii_html->add( '
' ). ENDIF. ENDMETHOD. METHOD render_field_textarea. DATA lv_rows TYPE i. ii_html->add( || ). IF is_attr-error IS NOT INITIAL. ii_html->add( is_attr-error ). ENDIF. lv_rows = lines( zcl_abapgit_convert=>split_string( is_attr-value ) ). ii_html->add( || ). ENDMETHOD. METHOD start_group. DATA ls_field LIKE LINE OF mt_fields. ls_field-type = c_field_type-field_group. ls_field-label = iv_label. ls_field-name = iv_name. ls_field-hint = iv_hint. APPEND ls_field TO mt_fields. ro_self = me. ENDMETHOD. METHOD table. DATA ls_field LIKE LINE OF mt_fields. ls_field-type = c_field_type-table. ls_field-name = iv_name. ls_field-label = iv_label. ls_field-hint = iv_hint. APPEND ls_field TO mt_fields. ro_self = me. ENDMETHOD. METHOD text. DATA ls_field LIKE LINE OF mt_fields. ls_field-type = c_field_type-text. ls_field-name = iv_name. ls_field-label = iv_label. ls_field-upper_case = iv_upper_case. ls_field-readonly = iv_readonly. ls_field-min = iv_min. ls_field-max = iv_max. ls_field-password = iv_password. ls_field-hint = iv_hint. ls_field-required = iv_required. ls_field-placeholder = iv_placeholder. IF iv_side_action IS NOT INITIAL AND mv_form_id IS NOT INITIAL. ls_field-item_class = 'with-command'. ls_field-side_action = iv_side_action. ls_field-dblclick = | ondblclick=""document.getElementById('{ mv_form_id }').action = 'sapevent:{ iv_side_action }'; document.getElementById('{ mv_form_id }').submit()""|. ENDIF. APPEND ls_field TO mt_fields. ro_self = me. ENDMETHOD. METHOD textarea. DATA ls_field LIKE LINE OF mt_fields. ls_field-type = c_field_type-textarea. ls_field-name = iv_name. ls_field-label = iv_label. ls_field-readonly = iv_readonly. ls_field-hint = iv_hint. ls_field-required = iv_required. ls_field-placeholder = iv_placeholder. APPEND ls_field TO mt_fields. ro_self = me. ENDMETHOD. METHOD validate_required_fields. DATA lv_value TYPE string. DATA lv_number TYPE i. FIELD-SYMBOLS LIKE LINE OF mt_fields. CREATE OBJECT ro_validation_log. LOOP AT mt_fields ASSIGNING . lv_value = io_form_data->get( -name ). IF -required IS NOT INITIAL AND lv_value IS INITIAL. ro_validation_log->set( iv_key = -name iv_val = |{ -label } cannot be empty| ). ENDIF. CASE -type. WHEN c_field_type-text. IF -min <> cl_abap_math=>min_int4 AND strlen( lv_value ) < -min. ro_validation_log->set( iv_key = -name iv_val = |{ -label } must not be shorter than { -min } characters| ). ENDIF. IF -max <> cl_abap_math=>max_int4 AND strlen( lv_value ) > -max. ro_validation_log->set( iv_key = -name iv_val = |{ -label } must not be longer than { -max } characters| ). ENDIF. WHEN c_field_type-number. TRY. lv_number = lv_value. CATCH cx_root. ro_validation_log->set( iv_key = -name iv_val = |{ -label } is not numeric| ). CONTINUE. ENDTRY. IF -min <> cl_abap_math=>min_int4 AND lv_number < -min. ro_validation_log->set( iv_key = -name iv_val = |{ -label } must not be lower than { -min }| ). ENDIF. IF -max <> cl_abap_math=>max_int4 AND lv_number > -max. ro_validation_log->set( iv_key = -name iv_val = |{ -label } must not be higher than { -max }| ). ENDIF. ENDCASE. ENDLOOP. ENDMETHOD. ENDCLASS. ",8061,False,1572.4695990829578,median "class ZCL_GUIDRASIL_BUILDER definition public final create public . *""* public components of class ZCL_GUIDRASIL_BUILDER *""* do not include other source files here!!! public section. type-pools ABAP . type-pools CNTB . type-pools ICON . interfaces ZIF_GUIDRASIL_FUNC_RECEIVER . constants ICON_CONTAINER type ZGUIDRASIL_ICON_NAME value ICON_WD_VIEW_CONTAINER ##NO_TEXT. constants K_MODE_DESIGN type CHAR01 value 'D' ##NO_TEXT. constants K_MODE_PATTERN type CHAR01 value 'P' ##NO_TEXT. class-methods CLASS_CONSTRUCTOR . class-methods INIT_CONTROL_NAME importing !IV_TEXT type C returning value(EV_NAME) type TEXT30 . methods ADD_CONTAINER importing !IV_SIDE type I !IV_CONTROL_ID type I optional . methods ADD_CONTAINER_BOX . methods ADD_CONTAINER_CC importing !CC_NAME type CLIKE optional . methods BUILD . methods CONSTRUCTOR importing !IV_PNAME type ZGUIDRASIL_PROJECT !IV_MODE type CHAR01 default SPACE . methods GET_CREATION_CODE returning value(CODE) type STRING_TABLE . methods GET_EVENT_PATTERN returning value(PATTERN) type STRING_TABLE . methods GET_EVENT_PATTERN_PLUS returning value(PATTERN) type STRING_TABLE . methods GET_OBJECT_BY_NAME importing !NAME type CLIKE returning value(OBJECT) type ref to CL_GUI_OBJECT . methods SAVE . PROTECTED SECTION. *""* protected components of class ZCL_GUIDRASIL_CONTROL_BUILDER *""* do not include other source files here!!! METHODS add_control_object IMPORTING VALUE(fcode) TYPE ui_func VALUE(r_sender) TYPE REF TO object VALUE(r_receiver) TYPE REF TO object VALUE(r_toolbar) TYPE REF TO cl_gui_toolbar . METHODS get_menu_functions IMPORTING !fcode TYPE clike RETURNING VALUE(it_functions) TYPE ttb_button . private section. types: *""* private components of class ZCL_GUIDRASIL_BUILDER *""* do not include other source files here!!! BEGIN OF gys_control_classes, id TYPE i, ""numc5, classname TYPE seoclsname, END OF gys_control_classes . types: gyt_control_classes TYPE SORTED TABLE OF gys_control_classes WITH UNIQUE KEY id . types: BEGIN OF gys_control_admin, id TYPE i, name TYPE string, parent TYPE REF TO zcl_guidrasil_control_base, parent_name TYPE zguidrasil_container_name, control TYPE REF TO zcl_guidrasil_control_base, END OF gys_control_admin . types: gyt_control_admin TYPE TABLE OF gys_control_admin . class-data MT_IDX type TY_IDX_T . class-data MT_CTLS type ZGUIDRASIL_CTLS_T . class-data GV_CONTROL_ID type NUMC3 . data CURRENT_CONTROL_ID type I . data R_TOOLBAR type ref to CL_GUI_TOOLBAR . data MT_CONTROLS type ZGUIDRASIL_OBJ_T . data MODE type CHAR01 . data PNAME type CHAR40 . data R_DOCKING type ref to CL_GUI_DOCKING_CONTAINER . data R_TOOLBAR_CONTAINER type ref to CL_GUI_DIALOGBOX_CONTAINER . class-data GT_CONTROL_CLASSES type GYT_CONTROL_CLASSES . data T_CONTROL_ADMIN type GYT_CONTROL_ADMIN . class-data GT_DELETE_FUNCTION type TTB_BUTTON . class-data GT_CLOSE_FUNCTION type TTB_BUTTON . class-data GT_INSERT_FUNCTION type TTB_BUTTON . class-data GT_PATTERN_FUNCTION type TTB_BUTTON . data GT_CONTROL_LIST type ZGUIDRASIL_CONTROL_LIST_T . class-methods GET_NAME_BUTTON importing !IR_CONTROL type ref to ZCL_GUIDRASIL_CONTROL_BASE changing !CT_FUNCTIONS type TTB_BUTTON . methods ADD_CONTROL importing !IR_CONTROL type ref to ZCL_GUIDRASIL_CONTROL_BASE !IR_PARENT type ref to ZCL_GUIDRASIL_CONTROL_BASE optional !IV_PARENT_NAME type CLIKE optional . methods BUILD_CONTROL_TOOLBAR importing !IR_WRAPPER type ref to ZCL_GUIDRASIL_DESIGN_CONTAINER . methods BUILD_DESIGN_TOOLBAR . methods BUILD_EDIT_TOOLBAR importing !IR_WRAPPER type ref to ZCL_GUIDRASIL_DESIGN_CONTAINER !IR_CONTROL_BUILDER type ref to ZCL_GUIDRASIL_CONTROL_BASE . methods BUILD_PATTERN_TOOLBAR importing !IR_WRAPPER type ref to ZCL_GUIDRASIL_DESIGN_CONTAINER !IR_CONTROL_BUILDER type ref to ZCL_GUIDRASIL_CONTROL_BASE . methods CODE_REPLACE importing !SEARCH type CLIKE !REPLACE type CLIKE !PREFIX type CLIKE changing !CODE type STRING_TABLE . methods CREATE_WRAPPER importing !IV_CONTROL_TOOLBAR type XFELD optional !IV_EDIT_TOOLBAR type XFELD optional !IR_CONTAINER type ref to CL_GUI_CONTAINER optional !IR_PARENT_BUILDER type ref to ZCL_GUIDRASIL_CONTROL_BASE exporting !ER_WRAPPER type ref to ZCL_GUIDRASIL_DESIGN_CONTAINER . methods IS_CLOSE_FUNCTION_ENABLED importing !IR_WRAPPER type ref to ZCL_GUIDRASIL_DESIGN_CONTAINER returning value(RV_ENABLED) type XFELD . methods ON_DESIGN_FUNCTION_SELECTED for event FUNCTION_SELECTED of CL_GUI_TOOLBAR importing !FCODE . methods SET_CURRENT_CONTROL_ID returning value(CONTROL_ID) type I . methods UPDATE_CONTROLS . ENDCLASS. CLASS ZCL_GUIDRASIL_BUILDER IMPLEMENTATION. METHOD add_container. DATA lv_extension TYPE i. DATA lv_control_id TYPE i. DATA lr_control_builder TYPE REF TO zcl_guidrasil_control_base. DATA lr_wrapper TYPE REF TO zcl_guidrasil_design_container. DATA lr_docking_container TYPE REF TO cl_gui_docking_container. IF iv_control_id IS INITIAL. lv_control_id = set_current_control_id( ). ELSE. lv_control_id = iv_control_id. ENDIF. CASE iv_side. WHEN cl_gui_docking_container=>dock_at_bottom OR cl_gui_docking_container=>dock_at_top. lv_extension = 160. WHEN cl_gui_docking_container=>dock_at_left OR cl_gui_docking_container=>dock_at_right. lv_extension = 400. ENDCASE. * entsprechenden Control-Builder anlegen CALL METHOD zcl_guidrasil_control_base=>get_instance EXPORTING iv_classname = 'ZCL_GUIDRASIL_CONTROL_DOCKING' iv_control_id = lv_control_id IMPORTING er_control = lr_control_builder EXCEPTIONS OTHERS = 1. zcl_guidrasil_tools=>todo( 'Setzen Daten innerhalb drasil-Control' ). lr_control_builder->apply_settings( ). * Seite und Größe festlegen lr_docking_container ?= lr_control_builder->gr_control. lr_docking_container->dock_at( side = iv_side ). lr_docking_container->set_extension( extension = lv_extension ). * Control zur Verwaltungstabelle hinzufügen add_control( ir_control = lr_control_builder ). * im Designmode Wrapper hinzufügen create_wrapper( iv_control_toolbar = abap_true ir_parent_builder = lr_control_builder ). ENDMETHOD. METHOD add_container_box. DATA lv_extension TYPE i. DATA lr_control_builder TYPE REF TO zcl_guidrasil_control_base. DATA lr_wrapper TYPE REF TO zcl_guidrasil_design_container. DATA lv_control_id TYPE i. lv_control_id = set_current_control_id( ). * entsprechenden Control-Builder anlegen CALL METHOD zcl_guidrasil_control_base=>get_instance EXPORTING iv_classname = 'ZCL_GUIDRASIL_CONTROL_DIABOX' ir_parent_container = cl_gui_container=>screen0 iv_control_id = 0 IMPORTING er_control = lr_control_builder EXCEPTIONS OTHERS = 1. * Control zur Verwaltungstabelle hinzufügen add_control( lr_control_builder ). * im Designmode Wrapper hinzufügen CALL METHOD create_wrapper EXPORTING iv_control_toolbar = abap_true ir_parent_builder = lr_control_builder. ENDMETHOD. METHOD add_container_cc. DATA lv_extension TYPE i. DATA lr_control_builder TYPE REF TO zcl_guidrasil_control_base. DATA lr_wrapper TYPE REF TO zcl_guidrasil_design_container. DATA lr_cc_container TYPE REF TO cl_gui_custom_container. DATA lv_control_id TYPE i. lv_control_id = set_current_control_id( ). * entsprechenden Control-Builder anlegen CALL METHOD zcl_guidrasil_control_base=>get_instance EXPORTING iv_classname = 'ZCL_GUIDRASIL_CONTROL_CUSTOM' iv_name = cc_name iv_control_id = 0 IMPORTING er_control = lr_control_builder EXCEPTIONS OTHERS = 1. * Seite und Größe festlegen lr_cc_container ?= lr_control_builder->gr_control. * Control zur Verwaltungstabelle hinzufügen add_control( lr_control_builder ). * im Designmode Wrapper hinzufügen CALL METHOD create_wrapper EXPORTING iv_control_toolbar = abap_true ir_parent_builder = lr_control_builder. ENDMETHOD. METHOD add_control. DATA ls_control_admin TYPE gys_control_admin. *== New Control ls_control_admin-id = current_control_id. ls_control_admin-name = ir_control->gv_control_name. ls_control_admin-control = ir_control. ls_control_admin-parent = ir_parent. ls_control_admin-parent_name = iv_parent_name. APPEND ls_control_admin TO t_control_admin. set_current_control_id( ). DATA ls_control_list TYPE zguidrasil_control_list. CLEAR ls_control_list. READ TABLE gt_control_list TRANSPORTING NO FIELDS WITH TABLE KEY guid = ir_control->gv_guid. IF sy-subrc > 0. ls_control_list-guid = ir_control->gv_guid. ls_control_list-r_control_builder = ir_control. ls_control_list-t_container = ir_control->get_container_list( ). INSERT ls_control_list INTO TABLE gt_control_list. ENDIF. ENDMETHOD. METHOD add_control_object. DATA lr_container TYPE REF TO cl_gui_container. DATA lr_wrapper TYPE REF TO zcl_guidrasil_design_container. DATA lr_control_builder TYPE REF TO zcl_guidrasil_control_base. DATA ls_control_list LIKE LINE OF gt_control_list. ""ew20160609 FIELD-SYMBOLS TYPE gys_control_classes. CHECK fcode(1) <> '$'. * Lesen, welches Control hinzugefügt werden soll READ TABLE gt_control_classes ASSIGNING WITH KEY id = fcode. * Hinzufüge-Funktion eines Controls? CHECK sy-subrc = 0. * Container vom Wrapper holen lr_wrapper ?= r_sender. lr_container = lr_wrapper->get_container_first( ). ls_control_list-parent_container = lr_wrapper->get_container_name( ). * entsprechenden Control-Builder anlegen zcl_guidrasil_control_base=>get_instance( EXPORTING iv_classname = -classname ir_parent_container = lr_container iv_parent_container = ls_control_list-parent_container iv_control_id = -id IMPORTING er_control = lr_control_builder EXCEPTIONS OTHERS = 1 ). CHECK sy-subrc = 0. READ TABLE gt_control_list TRANSPORTING NO FIELDS WITH KEY guid = lr_control_builder->gv_guid. IF sy-subrc > 0. ls_control_list-guid = lr_control_builder->gv_guid. ls_control_list-r_control_builder = lr_control_builder. INSERT ls_control_list INTO TABLE gt_control_list. ""ew20160609 ENDIF. * Untergeordnetes Control bekannt machen lr_wrapper->add_child( lr_control_builder ). add_control( ir_control = lr_control_builder ir_parent = lr_wrapper->get_parent( ) iv_parent_name = ls_control_list-parent_container ). * Einfüge-Toolbar in Editiertoolbar ändern build_edit_toolbar( ir_wrapper = lr_wrapper ir_control_builder = lr_control_builder ). * Wrapper aufbauen, falls Control weitere Kindcontainer hat create_wrapper( iv_control_toolbar = abap_true ir_parent_builder = lr_control_builder ). ENDMETHOD. METHOD build. DATA lv_classname TYPE seoclsname. DATA ls_control_list TYPE zguidrasil_control_list. DATA lr_control_builder TYPE REF TO zcl_guidrasil_control_base. DATA lr_container TYPE REF TO cl_gui_container. DATA lr_wrapper TYPE REF TO zcl_guidrasil_design_container. DATA lv_parent_container_found TYPE boolean. FIELD-SYMBOLS TYPE zguidrasil_obj. FIELD-SYMBOLS LIKE ls_control_list. *TODO: Prüfung Klassennamen CASE mode. WHEN k_mode_design. * CALL METHOD build_design_toolbar. ENDCASE. SORT mt_controls BY control_index. * Controls aufbauen LOOP AT mt_controls ASSIGNING . READ TABLE gt_control_list ASSIGNING WITH TABLE KEY guid = -parent_guid. * Root -> erzeugen IF sy-subrc <> 0. * derzeit nur Docking-Container/ Custom Control lv_classname = -parent. CALL METHOD zcl_guidrasil_control_base=>get_instance EXPORTING iv_classname = lv_classname iv_guid = -parent_guid iv_control_id = -control_index IMPORTING er_control = lr_control_builder EXCEPTIONS OTHERS = 1. CLEAR ls_control_list. ls_control_list-guid = lr_control_builder->gv_guid. ls_control_list-r_control_builder = lr_control_builder. lr_container ?= lr_control_builder->gr_control. APPEND lr_container TO ls_control_list-t_container. INSERT ls_control_list INTO TABLE gt_control_list ASSIGNING . * Control zur Verwaltungstabelle hinzufügen set_current_control_id( ). add_control( ir_control = lr_control_builder ). ENDIF. * 1. Container ermitteln LOOP AT -t_container INTO lr_container. IF lr_container->get_name( ) = -parent_container. lv_parent_container_found = abap_true. EXIT. ENDIF. ENDLOOP. IF lv_parent_container_found = abap_false. READ TABLE -t_container INTO lr_container INDEX 1. * nur freie Container behalten und aktuellen rausnehmen DELETE -t_container INDEX 1. ENDIF. * es gibt keine? CHECK sy-subrc = 0. * im Designmode Wrapper mit Toolbar hinzufügen CASE mode. WHEN k_mode_design OR k_mode_pattern. CALL METHOD create_wrapper EXPORTING ir_container = lr_container ir_parent_builder = -r_control_builder IMPORTING er_wrapper = lr_wrapper. lr_container = lr_wrapper->get_container_first( ). ENDCASE. * Kind erzeugen lv_classname = -object. CALL METHOD zcl_guidrasil_control_base=>get_instance EXPORTING iv_classname = lv_classname iv_guid = -object_guid ir_parent_container = lr_container iv_parent_container = -parent_container iv_name = -control_name iv_control_id = -control_index * iv_dont_create = lv_dont_create IMPORTING er_control = lr_control_builder EXCEPTIONS OTHERS = 1. CLEAR ls_control_list. ls_control_list-guid = lr_control_builder->gv_guid. ls_control_list-r_control_builder = lr_control_builder. ls_control_list-t_container = lr_control_builder->get_container_list( ). INSERT ls_control_list INTO TABLE gt_control_list. CASE mode. WHEN k_mode_design. lr_wrapper->add_child( lr_control_builder ). build_edit_toolbar( ir_wrapper = lr_wrapper ir_control_builder = lr_control_builder ). WHEN k_mode_pattern. lr_wrapper->add_child( lr_control_builder ). build_pattern_toolbar( ir_wrapper = lr_wrapper ir_control_builder = lr_control_builder ). ENDCASE. add_control( ir_control = lr_control_builder ir_parent = -r_control_builder ). ENDLOOP. * Falls noch Container übrig sind -> Wrapper mit Control-Hinzufügefunktionen IF mode = k_mode_design. LOOP AT gt_control_list ASSIGNING . LOOP AT -t_container INTO lr_container. create_wrapper( iv_control_toolbar = abap_true ir_container = lr_container ir_parent_builder = -r_control_builder ). ENDLOOP. ENDLOOP. ENDIF. ENDMETHOD. METHOD build_control_toolbar. DATA lt_funcmenus TYPE ttb_btnmnu. ""ew DATA lt_functions TYPE ttb_button. DATA ls_function TYPE stb_button. * Buttons löschen CALL METHOD ir_wrapper->clear_toolbar. * Schließen Funktion IF is_close_function_enabled( ir_wrapper ) = abap_true. APPEND LINES OF gt_close_function TO lt_functions. ENDIF. *== MENÜ Eintrag für Auswahl ""CONTAINER"" CLEAR ls_function. ls_function-function = '$CONTAINER'. ls_function-text = ''. ls_function-icon = zcl_guidrasil_constants=>icon_container. ""icon_wd_view_container. ls_function-butn_type = cntb_btype_dropdown. APPEND ls_function TO lt_functions. *== MENÜ Eintrag für Auswahl ""Control"" CLEAR ls_function. ls_function-function = '$CONTROLS'. ls_function-text = ''. ls_function-icon = icon_oo_object. ls_function-butn_type = zcl_guidrasil_constants=>icon_control. ""cntb_btype_dropdown. APPEND ls_function TO lt_functions. *== MENÜ Eintrag für Auswahl ""Control"" CLEAR ls_function. ls_function-function = '$CUSTOM'. ls_function-text = ''. ls_function-icon = icon_interface. ls_function-butn_type = zcl_guidrasil_constants=>icon_control. ""cntb_btype_dropdown. APPEND ls_function TO lt_functions. * Hinzufügbare Controls APPEND LINES OF gt_insert_function TO lt_functions. CALL METHOD ir_wrapper->add_functions EXPORTING it_function = lt_functions it_funcmenu = lt_funcmenus ir_sender = ir_wrapper ir_receiver = me. ENDMETHOD. METHOD build_design_toolbar. DATA lt_events TYPE cntl_simple_events. DATA ls_event TYPE cntl_simple_event. * Design-Toolbar einmalig aufbauen CHECK mode = k_mode_design. CHECK r_toolbar_container IS NOT BOUND. * Dialogbox-Container CREATE OBJECT r_toolbar_container EXPORTING width = 30 height = 30 top = 0 left = 0 caption = 'Design-Toolbar'. * Toolbar CREATE OBJECT r_toolbar EXPORTING parent = r_toolbar_container. * ls_event-eventid = cl_gui_toolbar=>m_id_dropdown_clicked. ""ew * APPEND ls_event TO lt_event. ls_event-eventid = cl_gui_toolbar=>m_id_function_selected. APPEND ls_event TO lt_events. r_toolbar->set_registered_events( events = lt_events ). SET HANDLER on_design_function_selected FOR r_toolbar. * Funktionen für neue Docking-Container CALL METHOD r_toolbar->add_button EXPORTING fcode = '$BOTTOM' icon = icon_previous_value butn_type = cntb_btype_button quickinfo = 'Dockingcontainer unten' EXCEPTIONS cntb_error_fcode = 1. CALL METHOD r_toolbar->add_button EXPORTING fcode = '$LEFT' icon = icon_column_left butn_type = cntb_btype_button quickinfo = 'Dockingcontainer links' EXCEPTIONS cntb_error_fcode = 1. CALL METHOD r_toolbar->add_button EXPORTING fcode = '$RIGHT' icon = icon_column_right butn_type = cntb_btype_button quickinfo = 'Dockingcontainer rechts' EXCEPTIONS cntb_error_fcode = 1. CALL METHOD r_toolbar->add_button EXPORTING fcode = '$TOP' icon = icon_next_value butn_type = cntb_btype_button quickinfo = 'Dockingcontainer oben' EXCEPTIONS cntb_error_fcode = 1. ENDMETHOD. METHOD build_edit_toolbar. DATA: lt_funcmenu TYPE ttb_btnmnu, ""ew lt_function TYPE ttb_button, lrt_container TYPE cwb_container. * Buttons löschen CALL METHOD ir_wrapper->clear_toolbar. * Funktionen zum Container/Control löschen IF is_close_function_enabled( ir_wrapper ) = abap_true. APPEND LINES OF gt_close_function TO lt_function. ENDIF. APPEND LINES OF gt_delete_function TO lt_function. *** add ""Name of Control"" Button CALL METHOD get_name_button EXPORTING ir_control = ir_control_builder CHANGING ct_functions = lt_function. CALL METHOD ir_wrapper->add_functions EXPORTING it_function = lt_function it_funcmenu = lt_funcmenu ""ew ir_sender = ir_wrapper ir_receiver = me. * Prüfen, ob das Control weitere Container bereitstellt lrt_container = ir_control_builder->get_container_list( ). CHECK lrt_container IS INITIAL. ir_control_builder->init( ). * wennn nicht, evtl. Einstellungsfunktionen hinzufügen ir_control_builder->get_design_functions( IMPORTING et_functions = lt_function et_funcmenus = lt_funcmenu ). ir_wrapper->add_functions( it_function = lt_function it_funcmenu = lt_funcmenu ir_sender = ir_wrapper ir_receiver = ir_control_builder ). ENDMETHOD. METHOD build_pattern_toolbar. DATA lt_funcmenu TYPE ttb_btnmnu. DATA lt_function TYPE ttb_button. DATA lrt_container TYPE cwb_container. * Buttons löschen ir_wrapper->clear_toolbar( ). IF ir_control_builder->has_pattern( ) > 0. APPEND LINES OF gt_pattern_function TO lt_function. ENDIF. *** add ""Name of Control"" Button get_name_button( EXPORTING ir_control = ir_control_builder CHANGING ct_functions = lt_function ). ir_wrapper->add_functions( it_function = lt_function it_funcmenu = lt_funcmenu ir_sender = ir_wrapper ir_receiver = me ). * Prüfen, ob das Control weitere Container bereitstellt lrt_container = ir_control_builder->get_container_list( ). CHECK lrt_container IS INITIAL. * wennn nicht, evtl. Einstellungsfunktionen hinzufügen * lt_function = ir_control_builder->get_design_functions( ). ir_wrapper->add_functions( it_function = lt_function it_funcmenu = lt_funcmenu ir_sender = ir_wrapper ir_receiver = ir_control_builder ). ENDMETHOD. METHOD class_constructor. DATA: ls_ctls TYPE zguidrasil_ctls, ls_control_classes TYPE gys_control_classes, ls_function TYPE stb_button. * Funktion zum Schließen von Containern CLEAR ls_function. ls_function-function = '$CLOSE'. ls_function-icon = icon_close. ls_function-butn_type = cntb_btype_button. ls_function-quickinfo = 'Destroy Container'. APPEND ls_function TO gt_close_function. CLEAR ls_function. ls_function-function = '$SEP0'. ls_function-butn_type = cntb_btype_sep. APPEND ls_function TO gt_close_function. * Funktion zum Entfernen von Controls CLEAR ls_function. ls_function-function = '$DELETE'. ls_function-icon = icon_delete. ls_function-butn_type = cntb_btype_button. ls_function-quickinfo = 'Delete Current Control'. APPEND ls_function TO gt_delete_function. CLEAR ls_function. ls_function-function = '$SEP1'. ls_function-butn_type = cntb_btype_sep. APPEND ls_function TO gt_delete_function. * Funktion für die Auswahl eines Controls für Pattern CLEAR ls_function. ls_function-function = '$SELECT'. ls_function-icon = icon_system_okay. ls_function-butn_type = cntb_btype_button. APPEND ls_function TO gt_pattern_function. CLEAR ls_function. SELECT * FROM zguidrasil_ctls INTO TABLE mt_ctls WHERE usable = abap_true. LOOP AT mt_ctls INTO ls_ctls. ls_control_classes-classname = ls_ctls-classname. * verwendbare Klassen merken ADD 1 TO ls_control_classes-id. INSERT ls_control_classes INTO TABLE gt_control_classes. * Funktionsliste aufbauen SELECT SINGLE id FROM icon INTO ls_function-icon WHERE name = ls_ctls-iconname. ls_function-function = ls_control_classes-id. SHIFT ls_function-function LEFT DELETING LEADING space. ls_function-quickinfo = ls_ctls-quickinfo. ls_function-butn_type = cntb_btype_menu. APPEND ls_function TO gt_insert_function. ENDLOOP. ENDMETHOD. METHOD code_replace. LOOP AT code ASSIGNING FIELD-SYMBOL(). REPLACE ALL OCCURRENCES OF search IN WITH |{ prefix }_{ replace }|. ENDLOOP. ENDMETHOD. METHOD constructor. mode = iv_mode. pname = iv_pname. * gespeicherten Zustand laden SELECT * FROM zguidrasil_obj INTO TABLE mt_controls WHERE report = iv_pname. DATA ls_control LIKE LINE OF mt_controls. FIELD-SYMBOLS LIKE LINE OF mt_idx. DATA ls_idx LIKE LINE OF mt_idx. DATA name TYPE zguidrasil_container_name. DATA id LIKE ls_idx-control_id. LOOP AT mt_controls INTO ls_control. SPLIT ls_control-control_name AT '_' INTO name id. READ TABLE mt_idx WITH TABLE KEY name = name ASSIGNING . IF sy-subrc = 0. IF id > -control_id. -control_id = id . ENDIF. ELSE. ls_idx-name = name. ls_idx-control_id = id. INSERT ls_idx INTO TABLE mt_idx. ENDIF. ENDLOOP. ENDMETHOD. METHOD create_wrapper. DATA lrt_container TYPE cwb_container. DATA lr_container TYPE REF TO cl_gui_container. CHECK mode = k_mode_design OR mode = k_mode_pattern. * wenn angegeben, nur den übergebenen Container verwenden IF ir_container IS BOUND. CLEAR lrt_container. APPEND ir_container TO lrt_container. ELSE. * Container ermitteln lrt_container = ir_parent_builder->get_container_list( ). ENDIF. * Wrapper für jeden Container hinzufügen LOOP AT lrt_container INTO lr_container. DATA(lv_container_name) = lr_container->get_name( ). lr_container->set_name( |{ lr_container->get_name( ) }| ). * Wrappercontrol aufbauen CREATE OBJECT er_wrapper EXPORTING ir_parent_container = lr_container ir_parent_control = ir_parent_builder. * Übergeordnetes Control und Wrapper verlinken CALL METHOD ir_parent_builder->add_child( er_wrapper ). * Toolbar mit hinzufügbaren Controls IF iv_control_toolbar = abap_true. CALL METHOD build_control_toolbar EXPORTING ir_wrapper = er_wrapper. * Toolbar mit Einstellungen zum Control ELSEIF iv_edit_toolbar = abap_true. CALL METHOD build_edit_toolbar EXPORTING ir_wrapper = er_wrapper ir_control_builder = ir_parent_builder. ENDIF. ENDLOOP. ENDMETHOD. METHOD get_creation_code. DATA lt_data TYPE string_table. DATA lt_code TYPE string_table. DATA xt_data TYPE string_table. DATA xt_code TYPE string_table. LOOP AT mt_controls ASSIGNING FIELD-SYMBOL(). READ TABLE gt_control_list INTO DATA(ls_object) WITH TABLE KEY guid = -object_guid. IF sy-subrc = 0. READ TABLE gt_control_list INTO DATA(ls_parent) WITH TABLE KEY guid = -parent_guid. IF sy-subrc > 0. CLEAR ls_parent. ENDIF. IF ls_object-r_control_builder->return_creation_code( IMPORTING data = lt_data code = lt_code ) = abap_false. code_replace( EXPORTING search = '$control' prefix = 'lr' replace = ls_object-r_control_builder->gv_control_name CHANGING code = lt_data ). code_replace( EXPORTING search = '$control' prefix = 'lr' replace = ls_object-r_control_builder->gv_control_name CHANGING code = lt_code ). IF ls_parent IS NOT INITIAL. code_replace( EXPORTING search = '$parent' prefix = 'lr' replace = ls_parent-r_control_builder->gv_control_name CHANGING code = lt_code ). ENDIF. APPEND LINES OF lt_data TO xt_data. APPEND LINES OF lt_code TO xt_code. ENDIF. ENDIF. ENDLOOP. APPEND LINES OF xt_data TO code. APPEND LINES OF xt_code TO code. ENDMETHOD. METHOD get_event_pattern. DATA ls_control LIKE LINE OF gt_control_list. DATA ls_object LIKE LINE OF mt_controls. DATA lr_object TYPE REF TO cl_gui_object. DATA line TYPE string. DATA event TYPE string. DATA lr_obj TYPE REF TO cl_abap_classdescr. DATA lv_name TYPE string. TYPES: BEGIN OF ty_event_ctrl, event TYPE string, control TYPE string, name TYPE string, END OF ty_event_ctrl, BEGIN OF ty_event, event TYPE string, control TYPE string, END OF ty_event. DATA lt_events TYPE STANDARD TABLE OF ty_event. DATA ls_event TYPE ty_event. DATA lt_events_c TYPE STANDARD TABLE OF ty_event_ctrl. DATA ls_event_c TYPE ty_event_ctrl. DATA ls_event2 TYPE ty_event. *clear t_controls. * update_controls( ). _code 'CLASS lcl_main DEFINITION.'. _code ' PUBLIC SECTION.'. _code ' DATA mr_guidrasil TYPE REF TO zcl_guidrasil_builder.'. LOOP AT mt_controls INTO ls_object. READ TABLE gt_control_list INTO ls_control WITH KEY guid = ls_object-object_guid. IF sy-subrc = 0 . *== DATA DEFINITION lr_object ?= ls_control-r_control_builder->get_control( ). IF lr_object IS BOUND. lr_obj ?= cl_abap_typedescr=>describe_by_object_ref( lr_object ). lv_name = lr_obj->get_relative_name( ). line = | DATA mr_{ ls_object-control_name } TYPE REF TO { lv_name }.|. ENDIF. APPEND line TO pattern. *== EVENT HANDLER IF ls_control-r_control_builder->gt_events IS NOT INITIAL. LOOP AT ls_control-r_control_builder->gt_events INTO ls_event-event. ls_event-control = lv_name. READ TABLE lt_events TRANSPORTING NO FIELDS WITH KEY event = ls_event-event control = ls_event-control. IF sy-subrc > 0. APPEND ls_event TO lt_events. ENDIF. ls_event_c-event = ls_event-event. ls_event_c-control = lv_name. ls_event_c-name = ls_object-control_name. APPEND ls_event_c TO lt_events_c. ENDLOOP. ENDIF. ENDIF. ENDLOOP. _code ' METHODS constructor.'. LOOP AT lt_events_c INTO ls_event_c. line = | METHODS h_{ ls_event_c-event } FOR EVENT { ls_event_c-event } OF { ls_event_c-control } IMPORTING sender.|. APPEND line TO pattern. ENDLOOP. _code 'ENDCLASS.'. _code 'CLASS lcl_main IMPLEMENTATION.'. _code ' METHOD constructor.'. _code ' CREATE OBJECT mr_guidrasil'. _code ' EXPORTING'. line = ` iv_pname = '$$PROJECT$$'.`. REPLACE '$$PROJECT$$' WITH pname INTO line. APPEND line TO pattern. _code ' mr_guidrasil->build( ).'. _code ' ENDMETHOD.'. LOOP AT lt_events INTO ls_event. line = | METHOD h_{ ls_event-event }.|. APPEND line TO pattern. _code ' CASE sender.'. LOOP AT lt_events_c INTO ls_event_c WHERE event = ls_event-event AND control = ls_event-control. line = | WHEN mr_{ ls_event_c-name }.|. APPEND line TO pattern. line = | MESSAGE i000(oo) WITH '{ ls_event_c-event }' '{ ls_event_c-name }'.|. APPEND line TO pattern. ENDLOOP. _code ' ENDCASE.'. _code ' ENDMETHOD.'. ENDLOOP. _code 'ENDCLASS.'. _code 'DATA gr_main TYPE REF TO lcl_main.'. *CLASS lcl_main DEFINITION. * PUBLIC SECTION. * DATA mr_guidrasil TYPE REF TO zcl_guidrasil_builder. * DATA mr_text1 TYPE REF TO cl_gui_textedit. * DATA mr_pic TYPE REF TO cl_gui_picture. * METHODS constructor. * METHODS handle_pic_click * FOR EVENT picture_click OF cl_gui_picture * IMPORTING sender. * *ENDCLASS. * *CLASS lcl_main IMPLEMENTATION. * METHOD constructor. * CREATE OBJECT mr_guidrasil * EXPORTING * iv_pname = 'GF' * EXCEPTIONS * OTHERS = 3. * IF sy-subrc = 0. * mr_guidrasil->build( ). * * mr_text1 ?= mr_guidrasil->get_object_by_name( 'INFOTEXT' ). * mr_pic ?= mr_guidrasil->get_object_by_name( 'MEINHAUS' ). * IF mr_pic IS BOUND. * SET HANDLER handle_pic_click FOR mr_pic. * ENDIF. * * ENDIF. * ENDMETHOD. * METHOD handle_pic_click. * MESSAGE i000(oo) WITH 'BildKlick!!'. * ENDMETHOD. * *ENDCLASS. * *DATA gr_guidrasil TYPE REF TO lcl_main. ENDMETHOD. METHOD get_event_pattern_plus. pattern = zcl_guidrasil_code_creation=>create_code_complete( it_controls = mt_controls it_control_list = gt_control_list ). ENDMETHOD. METHOD get_menu_functions. DATA ls_function TYPE stb_button. DATA ls_ctls TYPE zguidrasil_ctls. DATA ls_control_class LIKE LINE OF gt_control_classes. CASE fcode. WHEN '$CONTAINER'. LOOP AT mt_ctls INTO ls_ctls WHERE type = 'C'. * Funktionsliste aufbauen für CONTAINER aufbauen READ TABLE gt_control_classes INTO ls_control_class WITH KEY classname = ls_ctls-classname. IF sy-subrc = 0. ls_function-function = ls_control_class-id. ENDIF. ls_function-quickinfo = ls_ctls-quickinfo. APPEND ls_function TO it_functions. ENDLOOP. WHEN '$CONTROLS'. LOOP AT mt_ctls INTO ls_ctls WHERE type = 'O'. * Funktionsliste aufbauen für CONTROLS aufbauen READ TABLE gt_control_classes INTO ls_control_class WITH KEY classname = ls_ctls-classname. IF sy-subrc = 0. ls_function-function = ls_control_class-id. ENDIF. ls_function-quickinfo = ls_ctls-quickinfo. APPEND ls_function TO it_functions. ENDLOOP. WHEN '$CUSTOM'. LOOP AT mt_ctls INTO ls_ctls WHERE type = 'Q'. * Funktionsliste aufbauen für CONTROLS aufbauen READ TABLE gt_control_classes INTO ls_control_class WITH KEY classname = ls_ctls-classname. IF sy-subrc = 0. ls_function-function = ls_control_class-id. ENDIF. ls_function-quickinfo = ls_ctls-quickinfo. APPEND ls_function TO it_functions. ENDLOOP. ENDCASE. ENDMETHOD. METHOD get_name_button. DATA ls_function TYPE stb_button. CHECK ir_control IS BOUND. * Funktionen zur Controlsteuerung CLEAR ls_function. ls_function-function = '$NAME'. ls_function-icon = icon_interface. ls_function-butn_type = cntb_btype_button. ls_function-text = ir_control->gv_control_name. APPEND ls_function TO ct_functions. ""==> will now only use ""CTRLFUNC ** Funktion für die Änderung des Namens * CLEAR ls_function. * ls_function-function = '$ATTRIBUTES'. * ls_function-icon = icon_system_favorites. * ls_function-butn_type = cntb_btype_button. * ls_function-quickinfo = 'Change Control Attributes'. * APPEND ls_function TO ct_functions. * Funktion für die control eigenen Änderungen CLEAR ls_function. ls_function-function = '$CTRLFUNC'. ls_function-icon = icon_system_favorites. ls_function-butn_type = cntb_btype_dropdown. ls_function-quickinfo = 'Control attributes'(cta). APPEND ls_function TO ct_functions. zcl_guidrasil_tools=>todo( 'Wenn control keine Funktionen zur Verfügung stellt, darf der Knopf nicht angezeigt werden...' ). ENDMETHOD. METHOD get_object_by_name. DATA ls_control_list TYPE zguidrasil_control_list. READ TABLE mt_controls ASSIGNING FIELD-SYMBOL() WITH KEY control_name = name. IF sy-subrc = 0. READ TABLE gt_control_list INTO ls_control_list WITH KEY guid = -object_guid. IF sy-subrc = 0. TRY . object ?= ls_control_list-r_control_builder->get_control( ). CATCH cx_sy_move_cast_error. ENDTRY. ENDIF. ENDIF. ENDMETHOD. METHOD init_control_name. DATA lv_name TYPE zguidrasil_container_name. FIELD-SYMBOLS LIKE LINE OF mt_idx. DATA ls_idx LIKE LINE OF mt_idx. IF iv_text IS INITIAL. lv_name = 'CONTROL'. ELSE. lv_name = iv_text. ENDIF. READ TABLE mt_idx WITH TABLE KEY name = lv_name ASSIGNING . IF sy-subrc = 0. ADD 1 TO -control_id. CONCATENATE iv_text '_' -control_id INTO ev_name. ELSE. ls_idx-name = lv_name. ls_idx-control_id = 1. INSERT ls_idx INTO TABLE mt_idx. CONCATENATE iv_text '_' ls_idx-control_id INTO ev_name. ENDIF. ENDMETHOD. METHOD is_close_function_enabled. DATA lr_parent_builder TYPE REF TO zcl_guidrasil_control_base. DATA lrt_container TYPE cwb_container. rv_enabled = abap_true. * Vater fragen, ob er mehrere Container bereitstellt lr_parent_builder = ir_wrapper->get_parent( ). lrt_container = lr_parent_builder->get_container_list( ). * wenn ja, dann können diese nicht einzeln geschlossen werden IF lines( lrt_container ) > 1. rv_enabled = abap_false. ENDIF. ENDMETHOD. METHOD on_design_function_selected. CASE fcode. WHEN '$BOTTOM'. * add_container( cl_gui_docking_container=>dock_at_bottom ). WHEN '$LEFT'. * add_container( cl_gui_docking_container=>dock_at_left ). WHEN '$RIGHT'. * add_container( cl_gui_docking_container=>dock_at_right ). WHEN '$TOP'. * add_container( cl_gui_docking_container=>dock_at_top ). WHEN OTHERS. EXIT. ENDCASE. ENDMETHOD. METHOD save. DATA lv_id TYPE i. DATA lv_name TYPE string. DATA ls_object TYPE zguidrasil_obj. DATA lt_objects TYPE TABLE OF zguidrasil_obj. DATA ls_control_admin TYPE gys_control_admin. DATA ls_control_list TYPE zguidrasil_ctl_hierarchy_s. DATA lt_control_list TYPE zguidrasil_ctl_hierarchy_t. DATA lr_control_builder TYPE REF TO zcl_guidrasil_control_base. DATA lr_obj TYPE REF TO cl_abap_classdescr. DATA lr_docking TYPE REF TO cl_gui_docking_container. DATA lr_splitter TYPE REF TO cl_gui_easy_splitter_container. * anfangen bei den Basiscontrols LOOP AT t_control_admin INTO ls_control_admin. ls_control_list-control = ls_control_admin-control. APPEND ls_control_list TO lt_control_list. * Liste untergeordneter Controls ermitteln CALL METHOD ls_control_admin-control->get_control_list EXPORTING ir_parent_control = ls_control_list-control CHANGING ct_control_list = lt_control_list. * Einstellungen der Controls speichern CALL METHOD ls_control_admin-control->save_all. ENDLOOP. ls_object-report = pname. LOOP AT lt_control_list INTO ls_control_list. CHECK ls_control_list-parent IS BOUND. * Control IF ls_control_list-control IS BOUND. lr_obj ?= cl_abap_typedescr=>describe_by_object_ref( ls_control_list-control ). lv_name = lr_obj->get_relative_name( ). * alles außer Wrapper speichern IF lv_name <> 'ZCL_GUIDRASIL_DESIGN_CONTAINER'. ls_object-object = lv_name. ls_object-object_guid = ls_control_list-control->gv_guid. ls_object-control_name = ls_control_list-control->gv_control_name. ls_object-parent_container = ls_control_list-control->mv_parent_container_name. ENDIF. ENDIF. * ggf. Parent speichern IF ls_control_list-parent IS BOUND. lr_obj ?= cl_abap_typedescr=>describe_by_object_ref( ls_control_list-parent ). lv_name = lr_obj->get_relative_name( ). * alles außer Wrapper speichern IF lv_name <> 'ZCL_GUIDRASIL_DESIGN_CONTAINER'. ls_object-parent = lv_name. ls_object-parent_guid = ls_control_list-parent->gv_guid. ENDIF. ENDIF. * wenn sowohl Parent als auch Child gesetzt sind IF ls_object-parent IS NOT INITIAL AND ls_object-object IS NOT INITIAL. ADD 1 TO lv_id. ls_object-control_index = lv_id. APPEND ls_object TO lt_objects. CLEAR ls_object. ls_object-report = pname. ENDIF. ENDLOOP. ** update_controls( ). * ** anfangen bei den Basiscontrols * LOOP AT t_control_admin INTO ls_control_admin. ** Einstellungen der Controls speichern * CALL METHOD ls_control_admin-control->save_all. * ENDLOOP. * * * * bisheriges Projekt löschen DELETE FROM zguidrasil_obj WHERE report = pname. * und neuen Stand speichern IF lt_objects IS NOT INITIAL. INSERT zguidrasil_obj FROM TABLE lt_objects. ENDIF. COMMIT WORK. mt_controls = lt_objects. MESSAGE s001. ENDMETHOD. METHOD set_current_control_id. ADD 1 TO current_control_id. IF control_id IS REQUESTED. control_id = current_control_id. ENDIF. ENDMETHOD. METHOD update_controls. * DATA: * lv_id TYPE i, * lv_name TYPE string, * ls_guidrasil TYPE /inw/guidrasil, ** lt_guidrasil TYPE TABLE OF /INW/guidrasil, * ls_control_admin TYPE gys_control_admin, * ls_control_list TYPE /inw/guidrasil_ctl_hierarchy, * lt_control_list TYPE /inw/guidrasil_ctl_hierarchy_t, * lr_control_builder TYPE REF TO /inw/guidrasil_control_base, * lr_obj TYPE REF TO cl_abap_classdescr, * lr_docking TYPE REF TO cl_gui_docking_container, * lr_splitter TYPE REF TO cl_gui_easy_splitter_container. * **== Geht noch nicht, wenn neue Controls hinzukommen. **== es muss erst gespeichert werden... :/ * zcl_guidrasil_tools=>todo( ). * ** anfangen bei den Basiscontrols * LOOP AT t_control_admin INTO ls_control_admin. * * ls_control_list-control = ls_control_admin-control. * APPEND ls_control_list TO lt_control_list. * ** Liste untergeordneter Controls ermitteln * CALL METHOD ls_control_admin-control->get_control_list * EXPORTING * ir_parent_control = ls_control_list-control * CHANGING * ct_control_list = lt_control_list. * ** Einstellungen der Controls speichern ** CALL METHOD ls_control_admin-control->save_all. * * ENDLOOP. * ** CLEAR ls_control_list. ** ls_control_list-guid = ls_control-r_control_builder->gv_guid. ** ls_control_list-r_control_builder = lr_control_builder. ** lr_container ?= lr_control_builder->gr_control. ** APPEND lr_container TO ls_control_list-t_container. ** INSERT ls_control_list INTO TABLE gt_control_list ** ASSIGNING . * * ls_guidrasil-report = pname. * * LOOP AT lt_control_list INTO ls_control_list. * * * CHECK ls_control_list-parent IS BOUND. * ** Control * IF ls_control_list-control IS BOUND. * * lr_obj ?= cl_abap_typedescr=>describe_by_object_ref( ls_control_list-control ). * lv_name = lr_obj->get_relative_name( ). * ** alles außer Wrapper speichern * IF lv_name <> 'ZCL_GUIDRASIL_DESIGN_CONTAINER'. * ls_guidrasil-object = lv_name. * ls_guidrasil-object_guid = ls_control_list-control->gv_guid. * ls_guidrasil-control_name = ls_control_list-control->gv_control_name. * ENDIF. * * ENDIF. * * ** ggf. Parent speichern * IF ls_control_list-parent IS BOUND. * * lr_obj ?= cl_abap_typedescr=>describe_by_object_ref( ls_control_list-parent ). * lv_name = lr_obj->get_relative_name( ). * ** alles außer Wrapper speichern * IF lv_name <> 'ZCL_GUIDRASIL_DESIGN_CONTAINER'. * ls_guidrasil-parent = lv_name. * ls_guidrasil-parent_guid = ls_control_list-parent->gv_guid. * ENDIF. * * ENDIF. * * ** wenn sowohl Parent als auch Child gesetzt sind * IF ls_guidrasil-parent IS NOT INITIAL AND * ls_guidrasil-object IS NOT INITIAL. * * ADD 1 TO lv_id. * ls_guidrasil-control_index = lv_id. * APPEND ls_guidrasil TO t_controls. * * CLEAR ls_guidrasil. * ls_guidrasil-report = pname. * * ENDIF. * * ENDLOOP. ENDMETHOD. METHOD zif_guidrasil_func_receiver~on_dropdown_clicked. ""functions DATA lt_functions TYPE ttb_button. DATA ls_function TYPE stb_button. ""Menu DATA lr_text TYPE REF TO cl_gui_textedit. DATA lv_icon TYPE icon_d. DATA lv_disabled TYPE cua_active. DATA lv_checked TYPE cua_active. DATA lv_text TYPE gui_text. DATA lx_menu TYPE REF TO cl_ctmenu. DATA lx_menu_sub TYPE REF TO cl_ctmenu. DATA lv_flag TYPE i. lt_functions = get_menu_functions( fcode ). IF lt_functions IS NOT INITIAL. *== Create menu CREATE OBJECT lx_menu. *== Set functions for Container and Controls LOOP AT lt_functions INTO ls_function. lv_text = ls_function-quickinfo. SHIFT ls_function-function LEFT DELETING LEADING space. CALL METHOD lx_menu->add_function EXPORTING fcode = ls_function-function disabled = lv_disabled checked = lv_checked text = lv_text. ENDLOOP. * create object lx_menu_sub. * CALL METHOD lx_menu_sub->add_function * EXPORTING * fcode = 'SUB1' * text = 'Sub-Menu-Test 1'. * * CALL METHOD lx_menu_sub->add_function * EXPORTING * fcode = 'SUB2' * text = 'Sub-Menu-Test 2'. * * lx_menu->add_submenu( menu = lx_menu_sub * text = 'Sub1' ). *== set menu r_toolbar->track_context_menu( context_menu = lx_menu posx = posx posy = posy ). ENDIF. ENDMETHOD. METHOD zif_guidrasil_func_receiver~on_function_selected. DATA lr_container TYPE REF TO cl_gui_container. DATA lr_wrapper TYPE REF TO zcl_guidrasil_design_container. DATA lr_control_builder TYPE REF TO zcl_guidrasil_control_base. DATA lr_parent TYPE REF TO zcl_guidrasil_control_base. DATA lrt_container TYPE cwb_container. DATA ls_function TYPE stb_button. DATA lt_function TYPE ttb_button. DATA lt_controls TYPE zguidrasil_control_t. DATA ls_control_admin TYPE gys_control_admin. DATA lv_string TYPE string. DATA lt_pattern TYPE STANDARD TABLE OF string. DATA lt_child_controls TYPE zguidrasil_control_t. DATA lr_child_control TYPE REF TO zcl_guidrasil_control_base. DATA ls_control_list LIKE LINE OF gt_control_list. FIELD-SYMBOLS TYPE string. FIELD-SYMBOLS TYPE REF TO zcl_guidrasil_control_base. FIELD-SYMBOLS TYPE gys_control_classes. * bin ich gemeint oder ein anderes Objekt? CHECK r_receiver = me. CASE fcode. * Control wurde ausgewählt für Pattern WHEN '$SELECT'. lr_wrapper ?= r_sender. CALL METHOD lr_wrapper->get_children IMPORTING er_first_control = lr_control_builder. IF lr_control_builder IS BOUND. lt_pattern = lr_control_builder->get_pattern( ). IF lt_pattern IS NOT INITIAL. CLEAR lv_string. LOOP AT lt_pattern ASSIGNING . CONCATENATE lv_string cl_abap_char_utilities=>cr_lf INTO lv_string. ENDLOOP. CALL FUNCTION 'SRM_DISPLAY_TEXT' EXPORTING im_text = lv_string. ENDIF. ENDIF. * Control löschen WHEN '$DELETE'. lr_wrapper ?= r_sender. CALL METHOD lr_wrapper->get_children IMPORTING et_controls = lt_child_controls er_first_control = lr_control_builder. LOOP AT lt_child_controls INTO lr_child_control. DELETE t_control_admin WHERE parent = lr_child_control OR control = lr_child_control. ENDLOOP. IF lr_control_builder IS BOUND. lr_control_builder->destroy( ). lr_wrapper->remove_child( ). ENDIF. CALL METHOD build_control_toolbar EXPORTING ir_wrapper = lr_wrapper. * Basis-Container schließen WHEN '$CLOSE'. lr_wrapper ?= r_sender. lr_parent = lr_wrapper->get_parent( ). IF lr_parent IS BOUND. lr_parent->destroy( ). ENDIF. WHEN '$NAME'. DATA lv_answer TYPE c LENGTH 1. DATA lv_name TYPE char30. lr_wrapper ?= r_sender. CALL METHOD lr_wrapper->get_children IMPORTING er_first_control = lr_control_builder et_controls = lt_controls. READ TABLE lt_controls ASSIGNING INDEX 1. IF sy-subrc = 0. lv_name = ->gv_control_name. TRANSLATE lv_name TO UPPER CASE. CALL FUNCTION 'POPUP_TO_GET_VALUE' EXPORTING fieldname = 'CONTROL_NAME' tabname = 'ZGUIDRASIL_OBJ' titel = 'Name Of Control' valuein = lv_name IMPORTING answer = lv_answer valueout = lv_name EXCEPTIONS fieldname_not_found = 1 OTHERS = 2. IF sy-subrc = 0 AND lv_answer IS INITIAL. TRANSLATE lv_name TO UPPER CASE. ->gv_control_name = lv_name. ENDIF. * Container vom Wrapper holen lr_wrapper ?= r_sender. * Einfüge-Toolbar in Editiertoolbar ändern build_edit_toolbar( ir_wrapper = lr_wrapper ir_control_builder = ). ENDIF. * WHEN '$ATTRIBUTES' WHEN '$CTRLFUNC'. lr_wrapper ?= r_sender. CALL METHOD lr_wrapper->get_children IMPORTING er_first_control = lr_control_builder et_controls = lt_controls. READ TABLE lt_controls ASSIGNING INDEX 1. IF sy-subrc = 0. ->view_attributes( iv_edit = 'X' ). * Container vom Wrapper holen lr_wrapper ?= r_sender. * Einfüge-Toolbar in Editiertoolbar ändern build_edit_toolbar( ir_wrapper = lr_wrapper ir_control_builder = ). ENDIF. * Control hinzufügen WHEN OTHERS. CHECK fcode(1) <> '$'. add_control_object( fcode = fcode r_sender = r_sender r_receiver = r_receiver r_toolbar = r_toolbar ). ENDCASE. ENDMETHOD. ENDCLASS. ",12509,True,2566.2261594143533,median "********************************************************************** * UTILS ********************************************************************** CLASS lcl_utils DEFINITION FINAL. PUBLIC SECTION. CLASS-METHODS normalize_path IMPORTING iv_path TYPE string RETURNING VALUE(rv_path) TYPE string. CLASS-METHODS split_path IMPORTING iv_path TYPE string RETURNING VALUE(rv_path_name) TYPE zif_abapgit_ajson=>ty_path_name. CLASS-METHODS validate_array_index IMPORTING iv_path TYPE string iv_index TYPE string RETURNING VALUE(rv_index) TYPE i RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_utils IMPLEMENTATION. METHOD validate_array_index. IF NOT iv_index CO '0123456789'. zcx_abapgit_ajson_error=>raise( |Cannot add non-numeric key [{ iv_index }] to array [{ iv_path }]| ). ENDIF. rv_index = iv_index. IF rv_index = 0. zcx_abapgit_ajson_error=>raise( |Cannot add zero key to array [{ iv_path }]| ). ENDIF. ENDMETHOD. METHOD normalize_path. rv_path = iv_path. IF strlen( rv_path ) = 0. rv_path = '/'. ENDIF. IF rv_path+0(1) <> '/'. rv_path = '/' && rv_path. ENDIF. IF substring( val = rv_path off = strlen( rv_path ) - 1 ) <> '/'. rv_path = rv_path && '/'. ENDIF. ENDMETHOD. METHOD split_path. DATA lv_offs TYPE i. DATA lv_len TYPE i. DATA lv_trim_slash TYPE i. lv_len = strlen( iv_path ). IF lv_len = 0 OR iv_path = '/'. RETURN. "" empty path is the alias for root item = '' + '' ENDIF. IF substring( val = iv_path off = lv_len - 1 ) = '/'. lv_trim_slash = 1. "" ignore last '/' ENDIF. lv_offs = find( val = reverse( iv_path ) sub = '/' off = lv_trim_slash ). IF lv_offs = -1. lv_offs = lv_len. "" treat whole string as the 'name' part ENDIF. lv_offs = lv_len - lv_offs. rv_path_name-path = normalize_path( substring( val = iv_path len = lv_offs ) ). rv_path_name-name = substring( val = iv_path off = lv_offs len = lv_len - lv_offs - lv_trim_slash ). ENDMETHOD. ENDCLASS. ********************************************************************** * PARSER ********************************************************************** CLASS lcl_json_parser DEFINITION FINAL. PUBLIC SECTION. METHODS parse IMPORTING iv_json TYPE string RETURNING VALUE(rt_json_tree) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. PRIVATE SECTION. TYPES: ty_stack_tt TYPE STANDARD TABLE OF REF TO zif_abapgit_ajson=>ty_node. DATA mt_stack TYPE ty_stack_tt. CLASS-METHODS join_path IMPORTING it_stack TYPE ty_stack_tt RETURNING VALUE(rv_path) TYPE string. METHODS raise IMPORTING iv_error TYPE string RAISING zcx_abapgit_ajson_error. METHODS _parse IMPORTING iv_json TYPE string RETURNING VALUE(rt_json_tree) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error cx_sxml_error. METHODS _get_location IMPORTING iv_json TYPE string iv_offset TYPE i RETURNING VALUE(rv_location) TYPE string. ENDCLASS. CLASS lcl_json_parser IMPLEMENTATION. METHOD parse. DATA lx_sxml_parse TYPE REF TO cx_sxml_parse_error. DATA lx_sxml TYPE REF TO cx_sxml_error. DATA lv_location TYPE string. TRY. rt_json_tree = _parse( iv_json ). CATCH cx_sxml_parse_error INTO lx_sxml_parse. lv_location = _get_location( iv_json = iv_json iv_offset = lx_sxml_parse->xml_offset ). zcx_abapgit_ajson_error=>raise( iv_msg = |Json parsing error (SXML): { lx_sxml_parse->get_text( ) }| iv_location = lv_location ). CATCH cx_sxml_error INTO lx_sxml. zcx_abapgit_ajson_error=>raise( iv_msg = |Json parsing error (SXML): { lx_sxml->get_text( ) }| iv_location = '@PARSER' ). ENDTRY. ENDMETHOD. METHOD _get_location. DATA lv_json TYPE string. DATA lv_offset TYPE i. DATA lt_text TYPE TABLE OF string. DATA lv_text TYPE string. DATA lv_line TYPE i. DATA lv_pos TYPE i. lv_offset = iv_offset. IF lv_offset < 0. lv_offset = 0. ENDIF. IF lv_offset > strlen( iv_json ). lv_offset = strlen( iv_json ). ENDIF. lv_json = iv_json(lv_offset). REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>cr_lf IN lv_json WITH cl_abap_char_utilities=>newline. SPLIT lv_json AT cl_abap_char_utilities=>newline INTO TABLE lt_text. lv_line = lines( lt_text ). IF lv_line = 0. lv_line = 1. lv_pos = 1. ELSE. READ TABLE lt_text INDEX lv_line INTO lv_text. lv_pos = strlen( lv_text ) + 1. ENDIF. rv_location = |Line { lv_line }, Offset { lv_pos }|. ENDMETHOD. METHOD _parse. DATA lo_reader TYPE REF TO if_sxml_reader. DATA lr_stack_top LIKE LINE OF mt_stack. DATA lo_node TYPE REF TO if_sxml_node. FIELD-SYMBOLS LIKE LINE OF rt_json_tree. CLEAR mt_stack. IF iv_json IS INITIAL. RETURN. ENDIF. lo_reader = cl_sxml_string_reader=>create( cl_abap_codepage=>convert_to( iv_json ) ). "" TODO: self protection, check non-empty, check starting from object ... DO. lo_node = lo_reader->read_next_node( ). IF lo_node IS NOT BOUND. EXIT. ENDIF. CASE lo_node->type. WHEN if_sxml_node=>co_nt_element_open. DATA lt_attributes TYPE if_sxml_attribute=>attributes. DATA lo_attr LIKE LINE OF lt_attributes. DATA lo_open TYPE REF TO if_sxml_open_element. lo_open ?= lo_node. APPEND INITIAL LINE TO rt_json_tree ASSIGNING . -type = to_lower( lo_open->qname-name ). READ TABLE mt_stack INDEX 1 INTO lr_stack_top. IF sy-subrc = 0. -path = join_path( mt_stack ). lr_stack_top->children = lr_stack_top->children + 1. IF lr_stack_top->type = 'array'. -name = |{ lr_stack_top->children }|. -index = lr_stack_top->children. ELSE. lt_attributes = lo_open->get_attributes( ). LOOP AT lt_attributes INTO lo_attr. IF lo_attr->qname-name = 'name' AND lo_attr->value_type = if_sxml_value=>co_vt_text. -name = lo_attr->get_value( ). ENDIF. ENDLOOP. ENDIF. ENDIF. GET REFERENCE OF INTO lr_stack_top. INSERT lr_stack_top INTO mt_stack INDEX 1. WHEN if_sxml_node=>co_nt_element_close. DATA lo_close TYPE REF TO if_sxml_close_element. lo_close ?= lo_node. READ TABLE mt_stack INDEX 1 INTO lr_stack_top. DELETE mt_stack INDEX 1. IF lo_close->qname-name <> lr_stack_top->type. raise( 'Unexpected closing node type' ). ENDIF. WHEN if_sxml_node=>co_nt_value. DATA lo_value TYPE REF TO if_sxml_value_node. lo_value ?= lo_node. -value = lo_value->get_value( ). WHEN OTHERS. raise( 'Unexpected node type' ). ENDCASE. ENDDO. IF lines( mt_stack ) > 0. raise( 'Unexpected end of data' ). ENDIF. ENDMETHOD. METHOD join_path. FIELD-SYMBOLS LIKE LINE OF it_stack. LOOP AT it_stack ASSIGNING . rv_path = ->name && '/' && rv_path. ENDLOOP. ENDMETHOD. METHOD raise. zcx_abapgit_ajson_error=>raise( iv_location = join_path( mt_stack ) iv_msg = |JSON PARSER: { iv_error } @ { join_path( mt_stack ) }| ). ENDMETHOD. ENDCLASS. ********************************************************************** * SERIALIZER ********************************************************************** CLASS lcl_json_serializer DEFINITION FINAL CREATE PRIVATE. PUBLIC SECTION. CLASS-METHODS stringify IMPORTING it_json_tree TYPE zif_abapgit_ajson=>ty_nodes_ts iv_indent TYPE i DEFAULT 0 iv_keep_item_order TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rv_json_string) TYPE string RAISING zcx_abapgit_ajson_error. CLASS-METHODS class_constructor. PRIVATE SECTION. CLASS-DATA gv_comma_with_lf TYPE string. DATA mt_json_tree TYPE zif_abapgit_ajson=>ty_nodes_ts. DATA mv_keep_item_order TYPE abap_bool. DATA mt_buffer TYPE string_table. DATA mv_indent_step TYPE i. DATA mv_level TYPE i. CLASS-METHODS escape IMPORTING iv_unescaped TYPE string RETURNING VALUE(rv_escaped) TYPE string. METHODS _stringify RETURNING VALUE(rv_json_string) TYPE string RAISING zcx_abapgit_ajson_error. METHODS stringify_node IMPORTING is_node TYPE zif_abapgit_ajson=>ty_node RAISING zcx_abapgit_ajson_error. METHODS stringify_set IMPORTING iv_parent_path TYPE string iv_array TYPE abap_bool RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_json_serializer IMPLEMENTATION. METHOD class_constructor. gv_comma_with_lf = ',' && cl_abap_char_utilities=>newline. ENDMETHOD. METHOD stringify. DATA lo TYPE REF TO lcl_json_serializer. CREATE OBJECT lo. lo->mt_json_tree = it_json_tree. lo->mv_indent_step = iv_indent. lo->mv_keep_item_order = iv_keep_item_order. rv_json_string = lo->_stringify( ). ENDMETHOD. METHOD _stringify. FIELD-SYMBOLS LIKE LINE OF mt_json_tree. READ TABLE mt_json_tree ASSIGNING WITH KEY path = '' name = ''. "" Root IF sy-subrc <> 0. RETURN. ENDIF. stringify_node( ). rv_json_string = concat_lines_of( table = mt_buffer ). ENDMETHOD. METHOD stringify_node. DATA lv_item TYPE string. DATA lv_indent_prefix TYPE string. IF mv_indent_step > 0. lv_indent_prefix = repeat( val = ` ` occ = mv_indent_step * mv_level ). lv_item = lv_indent_prefix. ENDIF. IF is_node-name IS NOT INITIAL AND is_node-index IS INITIAL. "" Not root, not array item IF mv_indent_step > 0. lv_item = lv_item && |""{ is_node-name }"": |. ELSE. lv_item = |""{ is_node-name }"":|. ENDIF. ENDIF. CASE is_node-type. WHEN zif_abapgit_ajson=>node_type-array. lv_item = lv_item && '['. WHEN zif_abapgit_ajson=>node_type-object. lv_item = lv_item && '{'. WHEN zif_abapgit_ajson=>node_type-string. lv_item = lv_item && |""{ escape( is_node-value ) }""|. WHEN zif_abapgit_ajson=>node_type-boolean OR zif_abapgit_ajson=>node_type-number. lv_item = lv_item && is_node-value. WHEN zif_abapgit_ajson=>node_type-null. lv_item = lv_item && 'null'. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( iv_msg = |Unexpected type [{ is_node-type }]| iv_location = is_node-path && is_node-name ). ENDCASE. IF mv_indent_step > 0 AND ( is_node-type = zif_abapgit_ajson=>node_type-array OR is_node-type = zif_abapgit_ajson=>node_type-object ) AND is_node-children > 0. mv_level = mv_level + 1. lv_item = lv_item && cl_abap_char_utilities=>newline. ENDIF. APPEND lv_item TO mt_buffer. "" finish complex item IF is_node-type = zif_abapgit_ajson=>node_type-array OR is_node-type = zif_abapgit_ajson=>node_type-object. DATA lv_children_path TYPE string. DATA lv_tail TYPE string. lv_children_path = is_node-path && is_node-name && '/'. "" for root: path = '' and name = '', so result is '/' CASE is_node-type. WHEN zif_abapgit_ajson=>node_type-array. IF is_node-children > 0. stringify_set( iv_parent_path = lv_children_path iv_array = abap_true ). ENDIF. lv_tail = ']'. WHEN zif_abapgit_ajson=>node_type-object. IF is_node-children > 0. stringify_set( iv_parent_path = lv_children_path iv_array = abap_false ). ENDIF. lv_tail = '}'. ENDCASE. IF mv_indent_step > 0 AND is_node-children > 0. lv_tail = lv_indent_prefix && lv_tail. mv_level = mv_level - 1. ENDIF. APPEND lv_tail TO mt_buffer. ENDIF. ENDMETHOD. METHOD stringify_set. DATA lv_tab_key TYPE string. DATA lv_first_done TYPE abap_bool. FIELD-SYMBOLS LIKE LINE OF mt_json_tree. IF iv_array = abap_true. lv_tab_key = 'array_index'. "" path + index ELSEIF mv_keep_item_order = abap_true. lv_tab_key = 'item_order'. "" path + order ELSE. lv_tab_key = 'primary_key'. "" path + name ENDIF. LOOP AT mt_json_tree ASSIGNING USING KEY (lv_tab_key) WHERE path = iv_parent_path. IF lv_first_done = abap_false. lv_first_done = abap_true. ELSEIF mv_indent_step > 0. APPEND gv_comma_with_lf TO mt_buffer. ELSE. APPEND ',' TO mt_buffer. ENDIF. stringify_node( ). ENDLOOP. IF mv_indent_step > 0 AND lv_first_done = abap_true. "" only of items were in the list APPEND cl_abap_char_utilities=>newline TO mt_buffer. ENDIF. ENDMETHOD. METHOD escape. rv_escaped = iv_unescaped. IF rv_escaped CA |""\\\\\\t\\n\\r|. "" TODO consider performance ... "" see also https://www.json.org/json-en.html rv_escaped = replace( val = rv_escaped sub = '\\' with = '\\\\' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = |\\n| with = '\\n' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = |\\r| with = '\\r' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = |\\t| with = '\\t' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = '""' with = '\\""' occ = 0 ). ENDIF. ENDMETHOD. ENDCLASS. ********************************************************************** * JSON_TO_ABAP ********************************************************************** CLASS lcl_json_to_abap DEFINITION FINAL. PUBLIC SECTION. METHODS constructor IMPORTING !ii_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping OPTIONAL. METHODS to_abap IMPORTING it_nodes TYPE zif_abapgit_ajson=>ty_nodes_ts CHANGING c_container TYPE any RAISING zcx_abapgit_ajson_error. METHODS to_timestamp IMPORTING iv_value TYPE zif_abapgit_ajson=>ty_node-value RETURNING VALUE(rv_result) TYPE timestamp RAISING zcx_abapgit_ajson_error. METHODS to_date IMPORTING iv_value TYPE zif_abapgit_ajson=>ty_node-value RETURNING VALUE(rv_result) TYPE d RAISING zcx_abapgit_ajson_error. PRIVATE SECTION. TYPES: BEGIN OF ty_type_cache, type_path TYPE string, target_field_name TYPE string, dd TYPE REF TO cl_abap_datadescr, type_kind LIKE cl_abap_typedescr=>typekind_any, tab_item_buf TYPE REF TO data, END OF ty_type_cache. DATA mt_node_type_cache TYPE HASHED TABLE OF ty_type_cache WITH UNIQUE KEY type_path. DATA mr_nodes TYPE REF TO zif_abapgit_ajson=>ty_nodes_ts. DATA mi_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping. METHODS any_to_abap IMPORTING iv_path TYPE string is_parent_type TYPE ty_type_cache OPTIONAL i_container_ref TYPE REF TO data RAISING zcx_abapgit_ajson_error. METHODS value_to_abap IMPORTING is_node TYPE zif_abapgit_ajson=>ty_node is_node_type TYPE ty_type_cache i_container_ref TYPE REF TO data RAISING zcx_abapgit_ajson_error cx_sy_conversion_no_number. METHODS get_node_type IMPORTING is_node TYPE zif_abapgit_ajson=>ty_node OPTIONAL "" Empty for root is_parent_type TYPE ty_type_cache OPTIONAL i_container_ref TYPE REF TO data OPTIONAL RETURNING VALUE(rs_node_type) TYPE ty_type_cache RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_json_to_abap IMPLEMENTATION. METHOD constructor. mi_custom_mapping = ii_custom_mapping. ENDMETHOD. METHOD to_abap. DATA lr_ref TYPE REF TO data. CLEAR c_container. "" what about data/obj refs ? CLEAR mt_node_type_cache. GET REFERENCE OF c_container INTO lr_ref. GET REFERENCE OF it_nodes INTO mr_nodes. get_node_type( i_container_ref = lr_ref ). "" Pre-cache root node type any_to_abap( iv_path = '' i_container_ref = lr_ref ). ENDMETHOD. METHOD get_node_type. DATA lv_node_type_path TYPE string. DATA lo_sdescr TYPE REF TO cl_abap_structdescr. DATA lo_tdescr TYPE REF TO cl_abap_tabledescr. DATA lo_ddescr TYPE REF TO cl_abap_datadescr. "" Calculate type path IF is_parent_type-type_kind = cl_abap_typedescr=>typekind_table. lv_node_type_path = is_parent_type-type_path && '/-'. "" table item type ELSEIF is_parent_type-type_kind IS NOT INITIAL. lv_node_type_path = is_parent_type-type_path && '/' && is_node-name. ENDIF. "" For root node lv_node_type_path remains '' "" Get or create cached READ TABLE mt_node_type_cache INTO rs_node_type WITH KEY type_path = lv_node_type_path. IF sy-subrc <> 0. rs_node_type-type_path = lv_node_type_path. IF mi_custom_mapping IS BOUND. rs_node_type-target_field_name = to_upper( mi_custom_mapping->to_abap( iv_path = is_node-path iv_name = is_node-name ) ). IF rs_node_type-target_field_name IS INITIAL. rs_node_type-target_field_name = to_upper( is_node-name ). ENDIF. ELSE. rs_node_type-target_field_name = to_upper( is_node-name ). ENDIF. CASE is_parent_type-type_kind. WHEN 'h'. "" Table lo_tdescr ?= is_parent_type-dd. rs_node_type-dd = lo_tdescr->get_table_line_type( ). WHEN 'u' OR 'v'. "" Structure lo_sdescr ?= is_parent_type-dd. lo_sdescr->get_component_type( EXPORTING p_name = rs_node_type-target_field_name RECEIVING p_descr_ref = rs_node_type-dd EXCEPTIONS component_not_found = 4 ). IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( |Path not found| ). ENDIF. WHEN ''. "" Root node rs_node_type-dd ?= cl_abap_typedescr=>describe_by_data_ref( i_container_ref ). WHEN OTHERS. zcx_abapgit_ajson_error=>raise( |Unexpected parent type| ). ENDCASE. rs_node_type-type_kind = rs_node_type-dd->type_kind. "" for caching and cleaner unintialized access IF rs_node_type-type_kind = 'h'. "" Table lo_tdescr ?= rs_node_type-dd. IF lo_tdescr->table_kind <> 'S'. "" standard lo_ddescr = lo_tdescr->get_table_line_type( ). CREATE DATA rs_node_type-tab_item_buf TYPE HANDLE lo_ddescr. ENDIF. ENDIF. INSERT rs_node_type INTO TABLE mt_node_type_cache. ENDIF. ENDMETHOD. METHOD any_to_abap. DATA ls_node_type LIKE LINE OF mt_node_type_cache. DATA lx_ajson TYPE REF TO zcx_abapgit_ajson_error. DATA lx_root TYPE REF TO cx_root. DATA lr_target_field TYPE REF TO data. FIELD-SYMBOLS TYPE zif_abapgit_ajson=>ty_node. FIELD-SYMBOLS TYPE STANDARD TABLE. FIELD-SYMBOLS TYPE ANY TABLE. FIELD-SYMBOLS TYPE any. FIELD-SYMBOLS TYPE any. "" Assign container CASE is_parent_type-type_kind. WHEN 'h'. "" Table IF is_parent_type-tab_item_buf IS BOUND. "" Indirect hint that table was sorted/hashed, see get_node_type. ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. lr_target_field = is_parent_type-tab_item_buf. "" For hashed/sorted table - same buffer for all children ASSIGN is_parent_type-tab_item_buf->* TO . ASSERT sy-subrc = 0. ELSE. ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. ENDIF. WHEN 'u' OR 'v'. "" Structure ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. ENDCASE. TRY. "" array_index because stringified index goes in wrong order [1, 10, 2 ...] LOOP AT mr_nodes->* ASSIGNING USING KEY array_index WHERE path = iv_path. "" Get or create type cache record IF is_parent_type-type_kind <> 'h' OR ls_node_type-type_kind IS INITIAL. "" table records are the same, no need to refetch twice ls_node_type = get_node_type( is_node = is_parent_type = is_parent_type ). ENDIF. "" Validate node type IF ls_node_type-type_kind CA 'lr'. "" data/obj ref "" TODO maybe in future zcx_abapgit_ajson_error=>raise( 'Cannot assign to ref' ). ENDIF. "" Find target field reference CASE is_parent_type-type_kind. WHEN 'h'. "" Table IF NOT ls_node_type-target_field_name CO '0123456789'. "" Does not affect anything actually but for integrity zcx_abapgit_ajson_error=>raise( 'Need index to access tables' ). ENDIF. IF is_parent_type-tab_item_buf IS NOT BOUND. "" Indirect hint that table was srt/hsh, see get_node_type APPEND INITIAL LINE TO REFERENCE INTO lr_target_field. ASSERT sy-subrc = 0. ENDIF. WHEN 'u' OR 'v'. FIELD-SYMBOLS TYPE any. ASSIGN COMPONENT ls_node_type-target_field_name OF STRUCTURE TO . ASSERT sy-subrc = 0. GET REFERENCE OF INTO lr_target_field. WHEN ''. "" Root node lr_target_field = i_container_ref. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( 'Unexpected parent type' ). ENDCASE. "" Process value assignment CASE -type. WHEN zif_abapgit_ajson=>node_type-object. IF NOT ls_node_type-type_kind CO 'uv'. zcx_abapgit_ajson_error=>raise( 'Expected structure' ). ENDIF. any_to_abap( iv_path = -path && -name && '/' is_parent_type = ls_node_type i_container_ref = lr_target_field ). WHEN zif_abapgit_ajson=>node_type-array. IF NOT ls_node_type-type_kind = 'h'. zcx_abapgit_ajson_error=>raise( 'Expected table' ). ENDIF. any_to_abap( iv_path = -path && -name && '/' is_parent_type = ls_node_type i_container_ref = lr_target_field ). WHEN OTHERS. value_to_abap( is_node = is_node_type = ls_node_type i_container_ref = lr_target_field ). ENDCASE. IF is_parent_type-tab_item_buf IS BOUND. "" Indirect hint that table was sorted/hashed, see get_node_type. TRY. INSERT INTO TABLE . CATCH cx_sy_itab_duplicate_key. sy-subrc = 4. ENDTRY. IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( 'Duplicate insertion' ). ENDIF. ENDIF. ENDLOOP. CATCH zcx_abapgit_ajson_error INTO lx_ajson. IF lx_ajson->location IS INITIAL. lx_ajson->set_location( -path && -name ). ENDIF. RAISE EXCEPTION lx_ajson. CATCH cx_sy_conversion_no_number. zcx_abapgit_ajson_error=>raise( iv_msg = 'Source is not a number' iv_location = -path && -name ). CATCH cx_root INTO lx_root. zcx_abapgit_ajson_error=>raise( iv_msg = lx_root->get_text( ) iv_location = -path && -name ). ENDTRY. ENDMETHOD. METHOD value_to_abap. FIELD-SYMBOLS TYPE any. IF is_node_type-type_kind CA 'lruvh'. "" refs, table, strucs zcx_abapgit_ajson_error=>raise( |Unsupported target for value [{ is_node_type-type_kind }]| ). ENDIF. ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. CASE is_node-type. WHEN zif_abapgit_ajson=>node_type-null. "" Do nothing WHEN zif_abapgit_ajson=>node_type-boolean. "" TODO: check type ? = boolc( is_node-value = 'true' ). WHEN zif_abapgit_ajson=>node_type-number. "" TODO: check type ? = is_node-value. WHEN zif_abapgit_ajson=>node_type-string. "" TODO: check type ? IF is_node_type-type_kind = 'D' AND is_node-value IS NOT INITIAL. = to_date( is_node-value ). ELSEIF is_node_type-type_kind = 'P' AND is_node-value IS NOT INITIAL. = to_timestamp( is_node-value ). ELSE. = is_node-value. ENDIF. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( |Unexpected JSON type [{ is_node-type }]| ). ENDCASE. ENDMETHOD. METHOD to_date. DATA lv_y TYPE c LENGTH 4. DATA lv_m TYPE c LENGTH 2. DATA lv_d TYPE c LENGTH 2. FIND FIRST OCCURRENCE OF REGEX '^(\\d{4})-(\\d{2})-(\\d{2})(T|$)' IN iv_value SUBMATCHES lv_y lv_m lv_d. IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( 'Unexpected date format' ). ENDIF. CONCATENATE lv_y lv_m lv_d INTO rv_result. ENDMETHOD. METHOD to_timestamp. CONSTANTS lc_utc TYPE c LENGTH 6 VALUE 'UTC'. CONSTANTS lc_regex_ts_with_hour TYPE string VALUE `^(\\d{4})-(\\d{2})-(\\d{2})(T)(\\d{2}):(\\d{2}):(\\d{2})(\\+)(\\d{2}):(\\d{2})`. CONSTANTS lc_regex_ts_utc TYPE string VALUE `^(\\d{4})-(\\d{2})-(\\d{2})(T)(\\d{2}):(\\d{2}):(\\d{2})(Z|$)`. DATA: BEGIN OF ls_timestamp, year TYPE c LENGTH 4, month TYPE c LENGTH 2, day TYPE c LENGTH 2, t TYPE c LENGTH 1, hour TYPE c LENGTH 2, minute TYPE c LENGTH 2, second TYPE c LENGTH 2, local_sign TYPE c LENGTH 1, local_hour TYPE c LENGTH 2, local_minute TYPE c LENGTH 2, END OF ls_timestamp. DATA lv_date TYPE d. DATA lv_time TYPE t. DATA lv_seconds_conv TYPE i. DATA lv_timestamp TYPE timestampl. FIND FIRST OCCURRENCE OF REGEX lc_regex_ts_with_hour IN iv_value SUBMATCHES ls_timestamp-year ls_timestamp-month ls_timestamp-day ls_timestamp-t ls_timestamp-hour ls_timestamp-minute ls_timestamp-second ls_timestamp-local_sign ls_timestamp-local_hour ls_timestamp-local_minute. IF sy-subrc = 0. lv_seconds_conv = ( ls_timestamp-local_hour * 3600 ) + ( ls_timestamp-local_minute * 60 ). ELSE. FIND FIRST OCCURRENCE OF REGEX lc_regex_ts_utc IN iv_value SUBMATCHES ls_timestamp-year ls_timestamp-month ls_timestamp-day ls_timestamp-t ls_timestamp-hour ls_timestamp-minute ls_timestamp-second. IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( 'Unexpected timestamp format' ). ENDIF. ENDIF. CONCATENATE ls_timestamp-year ls_timestamp-month ls_timestamp-day INTO lv_date. CONCATENATE ls_timestamp-hour ls_timestamp-minute ls_timestamp-second INTO lv_time. CONVERT DATE lv_date TIME lv_time INTO TIME STAMP lv_timestamp TIME ZONE lc_utc. TRY. CASE ls_timestamp-local_sign. WHEN '-'. lv_timestamp = cl_abap_tstmp=>add( tstmp = lv_timestamp secs = lv_seconds_conv ). WHEN '+'. lv_timestamp = cl_abap_tstmp=>subtractsecs( tstmp = lv_timestamp secs = lv_seconds_conv ). ENDCASE. CATCH cx_parameter_invalid_range cx_parameter_invalid_type. zcx_abapgit_ajson_error=>raise( 'Unexpected error calculating timestamp' ). ENDTRY. cl_abap_tstmp=>move( EXPORTING tstmp_src = lv_timestamp IMPORTING tstmp_tgt = rv_result ). ENDMETHOD. ENDCLASS. ********************************************************************** * ABAP_TO_JSON ********************************************************************** CLASS lcl_abap_to_json DEFINITION FINAL. PUBLIC SECTION. CLASS-METHODS convert IMPORTING iv_data TYPE any is_prefix TYPE zif_abapgit_ajson=>ty_path_name OPTIONAL iv_array_index TYPE i DEFAULT 0 ii_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping OPTIONAL iv_keep_item_order TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rt_nodes) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. CLASS-METHODS insert_with_type IMPORTING iv_data TYPE any iv_type TYPE string is_prefix TYPE zif_abapgit_ajson=>ty_path_name OPTIONAL iv_array_index TYPE i DEFAULT 0 ii_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping OPTIONAL iv_keep_item_order TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rt_nodes) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. CLASS-METHODS class_constructor. PRIVATE SECTION. CLASS-DATA gv_ajson_absolute_type_name TYPE string. DATA mi_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping. DATA mv_keep_item_order TYPE abap_bool. METHODS convert_any IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_ajson IMPORTING io_json TYPE REF TO zcl_abapgit_ajson is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_value IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_ref IMPORTING iv_data TYPE any is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_struc IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt cs_root TYPE zif_abapgit_ajson=>ty_node OPTIONAL RAISING zcx_abapgit_ajson_error. METHODS convert_table IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS insert_value_with_type IMPORTING iv_data TYPE any iv_type TYPE string io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_abap_to_json IMPLEMENTATION. METHOD class_constructor. DATA lo_dummy TYPE REF TO zcl_abapgit_ajson. DATA lo_type TYPE REF TO cl_abap_refdescr. lo_type ?= cl_abap_typedescr=>describe_by_data( lo_dummy ). gv_ajson_absolute_type_name = lo_type->get_referenced_type( )->absolute_name. ENDMETHOD. METHOD convert. DATA lo_type TYPE REF TO cl_abap_typedescr. DATA lo_converter TYPE REF TO lcl_abap_to_json. lo_type = cl_abap_typedescr=>describe_by_data( iv_data ). CREATE OBJECT lo_converter. lo_converter->mi_custom_mapping = ii_custom_mapping. lo_converter->mv_keep_item_order = iv_keep_item_order. lo_converter->convert_any( EXPORTING iv_data = iv_data io_type = lo_type is_prefix = is_prefix iv_index = iv_array_index CHANGING ct_nodes = rt_nodes ). ENDMETHOD. METHOD convert_any. CASE io_type->kind. WHEN cl_abap_typedescr=>kind_elem. convert_value( EXPORTING iv_data = iv_data io_type = io_type is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). WHEN cl_abap_typedescr=>kind_struct. convert_struc( EXPORTING iv_data = iv_data io_type = io_type is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). WHEN cl_abap_typedescr=>kind_table. convert_table( EXPORTING iv_data = iv_data io_type = io_type is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). WHEN OTHERS. IF io_type->type_kind = cl_abap_typedescr=>typekind_dref. convert_ref( EXPORTING iv_data = iv_data is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). ELSEIF io_type->type_kind = cl_abap_typedescr=>typekind_oref AND cl_abap_typedescr=>describe_by_object_ref( iv_data )->absolute_name = gv_ajson_absolute_type_name. convert_ajson( EXPORTING io_json = iv_data is_prefix = is_prefix iv_index = iv_index CHANGING ct_nodes = ct_nodes ). ELSE. zcx_abapgit_ajson_error=>raise( |Unsupported type [{ io_type->type_kind }] @{ is_prefix-path && is_prefix-name }| ). ENDIF. ENDCASE. ENDMETHOD. METHOD convert_ajson. FIELD-SYMBOLS LIKE LINE OF ct_nodes. FIELD-SYMBOLS LIKE LINE OF ct_nodes. IF io_json IS NOT BOUND. RETURN. ENDIF. LOOP AT io_json->mt_json_tree ASSIGNING . APPEND TO ct_nodes ASSIGNING . IF -path IS INITIAL AND -name IS INITIAL. "" root node -path = is_prefix-path. -name = is_prefix-name. -index = iv_index. ELSE. -path = is_prefix-path && is_prefix-name && -path. ENDIF. ENDLOOP. ENDMETHOD. METHOD convert_value. DATA ls_node LIKE LINE OF ct_nodes. ls_node-path = is_prefix-path. ls_node-name = is_prefix-name. ls_node-index = iv_index. ls_node-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_node-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_node-name IS INITIAL. ls_node-name = is_prefix-name. ENDIF. IF io_type->absolute_name = '\\TYPE-POOL=ABAP\\TYPE=ABAP_BOOL' OR io_type->absolute_name = '\\TYPE=ABAP_BOOLEAN' OR io_type->absolute_name = '\\TYPE=XSDBOOLEAN' OR io_type->absolute_name = '\\TYPE=FLAG' OR io_type->absolute_name = '\\TYPE=XFELD'. ls_node-type = zif_abapgit_ajson=>node_type-boolean. IF iv_data IS NOT INITIAL. ls_node-value = 'true'. ELSE. ls_node-value = 'false'. ENDIF. ELSEIF io_type->type_kind CO 'CNgXyDT'. "" Char like, date/time, xstring ls_node-type = zif_abapgit_ajson=>node_type-string. ls_node-value = |{ iv_data }|. ELSEIF io_type->type_kind CO 'bsI8PaeF'. "" Numeric ls_node-type = zif_abapgit_ajson=>node_type-number. ls_node-value = |{ iv_data }|. ELSE. zcx_abapgit_ajson_error=>raise( |Unexpected elementary type [{ io_type->type_kind }] @{ is_prefix-path && is_prefix-name }| ). ENDIF. APPEND ls_node TO ct_nodes. ENDMETHOD. METHOD convert_ref. DATA ls_node LIKE LINE OF ct_nodes. ls_node-path = is_prefix-path. ls_node-name = is_prefix-name. ls_node-index = iv_index. ls_node-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_node-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_node-name IS INITIAL. ls_node-name = is_prefix-name. ENDIF. IF iv_data IS INITIAL. ls_node-type = zif_abapgit_ajson=>node_type-null. ls_node-value = 'null'. ELSE. "" TODO support data references zcx_abapgit_ajson_error=>raise( |Unexpected reference @{ is_prefix-path && is_prefix-name }| ). ENDIF. APPEND ls_node TO ct_nodes. ENDMETHOD. METHOD convert_struc. DATA lo_struc TYPE REF TO cl_abap_structdescr. DATA lt_comps TYPE cl_abap_structdescr=>component_table. DATA ls_next_prefix LIKE is_prefix. DATA lv_item_order TYPE i. DATA ls_root LIKE LINE OF ct_nodes. FIELD-SYMBOLS LIKE ls_root. FIELD-SYMBOLS LIKE LINE OF lt_comps. FIELD-SYMBOLS TYPE any. "" Object root IF cs_root IS SUPPLIED. "" call for include structure ASSIGN cs_root TO . ELSE. "" First call ls_root-path = is_prefix-path. ls_root-name = is_prefix-name. ls_root-type = zif_abapgit_ajson=>node_type-object. ls_root-index = iv_index. IF mi_custom_mapping IS BOUND. ls_root-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_root-name IS INITIAL. ls_root-name = is_prefix-name. ENDIF. ls_root-order = iv_item_order. APPEND ls_root TO ct_nodes ASSIGNING . ENDIF. "" Object attributes lo_struc ?= io_type. lt_comps = lo_struc->get_components( ). "" get_components is potentially much slower than lo_struc->components "" but ! we still need it to identify booleans "" and rtti seems to cache type descriptions really well (https://github.com/sbcgua/benchmarks.git) "" the structures will be repeated in real life ls_next_prefix-path = is_prefix-path && ls_root-name && '/'. LOOP AT lt_comps ASSIGNING . IF -as_include = abap_true. convert_struc( EXPORTING iv_data = iv_data io_type = -type is_prefix = is_prefix CHANGING cs_root = ct_nodes = ct_nodes ). ELSE. -children = -children + 1. ls_next_prefix-name = to_lower( -name ). ASSIGN COMPONENT -name OF STRUCTURE iv_data TO . ASSERT sy-subrc = 0. IF mv_keep_item_order = abap_true. lv_item_order = -children. ENDIF. convert_any( EXPORTING iv_data = io_type = -type is_prefix = ls_next_prefix iv_item_order = lv_item_order CHANGING ct_nodes = ct_nodes ). ENDIF. ENDLOOP. ENDMETHOD. METHOD convert_table. DATA lo_table TYPE REF TO cl_abap_tabledescr. DATA lo_ltype TYPE REF TO cl_abap_typedescr. DATA ls_next_prefix LIKE is_prefix. DATA lv_tabix TYPE sy-tabix. DATA ls_root LIKE LINE OF ct_nodes. FIELD-SYMBOLS LIKE ls_root. FIELD-SYMBOLS TYPE ANY TABLE. FIELD-SYMBOLS TYPE any. "" Array root ls_root-path = is_prefix-path. ls_root-name = is_prefix-name. ls_root-type = zif_abapgit_ajson=>node_type-array. ls_root-index = iv_index. ls_root-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_root-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_root-name IS INITIAL. ls_root-name = is_prefix-name. ENDIF. APPEND ls_root TO ct_nodes ASSIGNING . "" Array items lo_table ?= io_type. lo_ltype = lo_table->get_table_line_type( ). ls_next_prefix-path = is_prefix-path && is_prefix-name && '/'. ASSIGN iv_data TO . lv_tabix = 1. LOOP AT ASSIGNING . ls_next_prefix-name = to_lower( |{ lv_tabix }| ). convert_any( EXPORTING iv_data = io_type = lo_ltype is_prefix = ls_next_prefix iv_index = -children + 1 CHANGING ct_nodes = ct_nodes ). -children = -children + 1. lv_tabix = lv_tabix + 1. ENDLOOP. ENDMETHOD. METHOD insert_with_type. DATA lo_type TYPE REF TO cl_abap_typedescr. DATA lo_converter TYPE REF TO lcl_abap_to_json. lo_type = cl_abap_typedescr=>describe_by_data( iv_data ). CREATE OBJECT lo_converter. lo_converter->mi_custom_mapping = ii_custom_mapping. lo_converter->mv_keep_item_order = iv_keep_item_order. lo_converter->insert_value_with_type( EXPORTING iv_data = iv_data iv_type = iv_type io_type = lo_type is_prefix = is_prefix iv_index = iv_array_index CHANGING ct_nodes = rt_nodes ). ENDMETHOD. METHOD insert_value_with_type. DATA lv_prefix TYPE string. DATA ls_node LIKE LINE OF ct_nodes. lv_prefix = is_prefix-path && is_prefix-name. IF io_type->type_kind CO 'CNgXyDT'. "" Char like, date/time, xstring IF iv_type = zif_abapgit_ajson=>node_type-boolean AND iv_data <> 'true' AND iv_data <> 'false'. zcx_abapgit_ajson_error=>raise( |Unexpected boolean value [{ iv_data }] @{ lv_prefix }| ). ELSEIF iv_type = zif_abapgit_ajson=>node_type-null AND iv_data IS NOT INITIAL. zcx_abapgit_ajson_error=>raise( |Unexpected null value [{ iv_data }] @{ lv_prefix }| ). ELSEIF iv_type = zif_abapgit_ajson=>node_type-number AND iv_data CN '0123456789. E+-'. zcx_abapgit_ajson_error=>raise( |Unexpected numeric value [{ iv_data }] @{ lv_prefix }| ). ELSEIF iv_type <> zif_abapgit_ajson=>node_type-string AND iv_type <> zif_abapgit_ajson=>node_type-boolean AND iv_type <> zif_abapgit_ajson=>node_type-null AND iv_type <> zif_abapgit_ajson=>node_type-number. zcx_abapgit_ajson_error=>raise( |Unexpected type for value [{ iv_type },{ iv_data }] @{ lv_prefix }| ). ENDIF. ELSEIF io_type->type_kind CO 'bsI8PaeF'. "" Numeric IF iv_type <> zif_abapgit_ajson=>node_type-number. zcx_abapgit_ajson_error=>raise( |Unexpected value for numeric [{ iv_data }] @{ lv_prefix }| ). ENDIF. ELSE. zcx_abapgit_ajson_error=>raise( |Unexpected type [{ io_type->type_kind }] @{ lv_prefix }| ). ENDIF. ls_node-path = is_prefix-path. ls_node-name = is_prefix-name. ls_node-index = iv_index. ls_node-value = iv_data. ls_node-type = iv_type. ls_node-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_node-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_node-name IS INITIAL. ls_node-name = is_prefix-name. ENDIF. APPEND ls_node TO ct_nodes. ENDMETHOD. ENDCLASS. ********************************************************************** * FILTER RUNNER ********************************************************************** CLASS lcl_filter_runner DEFINITION FINAL. PUBLIC SECTION. METHODS run IMPORTING ii_filter TYPE REF TO zif_abapgit_ajson_filter it_source_tree TYPE zif_abapgit_ajson=>ty_nodes_ts CHANGING ct_dest_tree TYPE zif_abapgit_ajson=>ty_nodes_ts RAISING zcx_abapgit_ajson_error. PRIVATE SECTION. DATA mi_filter TYPE REF TO zif_abapgit_ajson_filter. DATA mr_source_tree TYPE REF TO zif_abapgit_ajson=>ty_nodes_ts. DATA mr_dest_tree TYPE REF TO zif_abapgit_ajson=>ty_nodes_ts. METHODS walk IMPORTING iv_path TYPE string CHANGING cs_parent TYPE zif_abapgit_ajson=>ty_node OPTIONAL RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_filter_runner IMPLEMENTATION. METHOD run. ASSERT ii_filter IS BOUND. mi_filter = ii_filter. CLEAR ct_dest_tree. GET REFERENCE OF it_source_tree INTO mr_source_tree. GET REFERENCE OF ct_dest_tree INTO mr_dest_tree. walk( iv_path = '' ). ENDMETHOD. METHOD walk. DATA ls_node TYPE zif_abapgit_ajson=>ty_node. LOOP AT mr_source_tree->* INTO ls_node WHERE path = iv_path. CASE ls_node-type. WHEN zif_abapgit_ajson=>node_type-boolean OR zif_abapgit_ajson=>node_type-null OR zif_abapgit_ajson=>node_type-number OR zif_abapgit_ajson=>node_type-string. IF mi_filter->keep_node( ls_node ) = abap_false. CONTINUE. ENDIF. WHEN zif_abapgit_ajson=>node_type-array OR zif_abapgit_ajson=>node_type-object. IF mi_filter->keep_node( is_node = ls_node iv_visit = zif_abapgit_ajson_filter=>visit_type-open ) = abap_false. CONTINUE. ENDIF. "" Intentionally clear AFTER ""open"" CLEAR ls_node-children. walk( EXPORTING iv_path = iv_path && ls_node-name && `/` CHANGING cs_parent = ls_node ). IF mi_filter->keep_node( is_node = ls_node iv_visit = zif_abapgit_ajson_filter=>visit_type-close ) = abap_false. CONTINUE. ENDIF. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( |Unexpected node type { ls_node-type }| ). ENDCASE. IF cs_parent IS SUPPLIED. cs_parent-children = cs_parent-children + 1. IF cs_parent-type = zif_abapgit_ajson=>node_type-array. ls_node-name = |{ cs_parent-children }|. ls_node-index = cs_parent-children. ENDIF. ENDIF. INSERT ls_node INTO TABLE mr_dest_tree->*. ENDLOOP. ENDMETHOD. ENDCLASS. ",12434,True,2644.551001468508,median "********************************************************************** ********************************************************************** CLASS cl_ex_sheet IMPLEMENTATION. *--------------------------------------------------------------------* METHOD constructor. DATA: l_sheet_ind TYPE string, lo_row TYPE REF TO if_ixml_element, lo_col TYPE REF TO if_ixml_element, lo_cell TYPE REF TO if_ixml_element, ls_cell TYPE REF TO ts_ex_cell, lo_merge_cell TYPE REF TO if_ixml_element, lo_data_valid TYPE REF TO if_ixml_element, l_val TYPE string, ls_area TYPE REF TO ts_ex_area, ls_cell_beg TYPE REF TO ts_ex_cell, ls_cell_end TYPE REF TO ts_ex_cell, ls_defined_name TYPE REF TO ts_ex_defined_name, ls_list_object TYPE REF TO ts_ex_list_object, l_prev_row TYPE i, l_prev_col TYPE i, lv_ind TYPE i, lv_name TYPE string, ls_blank TYPE ts_ex_cell. "" Path to the sheet int_2_text iv_ind l_sheet_ind. CONCATENATE `xl/worksheets/sheet` l_sheet_ind `.xml` INTO mv_full_path. ""#EC NOTEXT "" Content as an object zcl_eui_conv=>xml_from_zip( EXPORTING io_zip = io_xlsx->mo_zip iv_name = mv_full_path IMPORTING eo_xmldoc = mo_dom ). *************************************** "" Loop through excels rows lo_row ?= mo_dom->find_from_name( 'row' ). ""#EC NOTEXT WHILE lo_row IS BOUND. "" Add new row zcl_xtt_excel_xlsx=>row_read_xml( EXPORTING io_node = lo_row CHANGING ct_rows = mt_rows ). "" Loop through excels cells lo_cell = lo_row->find_from_name( 'c' ). ""#EC NOTEXT WHILE lo_cell IS BOUND. io_xlsx->cell_read_xml( EXPORTING io_node = lo_cell CHANGING ct_cells = mt_cells ). "" Add by key ""INSERT ls_cell INTO TABLE lt_cells_hash. lo_cell ?= lo_cell->get_next( ). ENDWHILE. lo_row ?= lo_row->get_next( ). ENDWHILE. "" No need already sorted ""SORT mt_cells BY table_line->c_row table_line->c_col_ind. *************************************** "" Loop through excels columns lo_col ?= mo_dom->find_from_name( 'col' ). ""#EC NOTEXT WHILE lo_col IS BOUND. "" Add new col zcl_xtt_excel_xlsx=>column_read_xml( EXPORTING io_node = lo_col CHANGING ct_columns = mt_columns ). lo_col ?= lo_col->get_next( ). ENDWHILE. *************************************** lo_merge_cell ?= mo_dom->find_from_name( 'mergeCell' ). ""#EC NOTEXT WHILE lo_merge_cell IS BOUND. "" Create new area l_val = lo_merge_cell->get_attribute( 'ref' ). ""#EC NOTEXT CREATE DATA ls_area. zcl_xtt_excel_xlsx=>area_read_xml( iv_value = l_val is_area = ls_area ). "" Always 2 cells READ TABLE ls_area->a_cells REFERENCE INTO ls_cell_beg INDEX 1. READ TABLE ls_area->a_cells REFERENCE INTO ls_cell_end INDEX 2. "" Get ref to existing or ls_cell_beg cell ls_cell = find_cell( ls_cell_beg->* ). "" Fill dx ls_cell->c_merge_row_dx = ls_cell_end->c_row - ls_cell_beg->c_row. ls_cell->c_merge_col_dx = ls_cell_end->c_col_ind - ls_cell_beg->c_col_ind. "" Next lo_merge_cell ?= lo_merge_cell->get_next( ). ENDWHILE. *************************************** lo_data_valid ?= mo_dom->find_from_name( 'dataValidation' ). ""#EC NOTEXT WHILE lo_data_valid IS BOUND. APPEND INITIAL LINE TO mt_data_valid REFERENCE INTO ls_area. "" Create new area l_val = lo_data_valid->get_attribute( 'sqref' ). ""#EC NOTEXT zcl_xtt_excel_xlsx=>area_read_xml( iv_value = l_val is_area = ls_area ). LOOP AT ls_area->a_cells REFERENCE INTO ls_cell. "" Get existing cell Or insert new one find_cell( ls_cell->* ). ENDLOOP. "" Next lo_data_valid ?= lo_data_valid->get_next( ). ENDWHILE. *************************************** "" Defined name contains areas mv_name = io_node->get_attribute( `name` ). ""#EC NOTEXT LOOP AT io_xlsx->mt_defined_names REFERENCE INTO ls_defined_name. LOOP AT ls_defined_name->d_areas REFERENCE INTO ls_area WHERE a_sheet_name = mv_name. "" Reference to reference LOOP AT ls_area->a_cells REFERENCE INTO ls_cell. "" Get existing cell Or insert new one find_cell( ls_cell->* ). ENDLOOP. ENDLOOP. ENDLOOP. *************************************** "" Find related list objects CONCATENATE `xl/worksheets/_rels/sheet` l_sheet_ind `.xml.rels` INTO l_val. ""#EC NOTEXT io_xlsx->list_object_read_xml( EXPORTING iv_path = l_val CHANGING ct_list_objects = mt_list_objects ). LOOP AT mt_list_objects REFERENCE INTO ls_list_object. LOOP AT ls_list_object->area-a_cells REFERENCE INTO ls_cell. "" Get existing cell Or insert new one find_cell( ls_cell->* ). ENDLOOP. ENDLOOP. *************************************** LOOP AT mt_cells REFERENCE INTO ls_cell WHERE c_value CS `;direction=column`. ""#EC NOTEXT "" Use columns lv_ind = sy-fdpos - 1. lv_name = ls_cell->c_value+1(lv_ind). INSERT lv_name INTO TABLE mt_column_dir. CLEAR ls_cell->c_value. "" Add blank cell CHECK ls_cell->c_col_ind > 1. ls_blank-c_row = ls_cell->c_row. ls_blank-c_col_ind = ls_cell->c_col_ind - 1. find_cell( ls_blank ). ENDLOOP. *************************************** "" Write offest l_prev_row = 0. l_prev_col = 0. LOOP AT mt_cells REFERENCE INTO ls_cell. "" If new row ls_cell->c_row_dx > 0 ls_cell->c_row_dx = ls_cell->c_row - l_prev_row. "" If new row then column also from 0 IF ls_cell->c_row_dx <> 0. l_prev_col = 0. ENDIF. ls_cell->c_col_dx = ls_cell->c_col_ind - l_prev_col. l_prev_row = ls_cell->c_row. l_prev_col = ls_cell->c_col_ind. ENDLOOP. *************************************** ENDMETHOD. ""constructor *--------------------------------------------------------------------* METHOD find_cell. DATA: ls_row TYPE ts_ex_row. READ TABLE mt_cells BINARY SEARCH REFERENCE INTO rr_ex_cell WITH KEY "" with table key c_row = ir_cell-c_row c_col_ind = ir_cell-c_col_ind. IF sy-subrc <> 0. INSERT ir_cell INTO mt_cells INDEX sy-tabix REFERENCE INTO rr_ex_cell. READ TABLE mt_rows TRANSPORTING NO FIELDS WITH TABLE KEY r = ir_cell-c_row. IF sy-subrc <> 0. ls_row-r = sy-tabix. INSERT ls_row INTO TABLE mt_rows. ENDIF. ENDIF. ENDMETHOD. *--------------------------------------------------------------------* METHOD fill_shared_strings. DATA: ls_cell TYPE REF TO ts_ex_cell. "" Add one by one LOOP AT mt_cells REFERENCE INTO ls_cell. ""WHERE c_value IS NOT INITIAL. CHECK zcl_xtt_excel_xlsx=>cell_is_string( ls_cell ) = abap_true. APPEND ls_cell->c_value TO ct_shared_strings. ENDLOOP. ENDMETHOD. ""fill_shared_strings *--------------------------------------------------------------------* METHOD save. DATA: l_sheet_data TYPE string, l_merge_cells TYPE string, l_merge_cnt TYPE i, ls_cell TYPE REF TO ts_ex_cell, ls_row TYPE REF TO ts_ex_row, ls_blank_row TYPE REF TO ts_ex_row, l_new_row_ind TYPE i, l_new_col_ind TYPE i, l_str TYPE string, lo_data_valid TYPE REF TO if_ixml_element, lo_mc TYPE REF TO if_ixml_element, ls_list_object TYPE REF TO ts_ex_list_object, lt_columns LIKE mt_columns, ls_column TYPE ts_ex_column, lv_columns_text TYPE string, lr_cell_ref TYPE REF TO ts_cell_ref, ls_cell_ref TYPE ts_cell_ref, ls_defined_name TYPE REF TO ts_ex_defined_name, ls_area TYPE REF TO ts_ex_area, lv_address TYPE string, lo_table TYPE REF TO if_ixml_element. "" Blank sheet CHECK mt_cells IS NOT INITIAL. ***************** "" Find old -> new match LOOP AT mt_cells REFERENCE INTO ls_cell. READ TABLE mt_cell_ref REFERENCE INTO lr_cell_ref WITH TABLE KEY r = ls_cell->c_row c = ls_cell->c_col_ind. IF sy-subrc <> 0. ls_cell_ref-r = ls_cell->c_row. ls_cell_ref-c = ls_cell->c_col_ind. ls_cell_ref-beg = ls_cell. INSERT ls_cell_ref INTO TABLE mt_cell_ref REFERENCE INTO lr_cell_ref. ENDIF. lr_cell_ref->end = ls_cell. ENDLOOP. ***************** "" Write cells data one by one CREATE DATA ls_blank_row. LOOP AT mt_cells REFERENCE INTO ls_cell. "" New row index as a string l_new_row_ind = l_new_row_ind + ls_cell->c_row_dx. "" New row IF ls_cell->c_row_dx > 0. l_new_col_ind = 0. "" Closing tag IF l_sheet_data IS NOT INITIAL. CONCATENATE l_sheet_data `` INTO l_sheet_data. ENDIF. "" Read by previous key READ TABLE mt_rows WITH TABLE KEY r = ls_cell->c_row REFERENCE INTO ls_row. IF sy-subrc = 0. zcl_xtt_excel_xlsx=>row_write_xml( EXPORTING is_row = ls_row iv_new_row = l_new_row_ind iv_outline_level = ls_cell->c_row_outline CHANGING cv_sheet_data = l_sheet_data ). ELSE. ls_blank_row->r = ls_cell->c_row. zcl_xtt_excel_xlsx=>row_write_xml( EXPORTING is_row = ls_blank_row iv_new_row = l_new_row_ind iv_outline_level = ls_cell->c_row_outline CHANGING cv_sheet_data = l_sheet_data ). ENDIF. ENDIF. *********** "" New column l_new_col_ind = l_new_col_ind + ls_cell->c_col_dx. DO 1 TIMES. "" Existing old column READ TABLE mt_columns INTO ls_column WITH TABLE KEY min = ls_cell->c_col_ind. "" Prog error CHECK sy-subrc = 0. IF ls_column-outline_skip = abap_true. CLEAR ls_column-outlinelevel. ENDIF. "" New outline IF ls_cell->c_column_outline IS NOT INITIAL. int_2_text ls_cell->c_column_outline ls_column-outlinelevel. ENDIF. IF l_new_col_ind <> ls_cell->c_col_ind. ls_column-min = ls_column-max = l_new_col_ind. ENDIF. INSERT ls_column INTO TABLE lt_columns. ENDDO. *********** "" Append cell info io_xlsx->cell_write_xml( EXPORTING is_cell = ls_cell iv_new_row = l_new_row_ind iv_new_col_ind = l_new_col_ind CHANGING cv_sheet_data = l_sheet_data cv_merge_cnt = l_merge_cnt cv_merge_cells = l_merge_cells ). ENDLOOP. "" New columns lv_columns_text = zcl_xtt_excel_xlsx=>column_write_xml( it_columns = lt_columns ). "" Closing tag CONCATENATE l_sheet_data `` INTO l_sheet_data. *************************************** "" Replace existing text xml_repleace_node( iv_tag_name = 'sheetData' ""#EC NOTEXT iv_repl_text = '_SHEET_DATA_' ). xml_repleace_node( iv_tag_name = 'cols' ""#EC NOTEXT iv_repl_text = '_NEW_COLUMNS_' ). lo_mc = xml_repleace_node( iv_tag_name = 'mergeCells' ""#EC NOTEXT iv_repl_text = '_MERGE_CELLS_' ). "" Change count IF lo_mc IS NOT INITIAL AND l_merge_cnt > 0. int_2_text l_merge_cnt l_str. lo_mc->set_attribute( name = 'count' value = l_str ). ""#EC NOTEXT ENDIF. "" Data validation IF mt_data_valid IS NOT INITIAL. lo_data_valid ?= mo_dom->find_from_name( 'dataValidation' ). ""#EC NOTEXT LOOP AT mt_data_valid REFERENCE INTO ls_area. CHECK lo_data_valid IS NOT INITIAL. "" Change replace_with_new( ls_area ). lv_address = zcl_xtt_excel_xlsx=>area_get_address( is_area = ls_area iv_no_bucks = abap_true ). lo_data_valid->set_attribute( name = 'sqref' value = lv_address ). ""#EC NOTEXT "" Next lo_data_valid ?= lo_data_valid->get_next( ). ENDLOOP. ENDIF. "" Transform to string zcl_eui_conv=>xml_to_str( EXPORTING io_doc = mo_dom IMPORTING ev_str = l_str ). "" Do replcement REPLACE FIRST OCCURRENCE OF '_SHEET_DATA_' IN l_str WITH l_sheet_data. ""#EC NOTEXT REPLACE FIRST OCCURRENCE OF '_NEW_COLUMNS_' IN l_str WITH lv_columns_text. ""#EC NOTEXT IF lo_mc IS NOT INITIAL AND l_merge_cnt > 0. REPLACE FIRST OCCURRENCE OF '_MERGE_CELLS_' IN l_str WITH l_merge_cells. ""#EC NOTEXT ENDIF. "" Replace XML file zcl_eui_conv=>xml_to_zip( io_zip = io_xlsx->mo_zip iv_name = mv_full_path iv_sdoc = l_str ). *************************************** LOOP AT io_xlsx->mt_defined_names REFERENCE INTO ls_defined_name. LOOP AT ls_defined_name->d_areas REFERENCE INTO ls_area WHERE a_sheet_name = mv_name. replace_with_new( ls_area ). ENDLOOP. ENDLOOP. "" List object LOOP AT mt_list_objects REFERENCE INTO ls_list_object. "" Get address GET REFERENCE OF ls_list_object->area INTO ls_area. "" Change cells replace_with_new( ls_area ). lv_address = zcl_xtt_excel_xlsx=>area_get_address( is_area = ls_area iv_no_bucks = abap_true ). CHECK lv_address IS NOT INITIAL. "" Change area lo_table = ls_list_object->dom->get_root_element( ). lo_table->set_attribute( name = 'ref' value = lv_address ). ""#EC NOTEXT "" Replace in zip zcl_eui_conv=>xml_to_zip( io_zip = io_xlsx->mo_zip iv_name = ls_list_object->arc_path io_xmldoc = ls_list_object->dom ). ENDLOOP. ENDMETHOD. ""save *--------------------------------------------------------------------* METHOD replace_with_new. DATA: lr_cell TYPE REF TO ts_ex_cell, lr_cell_ref TYPE REF TO ts_cell_ref, lv_tabix TYPE sytabix. LOOP AT ir_area->a_cells REFERENCE INTO lr_cell. lv_tabix = sy-tabix. "" OLD -> NEW READ TABLE mt_cell_ref REFERENCE INTO lr_cell_ref WITH TABLE KEY r = lr_cell->c_row c = lr_cell->c_col_ind. CHECK sy-subrc = 0. CASE lv_tabix. "" First occurrence WHEN 1. lr_cell->* = lr_cell_ref->beg->*. "" Last occurrence WHEN 2. lr_cell->* = lr_cell_ref->end->*. ENDCASE. ENDLOOP. "" Add additional cell to the eand IF lv_tabix = 1 AND lr_cell_ref IS NOT INITIAL. APPEND lr_cell_ref->end->* TO ir_area->a_cells. ENDIF. ENDMETHOD. *--------------------------------------------------------------------* METHOD merge. DATA: lo_new_replace_block TYPE REF TO zcl_xtt_replace_block, lr_field TYPE REF TO zcl_xtt_replace_block=>ts_field, lr_field2 TYPE REF TO zcl_xtt_replace_block=>ts_field, lt_cells_end LIKE ct_cells, lt_cells_mid LIKE ct_cells, lt_copy LIKE ct_cells, lt_cell_match TYPE tt_cell_match, lo_tree_handler TYPE REF TO lcl_tree_handler, lr_tree TYPE REF TO zcl_xtt_replace_block=>ts_tree, lv_by_column TYPE abap_bool. FIELD-SYMBOLS: TYPE ANY TABLE. * TYPE any. *************************************** "" merge-1 @see ME->MATCH_FOUND SET HANDLER match_found FOR io_replace_block ACTIVATION abap_true. "" Current cell LOOP AT ct_cells REFERENCE INTO ms_cell WHERE c_formula IS INITIAL. "" @see match_found io_replace_block->find_match( CHANGING cv_content = ms_cell->c_value ). ENDLOOP. "" Turn off event handler SET HANDLER match_found FOR io_replace_block ACTIVATION abap_false. *************************************** "" merge-2 Structures and objects LOOP AT io_replace_block->mt_fields REFERENCE INTO lr_field WHERE typ = zcl_xtt_replace_block=>mc_type_struct OR typ = zcl_xtt_replace_block=>mc_type_object. ""#EC CI_SORTSEQ "" Based on nested structure CREATE OBJECT lo_new_replace_block EXPORTING is_field = lr_field. "" Recursion if type is the same CHECK lr_field->typ = zcl_xtt_replace_block=>mc_type_struct OR lr_field->typ = zcl_xtt_replace_block=>mc_type_object. "" Recursion me->merge( EXPORTING io_replace_block = lo_new_replace_block CHANGING ct_cells = ct_cells ). ENDLOOP. *************************************** "" merge-3 Array types LOOP AT io_replace_block->mt_fields REFERENCE INTO lr_field WHERE typ = zcl_xtt_replace_block=>mc_type_table OR typ = zcl_xtt_replace_block=>mc_type_tree. ""#EC CI_SORTSEQ "" For columns READ TABLE mt_column_dir TRANSPORTING NO FIELDS WITH TABLE KEY table_line = lr_field->name. IF sy-subrc <> 0. lv_by_column = abap_false. ELSE. lv_by_column = abap_true. SORT ct_cells STABLE BY c_col_ind c_row. ENDIF. "" Find for replication cl_ex_sheet=>split_2_content( EXPORTING is_field = lr_field iv_by_column = lv_by_column CHANGING ct_cells = ct_cells "" Begin! ct_cells_mid = lt_cells_mid ct_cells_end = lt_cells_end ct_cell_match = lt_cell_match ). CASE lr_field->typ. ********************************************************************** WHEN zcl_xtt_replace_block=>mc_type_tree. lr_tree ?= lr_field->dref. CREATE OBJECT lo_tree_handler EXPORTING io_owner = me ir_tree = lr_tree iv_block_name = lr_field->name it_row_match = lt_cell_match. lo_tree_handler->add_tree_data( EXPORTING ir_tree = lr_tree CHANGING ct_cells = ct_cells ). ********************************************************************** WHEN zcl_xtt_replace_block=>mc_type_table. CHECK lt_cells_mid IS NOT INITIAL. "" Replicate middle ASSIGN lr_field->dref->* TO . "" Use copy CREATE DATA lr_field2. lr_field2->* = lr_field->*. LOOP AT REFERENCE INTO lr_field2->dref. ""ASSIGNING . lt_copy[] = lt_cells_mid[]. * "" Create descriptor * CREATE OBJECT lo_new_replace_block * EXPORTING * is_block = * iv_block_name = lr_field->name. * "" Create merge description * Create copy first * GET REFERENCE OF INTO lr_field->dref. CREATE OBJECT lo_new_replace_block EXPORTING is_field = lr_field2. "" Recursion me->merge( EXPORTING io_replace_block = lo_new_replace_block CHANGING ct_cells = lt_copy ). APPEND LINES OF lt_copy TO ct_cells. ENDLOOP. ENDCASE. "" Rest of the cells APPEND LINES OF lt_cells_end TO ct_cells. "" Set the order back IF lv_by_column = abap_true. SORT ct_cells STABLE BY c_row. ENDIF. ENDLOOP. ENDMETHOD. ""merge *--------------------------------------------------------------------* METHOD match_found. CONSTANTS: c_date_start TYPE d VALUE '18991230', c_time_start TYPE t VALUE '000000'. DATA: l_len TYPE i, l_value TYPE string, l_date TYPE float. FIELD-SYMBOLS: TYPE csequence, TYPE d, TYPE t. "" Just skip CHECK is_field->typ <> zcl_xtt_replace_block=>mc_type_tree. "" If the exactly in one cell and number (ms_cell->c_typ can be 's' string) l_len = strlen( ms_cell->c_value ). iv_pos_end = iv_pos_end + 1. IF iv_pos_beg = 0 AND l_len = iv_pos_end. CASE is_field->typ. "" integer and double(float) WHEN zcl_xtt_replace_block=>mc_type_integer OR zcl_xtt_replace_block=>mc_type_double. CLEAR ms_cell->c_type. "" Datetime Whole as a string like d + t WHEN zcl_xtt_replace_block=>mc_type_datetime. ASSIGN is_field->dref->* TO . "" Both parts ASSIGN (8) TO CASTING. ASSIGN +8(6) TO CASTING. CLEAR ms_cell->c_type. "" Date WHEN zcl_xtt_replace_block=>mc_type_date. ASSIGN is_field->dref->* TO CASTING. "" allow accept char(8) as date CLEAR ms_cell->c_type. "" Time WHEN zcl_xtt_replace_block=>mc_type_time. ASSIGN is_field->dref->* TO CASTING. "" allow accept char(6) as time CLEAR ms_cell->c_type. WHEN zcl_xtt_replace_block=>mc_type_boolean. ms_cell->c_type = 'b'. ENDCASE. DO 1 TIMES. "" Transform date to excel format as float CHECK IS ASSIGNED OR IS ASSIGNED. "" Date IF IS ASSIGNED AND IS NOT INITIAL. "" Number of days since l_date = - c_date_start. ENDIF. "" Time IF IS ASSIGNED AND IS NOT INITIAL. "" 0.5 half of a day l_date = l_date + ( - c_time_start ) / ( 60 * 60 * 24 ). ENDIF. "" Empty string IF l_date IS INITIAL. "" Empty string CREATE DATA is_field->dref TYPE string. is_field->typ = zcl_xtt_replace_block=>mc_type_string. ELSEIF l_date < 0. "" Use WRITE ... TO ELSE. GET REFERENCE OF l_date INTO is_field->dref. is_field->typ = zcl_xtt_replace_block=>mc_type_double. ENDIF. ENDDO. ENDIF. "" Try to get value as a string IF l_value IS INITIAL. l_value = zcl_xtt_replace_block=>get_as_string( is_field = is_field ). "" Use WRITE ... TO IF l_date < 0. ms_cell->c_style = ''. ms_cell->c_type = 's'. is_field->typ = zcl_xtt_replace_block=>mc_type_string. ENDIF. ENDIF. "" Create new value CONCATENATE ms_cell->c_value(iv_pos_beg) l_value ms_cell->c_value+iv_pos_end INTO ms_cell->c_value RESPECTING BLANKS. ENDMETHOD. ""match_found *--------------------------------------------------------------------* METHOD xml_repleace_node. DATA: lo_elem TYPE REF TO if_ixml_element. ro_elem = mo_dom->find_from_name( iv_tag_name ). CHECK ro_elem IS BOUND. "" Delete child elements DO. lo_elem ?= ro_elem->get_last_child( ). "" replace_child( ) instead ? IF_IXML_NODE IF lo_elem IS NOT BOUND. EXIT. ENDIF. ro_elem->remove_child( lo_elem ). ENDDO. "" Replace with text ro_elem->set_value( iv_repl_text ). ENDMETHOD. ""xml_repleace_node *--------------------------------------------------------------------* METHOD split_2_content. TYPES: BEGIN OF ts_pair, position TYPE i, "" Excel row Or column array_ind TYPE sytabix, "" Index in ct_cells[] END OF ts_pair, tt_pair TYPE SORTED TABLE OF ts_pair WITH UNIQUE KEY position. DATA: lv_ind_beg TYPE i, lv_ind_end TYPE i, lv_ind_end_1 TYPE i, lv_find_str TYPE string, ls_cell TYPE REF TO ts_ex_cell, lt_row_begs TYPE tt_pair, lt_row_ends TYPE tt_pair, lv_row_first TYPE i, lv_row_last TYPE i, ls_cur_pair TYPE ts_pair, ls_pair_ref TYPE REF TO ts_pair, lv_offset TYPE i, lv_length TYPE i, lv_text TYPE string, lt_row_off TYPE zcl_xtt_replace_block=>tt_row_offset, ls_row_off TYPE zcl_xtt_replace_block=>ts_row_offset, lv_from TYPE sytabix, ls_row_match TYPE ts_cell_match. FIELD-SYMBOLS: TYPE zcl_xtt_replace_block=>ts_row_offset, TYPE zcl_xtt_replace_block=>ts_row_offset. "" All positions CLEAR: ct_cell_match, ct_cells_end, ct_cells_mid. "" CONCATENATE zcl_xtt_replace_block=>mc_char_block_begin iv_fld_name INTO lv_find_str. CONCATENATE `\\{` is_field->name `\\b[^}]*\\}` INTO lv_find_str. "" Find matches LOOP AT ct_cells REFERENCE INTO ls_cell. "" Current values ls_cur_pair-array_ind = sy-tabix. "" What field to use IF iv_by_column = abap_true. ls_cur_pair-position = ls_cell->c_col_ind. "" ls_cur_pair-position + ls_cell->c_col_dx. ELSE. ls_cur_pair-position = ls_cell->c_row. "" ls_cur_pair-position + ls_cell->c_row_dx. ENDIF. "" Find row range READ TABLE lt_row_begs WITH TABLE KEY position = ls_cur_pair-position TRANSPORTING NO FIELDS. IF sy-subrc <> 0. INSERT ls_cur_pair INTO TABLE lt_row_begs. ENDIF. "" Make range bigger READ TABLE lt_row_ends REFERENCE INTO ls_pair_ref WITH TABLE KEY position = ls_cur_pair-position. IF sy-subrc = 0. ls_pair_ref->array_ind = ls_cur_pair-array_ind. ELSE. INSERT ls_cur_pair INTO TABLE lt_row_ends. ENDIF. "" Rows range FIND FIRST OCCURRENCE OF REGEX lv_find_str IN ls_cell->c_value MATCH OFFSET lv_offset MATCH LENGTH lv_length. CHECK sy-subrc = 0. lv_row_last = ls_cur_pair-position. "" Set 1 time only IF lv_row_first IS INITIAL. lv_row_first = lv_row_last. ENDIF. *************************** "" TREE begin CHECK is_field->typ = zcl_xtt_replace_block=>mc_type_tree. "" Delete surrounding {} lv_offset = lv_offset + 1. lv_length = lv_length - 2. lv_text = ls_cell->c_value+lv_offset(lv_length). "" Read from texts zcl_xtt_replace_block=>tree_detect_options( EXPORTING iv_text = lv_text iv_pos = ls_cur_pair-position CHANGING cs_row_offset = ls_row_off ct_row_offset = lt_row_off ). *************************** "" TREE end ENDLOOP. "" Skip IF lv_row_first IS INITIAL AND lv_row_last IS INITIAL. RETURN. ENDIF. "" Oops not found IF lv_row_first IS INITIAL OR lv_row_last IS INITIAL. MESSAGE x001(zsy_xtt). ENDIF. *************************** "" TREE begin Check overlaps LOOP AT lt_row_off ASSIGNING . lv_from = sy-tabix + 1. LOOP AT lt_row_off ASSIGNING FROM lv_from WHERE ( first <= -last AND first >= -first ) OR ( last <= -last AND last >= -first ). MESSAGE x001(zsy_xtt). ENDLOOP. ENDLOOP. "" And add LOOP AT lt_row_off ASSIGNING . CLEAR ls_row_match. READ TABLE lt_row_begs REFERENCE INTO ls_pair_ref WITH TABLE KEY position = -first. lv_ind_beg = ls_pair_ref->array_ind. READ TABLE lt_row_ends REFERENCE INTO ls_pair_ref WITH TABLE KEY position = -last. lv_ind_end = ls_pair_ref->array_ind. "" And add MOVE-CORRESPONDING TO ls_row_match. APPEND LINES OF ct_cells FROM lv_ind_beg TO lv_ind_end TO ls_row_match-cells. INSERT ls_row_match INTO TABLE ct_cell_match. ENDLOOP. *************************** "" TREE end "" Detect middle READ TABLE lt_row_begs REFERENCE INTO ls_pair_ref WITH TABLE KEY position = lv_row_first. lv_ind_beg = ls_pair_ref->array_ind. READ TABLE lt_row_ends REFERENCE INTO ls_pair_ref WITH TABLE KEY position = lv_row_last. lv_ind_end = ls_pair_ref->array_ind. "" End lv_ind_end_1 = lv_ind_end + 1. APPEND LINES OF ct_cells FROM lv_ind_end_1 TO ct_cells_end. "" Middle APPEND LINES OF ct_cells FROM lv_ind_beg TO lv_ind_end TO ct_cells_mid. "" Begin! DELETE ct_cells FROM lv_ind_beg. ENDMETHOD. ""split_2_content *--------------------------------------------------------------------* ENDCLASS. ""cl_ex_sheet IMPLEMENTATION ********************************************************************** ********************************************************************** CLASS lcl_tree_handler IMPLEMENTATION. METHOD constructor. mo_owner = io_owner. mv_block_name = iv_block_name. mt_row_match = it_row_match. "" If there are dynamic levels zcl_xtt_replace_block=>tree_initialize( EXPORTING ir_tree = ir_tree IMPORTING ev_program = mv_check_prog CHANGING ct_row_match = mt_row_match ). ENDMETHOD. METHOD add_tree_data. DATA: lo_replace_block TYPE REF TO zcl_xtt_replace_block, lr_found_match TYPE REF TO ts_cell_match, lv_top TYPE abap_bool, lt_row_top TYPE tt_ex_cell, lt_row_bottom TYPE tt_ex_cell, lr_tree_attr TYPE REF TO zcl_xtt_replace_block=>ts_tree_attr, lr_tree TYPE REF TO zcl_xtt_replace_block=>ts_tree, ls_cell TYPE REF TO ts_ex_cell, ls_row TYPE REF TO ts_ex_row, ls_column TYPE REF TO ts_ex_column, lv_templ_lev_cnt TYPE i. FIELD-SYMBOLS: TYPE any, TYPE tt_ex_cell. ASSIGN ir_tree->data->* TO . "" Create merge description CREATE OBJECT lo_replace_block EXPORTING is_block = iv_block_name = mv_block_name. "" Check amount of level's templates lv_templ_lev_cnt = lines( mt_row_match ). DO 3 TIMES. CASE sy-index. WHEN 1. ASSIGN lt_row_top TO . lv_top = abap_true. WHEN 2. ASSIGN lt_row_bottom TO . lv_top = abap_false. WHEN 3. "" 3-d try CHECK lt_row_top IS INITIAL AND lt_row_bottom IS INITIAL. ASSIGN lt_row_top TO . lv_top = abap_undefined. ENDCASE. "" Find match lr_found_match ?= zcl_xtt_replace_block=>tree_find_match( ir_tree = ir_tree iv_block_name = mv_block_name iv_top = lv_top iv_check_prog = mv_check_prog it_row_match = mt_row_match ). CHECK lr_found_match IS NOT INITIAL. "" Merge with data [] = lr_found_match->cells[]. "" For new rows only IF lv_templ_lev_cnt = 1. LOOP AT REFERENCE INTO ls_cell. "" Rows DO 1 TIMES. "" WHERE c_row_dx IS NOT INITIAL. ? "" Have outline ot not READ TABLE mo_owner->mt_rows WITH TABLE KEY r = ls_cell->c_row REFERENCE INTO ls_row. CHECK sy-subrc = 0 AND ls_row->outlinelevel IS NOT INITIAL. ls_cell->c_row_outline = ir_tree->level. ls_row->outline_skip = abap_true. ENDDO. "" Columns DO 1 TIMES. "" Have outline ot not READ TABLE mo_owner->mt_columns WITH TABLE KEY min = ls_cell->c_col_ind REFERENCE INTO ls_column. CHECK sy-subrc = 0 AND ls_column->outlinelevel IS NOT INITIAL. ls_cell->c_column_outline = ir_tree->level. ls_column->outline_skip = abap_true. ENDDO. ENDLOOP. ENDIF. mo_owner->merge( EXPORTING io_replace_block = lo_replace_block CHANGING ct_cells = ). ENDDO. "" row before APPEND LINES OF lt_row_top TO ct_cells. "" children rows LOOP AT ir_tree->sub_nodes REFERENCE INTO lr_tree_attr. lr_tree ?= lr_tree_attr->attr. add_tree_data( EXPORTING ir_tree = lr_tree CHANGING ct_cells = ct_cells ). ENDLOOP. "" row after APPEND LINES OF lt_row_bottom TO ct_cells. ENDMETHOD. ENDCLASS. ********************************************************************** ********************************************************************** ",8222,False,1624.915903378647,median "//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2003-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package flexlib.baseClasses { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.geom.Rectangle; import flash.ui.Keyboard; import flash.utils.getTimer; import mx.automation.IAutomationObject; import mx.controls.Button; import mx.core.ClassFactory; import mx.core.ComponentDescriptor; import mx.core.Container; import mx.core.ContainerCreationPolicy; import mx.core.EdgeMetrics; import mx.core.FlexVersion; import mx.core.IDataRenderer; import mx.core.IFactory; import mx.core.IInvalidating; import mx.core.IUIComponent; import mx.core.ScrollPolicy; import mx.core.UIComponent; import mx.core.mx_internal; import mx.effects.Effect; import mx.effects.Tween; import mx.events.ChildExistenceChangedEvent; import mx.events.FlexEvent; import mx.events.IndexChangedEvent; import mx.managers.IFocusManagerComponent; import mx.managers.IHistoryManagerClient; import flexlib.containers.accordionClasses.AccordionHeader; FLEX_TARGET_VERSION::flex4 { import mx.geom.RoundedRectangle; } FLEX_TARGET_VERSION::flex3 { import mx.graphics.RoundedRectangle; } import mx.managers.HistoryManager; import mx.styles.StyleManager; import mx.styles.CSSStyleDeclaration; import mx.styles.StyleProxy; import mx.styles.IStyleManager2; import mx.core.FlexGlobals; use namespace mx_internal; [RequiresDataBinding(true)] //[IconFile(""Accordion.png"")] /** * Dispatched when the selected child container changes. * * @eventType mx.events.IndexChangedEvent.CHANGE * @helpid 3012 * @tiptext change event */ [Event(name=""change"", type=""mx.events.IndexChangedEvent"")] //-------------------------------------- // Styles //-------------------------------------- /** * Specifies the alpha transparency values used for the background fill of components. * You should set this to an Array of either two or four numbers. * Elements 0 and 1 specify the start and end values for * an alpha gradient. * If elements 2 and 3 exist, they are used instead of elements 0 and 1 * when the component is in a mouse-over state. * The global default value is [ 0.60, 0.40, 0.75, 0.65 ]. * Some components, such as the ApplicationControlBar container, * have a different default value. For the ApplicationControlBar container, * the default value is [ 0.0, 0.0 ]. */ [Style(name=""fillAlphas"", type=""Array"", arrayType=""Number"", inherit=""no"", deprecatedReplacement=""headerStyleName"", deprecatedSince=""3.0"")] /** * Specifies the colors used to tint the background fill of the component. * You should set this to an Array of either two or four uint values * that specify RGB colors. * Elements 0 and 1 specify the start and end values for * a color gradient. * If elements 2 and 3 exist, they are used instead of elements 0 and 1 * when the component is in a mouse-over state. * For a flat-looking control, set the same color for elements 0 and 1 * and for elements 2 and 3, * The default value is * [ 0xFFFFFF, 0xCCCCCC, 0xFFFFFF, 0xEEEEEE ]. *

Some components, such as the ApplicationControlBar container, * have a different default value. For the ApplicationControlBar container, * the default value is [ 0xFFFFFF, 0xFFFFFF ].

*/ [Style(name=""fillColors"", type=""Array"", arrayType=""uint"", format=""Color"", inherit=""no"", deprecatedReplacement=""headerStyleName"", deprecatedSince=""3.0"")] /** * Specifies the alpha transparency value of the focus skin. * * @default 0.4 */ [Style(name=""focusAlpha"", type=""Number"", inherit=""no"", deprecatedReplacement=""headerStyleName"", deprecatedSince=""3.0"")] /** * Specifies which corners of the focus rectangle should be rounded. * This value is a space-separated String that can contain any * combination of ""tl"", ""tr"", ""bl"" * and ""br"". * For example, to specify that the right side corners should be rounded, * but the left side corners should be square, use ""tr br"". * The cornerRadius style property specifies * the radius of the rounded corners. * The default value depends on the component class; if not overridden for * the class, default value is ""tl tr bl br"". * */ [Style(name=""focusRoundedCorners"", type=""String"", inherit=""no"", deprecatedReplacement=""headerStyleName"", deprecatedSince=""3.0"")] /** * Skin used to draw the focus rectangle. * * @default mx.skins.halo.HaloFocusRect */ [Style(name=""focusSkin"", type=""Class"", inherit=""no"", deprecatedReplacement=""headerStyleName"", deprecatedSince=""3.0"")] /** * Thickness, in pixels, of the focus rectangle outline. * * @default 2 */ [Style(name=""focusThickness"", type=""Number"", format=""Length"", inherit=""no"", deprecatedReplacement=""headerStyleName"", deprecatedSince=""3.0"")] /** * Name of the CSS style declaration that specifies styles for the accordion * headers (tabs). * *

You can use this class selector to set the values of all the style properties * of the AccordionHeader class, including fillAlphas, fillColors, * focusAlpha, focusRounderCorners, * focusSkin, focusThickness, and selectedFillColors.

*/ [Style(name=""headerStyleName"", type=""String"", inherit=""no"")] /** * Number of pixels between children in the horizontal direction. * The default value is 8. */ [Style(name=""horizontalGap"", type=""Number"", format=""Length"", inherit=""no"")] /** * Height of each accordion header, in pixels. * The default value is automatically calculated based on the font styles for * the header. */ [Style(name=""headerHeight"", type=""Number"", format=""Length"", inherit=""no"")] /** * Duration, in milliseconds, of the animation from one child to another. * The default value is 250. */ [Style(name=""openDuration"", type=""Number"", format=""Time"", inherit=""no"")] /** * Tweening function used by the animation from one child to another. */ [Style(name=""openEasingFunction"", type=""Function"", inherit=""no"")] /** * Number of pixels between the container's bottom border and its content area. * The default value is -1, so the bottom border of the last header * overlaps the Accordion container's bottom border. */ [Style(name=""paddingBottom"", type=""Number"", format=""Length"", inherit=""no"")] /** * Number of pixels between the container's top border and its content area. * The default value is -1, so the top border of the first header * overlaps the Accordion container's top border. */ [Style(name=""paddingTop"", type=""Number"", format=""Length"", inherit=""no"")] /** * The two colors used to tint the background of the component * when in its selected state. * Pass the same color for both values for ""flat"" looking control. * The default value is undefined, which means the colors * are derived from themeColor. */ [Style(name=""selectedFillColors"", type=""Array"", arrayType=""uint"", format=""Color"", inherit=""no"", deprecatedReplacement=""headerStyleName"", deprecatedSince=""3.0"")] /** * Color of header text when rolled over. * The default value is 0x2B333C. */ [Style(name=""textRollOverColor"", type=""uint"", format=""Color"", inherit=""yes"")] /** * Color of selected text. * The default value is 0x2B333C. */ [Style(name=""textSelectedColor"", type=""uint"", format=""Color"", inherit=""yes"")] /** * Number of pixels between children in the vertical direction. * The default value is -1, so the top and bottom borders * of adjacent headers overlap. */ [Style(name=""verticalGap"", type=""Number"", format=""Length"", inherit=""no"")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name=""autoLayout"", kind=""property"")] [Exclude(name=""clipContent"", kind=""property"")] [Exclude(name=""defaultButton"", kind=""property"")] [Exclude(name=""horizontalLineScrollSize"", kind=""property"")] [Exclude(name=""horizontalPageScrollSize"", kind=""property"")] [Exclude(name=""horizontalScrollBar"", kind=""property"")] [Exclude(name=""horizontalScrollPolicy"", kind=""property"")] [Exclude(name=""horizontalScrollPosition"", kind=""property"")] [Exclude(name=""maxHorizontalScrollPosition"", kind=""property"")] [Exclude(name=""maxVerticalScrollPosition"", kind=""property"")] [Exclude(name=""verticalLineScrollSize"", kind=""property"")] [Exclude(name=""verticalPageScrollSize"", kind=""property"")] [Exclude(name=""verticalScrollBar"", kind=""property"")] [Exclude(name=""verticalScrollPolicy"", kind=""property"")] [Exclude(name=""verticalScrollPosition"", kind=""property"")] [Exclude(name=""scroll"", kind=""event"")] /* [Exclude(name=""focusBlendMode"", kind=""style"")] [Exclude(name=""focusSkin"", kind=""style"")] [Exclude(name=""focusThickness"", kind=""style"")] */ [Exclude(name=""horizontalScrollBarStyleName"", kind=""style"")] [Exclude(name=""verticalScrollBarStyleName"", kind=""style"")] //-------------------------------------- // Other metadata //-------------------------------------- [DefaultBindingProperty(source=""selectedIndex"", destination=""selectedIndex"")] [DefaultTriggerEvent(""change"")] /** * AccordionBase is a copy/paste version of the original Accordion class in the Flex framework. * *

The only modifications made to this class were to change some properties and * methods from private to protected so we can override them in a subclass.

* *

An Accordion navigator container has a collection of child containers, * but only one of them at a time is visible. * It creates and manages navigator buttons (accordion headers), which you use * to navigate between the children. * There is one navigator button associated with each child container, * and each navigator button belongs to the Accordion container, not to the child. * When the user clicks a navigator button, the associated child container * is displayed. * The transition to the new child uses an animation to make it clear to * the user that one child is disappearing and a different one is appearing.

* *

The Accordion container does not extend the ViewStack container, * but it implements all the properties, methods, styles, and events * of the ViewStack container, such as selectedIndex * and selectedChild.

* *

An Accordion container has the following default sizing characteristics:

* * * * * * * * * * * * * * * * * * * * * *
CharacteristicDescription
Default sizeThe width and height of the currently active child.
Container resizing rulesAccordion containers are only sized once to fit the size of the first child container by default. * They do not resize when you navigate to other child containers by default. * To force Accordion containers to resize when you navigate to a different child container, * set the resizeToContent property to true.
Child sizing rulesChildren are sized to their default size. The child is clipped if it is larger than the Accordion container. * If the child is smaller than the Accordion container, it is aligned to the upper-left corner of the * Accordion container.
Default padding-1 pixel for the top, bottom, left, and right values.
* * @mxml * *

The <mx:Accordion> tag inherits all of the * tag attributes of its superclass, with the exception of scrolling-related * attributes, and adds the following tag attributes:

* *
   *  <mx:Accordion
   *    Properties
   *    headerRenderer=""IFactory""
   *    historyManagementEnabled=""true|false""
   *    resizeToContent=""false|true""
   *    selectedIndex=""undefined""
   *
   *    Styles
   *    headerHeight=""depends on header font styles""
   *    headerStyleName=""No default""
   *    horizontalGap=""8""
   *    openDuration=""250""
   *    openEasingFunction=""undefined""
   *    paddingBottom=""-1""
   *    paddingTop=""-1""
   *    textRollOverColor=""0xB333C""
   *    textSelectedColor=""0xB333C""
   *    verticalGap=""-1""
   *
   *    Events
   *    change=""No default""
   *    >
   *      ...
   *      child tags
   *      ...
   *  </mx:Accordion>
   *  
* * * * @see mx.containers.accordionClasses.AccordionHeader * * @tiptext Accordion allows for navigation between different child views * @helpid 3013 */ public class AccordionBase extends Container implements IHistoryManagerClient, IFocusManagerComponent { //include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private * Base for all header names (_header0 - _headerN). */ private static const HEADER_NAME_BASE:String = ""_header""; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. */ public function AccordionBase() { super(); headerRenderer = new ClassFactory(AccordionHeader); // Most views can't take focus, but an accordion can. // However, it draws its own focus indicator on the // header for the currently selected child view. // Container() has set tabEnabled false, so we // have to set it back to true. tabEnabled = true; // Accordion always clips content, it just handles it by itself super.clipContent = false; addEventListener(ChildExistenceChangedEvent.CHILD_ADD, childAddHandler); addEventListener(ChildExistenceChangedEvent.CHILD_REMOVE, childRemoveHandler); showInAutomationHierarchy = true; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Is the accordian currently sliding between views? */ protected var bSliding:Boolean = false; /** * @private */ private var initialSelectedIndex:int = -1; /** * @private * If true, call HistoryManager.save() when setting currentIndex. */ private var bSaveState:Boolean = false; /** * @private */ private var bInLoadState:Boolean = false; /** * @private */ private var firstTime:Boolean = true; /** * @private */ protected var showFocusIndicator:Boolean = false; /** * @private * Cached tween properties to speed up tweening calculations. */ protected var tweenViewMetrics:EdgeMetrics; protected var tweenContentWidth:Number; protected var tweenContentHeight:Number; protected var tweenOldSelectedIndex:int; protected var tweenNewSelectedIndex:int; protected var tween:Tween; /** * @private * We'll measure ourselves once and then store the results here * for the lifetime of the ViewStack. */ protected var accMinWidth:Number; protected var accMinHeight:Number; protected var accPreferredWidth:Number; protected var accPreferredHeight:Number; /** * @private * When a child is added or removed, this flag is set true * and it causes a re-measure. */ private var childAddedOrRemoved:Boolean = false; /** * @private * Remember which child has an overlay mask, if any. */ private var overlayChild:IUIComponent; /** * @private * Keep track of the overlay's targetArea */ private var overlayTargetArea:RoundedRectangle; /** * @private */ protected var layoutStyleChanged:Boolean = false; /** * @private */ protected var currentDissolveEffect:Effect; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // autoLayout //---------------------------------- // Don't allow user to set autoLayout because // there are problems if deferred instantiation // runs at the same time as an effect. (Bug 79174) [Inspectable(environment=""none"")] /** * @private */ override public function get autoLayout():Boolean { return true; } /** * @private */ override public function set autoLayout(value:Boolean):void { } //---------------------------------- // baselinePosition //---------------------------------- /** * @private * The baselinePosition of an Accordion is calculated * for the label of the first header. * If there are no children, a child is temporarily added * to do the computation. */ override public function get baselinePosition():Number { if (FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0) return super.baselinePosition; if (!validateBaselinePosition()) return NaN; var isEmpty:Boolean = numChildren == 0; if (isEmpty) { var child0:Container = new Container(); addChild(child0); validateNow(); } var header0:Button = getHeaderAt(0); var result:Number = header0.y + header0.baselinePosition; if (isEmpty) { removeChildAt(0); validateNow(); } return result; } //---------------------------------- // clipContent //---------------------------------- // We still need to ensure the clip mask is *never* created for an // Accordion. [Inspectable(environment=""none"")] /** * @private */ override public function get clipContent():Boolean { return true; // Accordion does clip, it just does it itself } /** * @private */ override public function set clipContent(value:Boolean):void { } //---------------------------------- // horizontalScrollPolicy //---------------------------------- [Inspectable(environment=""none"")] /** * @private */ override public function get horizontalScrollPolicy():String { return ScrollPolicy.OFF; } /** * @private */ override public function set horizontalScrollPolicy(value:String):void { } //---------------------------------- // verticalScrollPolicy //---------------------------------- [Inspectable(environment=""none"")] /** * @private */ override public function get verticalScrollPolicy():String { return ScrollPolicy.OFF; } /** * @private */ override public function set verticalScrollPolicy(value:String):void { } //-------------------------------------------------------------------------- // // Public properties // //-------------------------------------------------------------------------- /** * @private */ private var _focusedIndex:int = -1; /** * @private */ mx_internal function get focusedIndex():int { return _focusedIndex; } //---------------------------------- // contentHeight //---------------------------------- /** * The height of the area, in pixels, in which content is displayed. * You can override this getter if your content * does not occupy the entire area of the container. */ protected function get contentHeight():Number { // Start with the height of the entire accordion. var contentHeight:Number = unscaledHeight; // Subtract the heights of the top and bottom borders. var vm:EdgeMetrics = viewMetricsAndPadding; contentHeight -= vm.top + vm.bottom; // Subtract the header heights. var verticalGap:Number = getStyle(""verticalGap""); var n:int = numChildren; for (var i:int = 0; i < n; i++) { contentHeight -= getHeaderAt(i).height; if (i > 0) contentHeight -= verticalGap; } return contentHeight; } //---------------------------------- // contentWidth //---------------------------------- /** * The width of the area, in pixels, in which content is displayed. * You can override this getter if your content * does not occupy the entire area of the container. */ protected function get contentWidth():Number { // Start with the width of the entire accordion. var contentWidth:Number = unscaledWidth; // Subtract the widths of the left and right borders. var vm:EdgeMetrics = viewMetricsAndPadding; contentWidth -= vm.left + vm.right; contentWidth -= getStyle(""paddingLeft"") + getStyle(""paddingRight""); return contentWidth; } //---------------------------------- // headerRenderer //---------------------------------- /** * @private * Storage for the headerRenderer property. */ private var _headerRenderer:IFactory; [Bindable(""headerRendererChanged"")] /** * A factory used to create the navigation buttons for each child. * The default value is a factory which creates a * mx.containers.accordionClasses.AccordionHeader. The * created object must be a subclass of Button and implement the * mx.core.IDataRenderer interface. The data * property is set to the content associated with the header. * * @see mx.containers.accordionClasses.AccordionHeader */ public function get headerRenderer():IFactory { return _headerRenderer; } /** * @private */ public function set headerRenderer(value:IFactory):void { _headerRenderer = value; dispatchEvent(new Event(""headerRendererChanged"")); } //---------------------------------- // historyManagementEnabled //---------------------------------- /** * @private * Storage for historyManagementEnabled property. */ private var _historyManagementEnabled:Boolean = true; /** * @private */ private var historyManagementEnabledChanged:Boolean = false; [Inspectable(defaultValue=""true"")] /** * If set to true, this property enables history management * within this Accordion container. * As the user navigates from one child to another, * the browser remembers which children were visited. * The user can then click the browser's Back and Forward buttons * to move through this navigation history. * * @default true * * @see mx.managers.HistoryManager */ public function get historyManagementEnabled():Boolean { return _historyManagementEnabled; } /** * @private */ public function set historyManagementEnabled(value:Boolean):void { if (value != _historyManagementEnabled) { _historyManagementEnabled = value; historyManagementEnabledChanged = true; invalidateProperties(); } } //---------------------------------- // resizeToContent //---------------------------------- /** * @private * Storage for the resizeToContent property. */ protected var _resizeToContent:Boolean = false; [Inspectable(defaultValue=""false"")] /** * If set to true, this Accordion automatically resizes to * the size of its current child. * * @default false */ public function get resizeToContent():Boolean { return _resizeToContent; } /** * @private */ public function set resizeToContent(value:Boolean):void { if (value != _resizeToContent) { _resizeToContent = value; if (value) invalidateSize(); } } //---------------------------------- // selectedChild //---------------------------------- [Bindable(""valueCommit"")] /** * A reference to the currently visible child container. * The default value is a reference to the first child. * If there are no children, this property is null. * *

Note: You can only set this property in an ActionScript statement, * not in MXML.

* * @tiptext Specifies the child view that is currently displayed * @helpid 3401 */ public function get selectedChild():Container { if (selectedIndex == -1) return null; return Container(getChildAt(selectedIndex)); } /** * @private */ public function set selectedChild(value:Container):void { var newIndex:int = getChildIndex(DisplayObject(value)); if (newIndex >= 0 && newIndex < numChildren) selectedIndex = newIndex; } //---------------------------------- // selectedIndex //---------------------------------- /** * @private * Storage for the selectedIndex and selectedChild properties. */ private var _selectedIndex:int = -1; /** * @private */ private var proposedSelectedIndex:int = -1; [Bindable(""valueCommit"")] [Inspectable(category=""General"", defaultValue=""0"")] /** * The zero-based index of the currently visible child container. * Child indexes are in the range 0, 1, 2, ..., n - 1, where n is the number * of children. * The default value is 0, corresponding to the first child. * If there are no children, this property is -1. * * @default 0 * * @tiptext Specifies the index of the child view that is currently displayed * @helpid 3402 */ public function get selectedIndex():int { if (proposedSelectedIndex != -1) return proposedSelectedIndex; return _selectedIndex; } /** * @private */ public function set selectedIndex(value:int):void { // Bail if new index isn't a number. if (value == -1) return; // Bail if the index isn't changing. if (value == _selectedIndex) return; // Propose the specified value as the new value for selectedIndex. // It gets applied later when commitProperties() calls commitSelectedIndex(). // The proposed value can be ""out of range"", because the children // may not have been created yet, so the range check is handled // in commitSelectedIndex(), not here. Other calls to this setter // can change the proposed index before it is committed. Also, // childAddHandler() proposes a value of 0 when it creates the first // child, if no value has yet been proposed. proposedSelectedIndex = value; invalidateProperties(); // Set a flag which will cause the History Manager to save state // the next time measure() is called. if (historyManagementEnabled && _selectedIndex != -1 && !bInLoadState) bSaveState = true; dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ override public function createComponentsFromDescriptors( recurse:Boolean=true):void { // The easiest way to handle the ContainerCreationPolicy.ALL policy is to let // Container's implementation of createComponents handle it. if (actualCreationPolicy == ContainerCreationPolicy.ALL) { super.createComponentsFromDescriptors(); return; } // If the policy is ContainerCreationPolicy.AUTO, Accordion instantiates its children // immediately, but not any grandchildren. The children of // the selected child will get created in instantiateSelectedChild(). // Why not create the grandchildren of the selected child by calling // createComponentFromDescriptor(childDescriptors[i], i == selectedIndex); // in the loop below? Because one of this Accordion's childDescriptors // may be for a Repeater, in which case the following loop over the // childDescriptors is not the same as a loop over the children. // In particular, selectedIndex is supposed to specify the nth // child, not the nth childDescriptor, and the 2nd parameter of // createComponentFromDescriptor() should make the recursion happen // on the nth child, not the nth childDescriptor. var numChildrenBefore:int = numChildren; if (childDescriptors) { var n:int = childDescriptors.length; for (var i:int = 0; i < n; i++) { var descriptor:ComponentDescriptor = ComponentDescriptor(childDescriptors[i]); createComponentFromDescriptor(descriptor, false); } } numChildrenCreated = numChildren - numChildrenBefore; processedDescriptors = true; } /** * @private */ override public function setChildIndex(child:DisplayObject, newIndex:int):void { var oldIndex:int = getChildIndex(child); // Check boundary conditions first if (oldIndex == -1 || newIndex < 0) return; var nChildren:int = numChildren; if (newIndex >= nChildren) newIndex = nChildren - 1; // Next, check for no move if (newIndex == oldIndex) return; // De-select the old selected index header var oldSelectedHeader:Button = getHeaderAt(selectedIndex); if (oldSelectedHeader) { oldSelectedHeader.selected = false; drawHeaderFocus(_focusedIndex, false); } // Adjust the depths and _childN references of the affected children. super.setChildIndex(child, newIndex); // Shuffle the headers shuffleHeaders(oldIndex, newIndex); // Select the new selected index header var newSelectedHeader:Button = getHeaderAt(selectedIndex); if (newSelectedHeader) { newSelectedHeader.selected = true; drawHeaderFocus(_focusedIndex, showFocusIndicator); } // Make sure the new selected child is instantiated instantiateChild(selectedChild); } /** * @private */ private function shuffleHeaders(oldIndex:int, newIndex:int):void { var i:int; // Adjust the _headerN references of the affected headers. // Note: Algorithm is the same as Container.setChildIndex(). var header:Button = getHeaderAt(oldIndex); if (newIndex < oldIndex) { for (i = oldIndex; i > newIndex; i--) { getHeaderAt(i - 1).name = HEADER_NAME_BASE + i; } } else { for (i = oldIndex; i < newIndex; i++) { getHeaderAt(i + 1).name = HEADER_NAME_BASE + i; } } header.name = HEADER_NAME_BASE + newIndex; } /** * @private */ override protected function commitProperties():void { super.commitProperties(); if (historyManagementEnabledChanged) { if (historyManagementEnabled) HistoryManager.register(this); else HistoryManager.unregister(this); historyManagementEnabledChanged = false; } commitSelectedIndex(); if (firstTime) { firstTime = false; // Add ""addedToStage"" and ""removedFromStage"" listeners so we can // register/un-register from the history manager when this component // is added or removed from the display list. addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler, false, 0, true); addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler, false, 0, true); } } /** * @private */ override protected function measure():void { super.measure(); /* measure() gets implemented by a subclass, either HAccordion or VAccordion */ /** var minWidth:Number = 0; var minHeight:Number = 0; var preferredWidth:Number = 0; var preferredHeight:Number = 0; var paddingLeft:Number = getStyle(""paddingLeft""); var paddingRight:Number = getStyle(""paddingRight""); var headerHeight:Number = getHeaderHeight(); // In general, we only measure once and thereafter use cached values. // There are three exceptions: when resizeToContent is true, // when a layout style like headerHeight changes, // and when a child is added or removed. // // We need to copy the cached values into the measured fields // again to handle the case where scaleX or scaleY is not 1.0. // When the Accordion is zoomed, code in UIComponent.measureSizes // scales the measuredWidth/Height values every time that // measureSizes is called. (bug 100749) if (accPreferredWidth && !_resizeToContent && !layoutStyleChanged && !childAddedOrRemoved) { measuredMinWidth = accMinWidth; measuredMinHeight = accMinHeight; measuredWidth = accPreferredWidth; measuredHeight = accPreferredHeight; return; } layoutStyleChanged = false; childAddedOrRemoved = false; var n:int = numChildren; for (var i:int = 0; i < n; i++) { var button:Button = getHeaderAt(i); var child:IUIComponent = IUIComponent(getChildAt(i)); minWidth = Math.max(minWidth, button.minWidth); minHeight += headerHeight; preferredWidth = Math.max(preferredWidth, minWidth); preferredHeight += headerHeight; // The headers preferredWidth is messing up the accordion measurement. This may not // be needed anyway because we're still using the headers minWidth to determine our overall // minWidth. if (i == selectedIndex) { preferredWidth = Math.max(preferredWidth, child.getExplicitOrMeasuredWidth()); preferredHeight += child.getExplicitOrMeasuredHeight(); minWidth = Math.max(minWidth, child.minWidth); minHeight += child.minHeight; } } // Add space for borders and margins var vm:EdgeMetrics = viewMetricsAndPadding; var widthPadding:Number = vm.left + vm.right; var heightPadding:Number = vm.top + vm.bottom; // Need to adjust the widthPadding if paddingLeft and paddingRight are negative numbers // (see explanation in updateDisplayList()) if (paddingLeft < 0) widthPadding -= paddingLeft; if (paddingRight < 0) widthPadding -= paddingRight; minWidth += widthPadding; preferredWidth += widthPadding; minHeight += heightPadding; preferredHeight += heightPadding; measuredMinWidth = minWidth; measuredMinHeight = minHeight; measuredWidth = preferredWidth; measuredHeight = preferredHeight; // If we're called before instantiateSelectedChild, then bail. // We'll be called again later (instantiateSelectedChild calls // invalidateSize), and we don't want to load values into the // cache until we're fully initialized. (bug 102639) // This check was moved from the beginning of this function to // here to fix bugs 103665/104213. if (selectedChild && Container(selectedChild).numChildrenCreated == -1) return; // Don't remember sizes if we don't have any children if (numChildren == 0) return; accMinWidth = minWidth; accMinHeight = minHeight; accPreferredWidth = preferredWidth; accPreferredHeight = preferredHeight; **/ } /** * @private * Arranges the layout of the accordion contents. * * @tiptext Arranges the layout of the Accordion's contents * @helpid 3017 */ override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); /* updateDisplayList() gets implemented by a subclass, either HAccordion or VAccordion */ /** // Don't do layout if we're tweening because the tweening // code is handling it. if (tween) return; // Measure the border. var bm:EdgeMetrics = borderMetrics; var paddingLeft:Number = getStyle(""paddingLeft""); var paddingRight:Number = getStyle(""paddingRight""); var paddingTop:Number = getStyle(""paddingTop""); var verticalGap:Number = getStyle(""verticalGap""); // Determine the width and height of the content area. var localContentWidth:Number = calcContentWidth(); var localContentHeight:Number = calcContentHeight(); // Arrange the headers, the content clips, // based on selectedIndex. var x:Number = bm.left + paddingLeft; var y:Number = bm.top + paddingTop; // Adjustments. These are required since the default halo // appearance has verticalGap and all margins set to -1 // so the edges of the headers overlap each other and the // border of the accordion. These overlaps cause problems with // the content area clipping, so we adjust for them here. var contentX:Number = x; var adjContentWidth:Number = localContentWidth; var headerHeight:Number = getHeaderHeight(); if (paddingLeft < 0) { contentX -= paddingLeft; adjContentWidth += paddingLeft; } if (paddingRight < 0) adjContentWidth += paddingRight; var n:int = numChildren; for (var i:int = 0; i < n; i++) { var header:Button = getHeaderAt(i); var content:IUIComponent = IUIComponent(getChildAt(i)); header.move(x, y); header.setActualSize(localContentWidth, headerHeight); y += headerHeight; if (i == selectedIndex) { content.move(contentX, y); content.visible = true; var contentW:Number = adjContentWidth; var contentH:Number = localContentHeight; if (!isNaN(content.percentWidth)) { if (contentW > content.maxWidth) contentW = content.maxWidth; } else { if (contentW > content.getExplicitOrMeasuredWidth()) contentW = content.getExplicitOrMeasuredWidth(); } if (!isNaN(content.percentHeight)) { if (contentH > content.maxHeight) contentH = content.maxHeight; } else { if (contentH > content.getExplicitOrMeasuredHeight()) contentH = content.getExplicitOrMeasuredHeight(); } if (content.width != contentW || content.height != contentH) { content.setActualSize(contentW, contentH); } y += localContentHeight; } else { content.move(contentX, i < selectedIndex ? y : y - localContentHeight); content.visible = false; } y += verticalGap; } // Make sure blocker is in front if (blocker) rawChildren.setChildIndex(blocker, numChildren - 1); // refresh the focus rect, the dimensions might have changed. drawHeaderFocus(_focusedIndex, showFocusIndicator); */ } /** * @private */ override mx_internal function setActualCreationPolicies(policy:String):void { super.setActualCreationPolicies(policy); // If the creation policy is switched to ContainerCreationPolicy.ALL and our createComponents // function has already been called (we've created our children but not // all our grandchildren), then create all our grandchildren now (bug 99160). if (policy == ContainerCreationPolicy.ALL && numChildren > 0) { var n:int = numChildren; for (var i:int = 0; i < n; i++) { Container(getChildAt(i)).createComponentsFromDescriptors(); } } } /** * @private */ override protected function focusInHandler(event:FocusEvent):void { super.focusInHandler(event); showFocusIndicator = focusManager.showFocusIndicator; // When the accordion has focus, the Focus Manager // should not treat the Enter key as a click on // the default pushbutton. if (event.target == this) focusManager.defaultButtonEnabled = false; } /** * @private */ override protected function focusOutHandler(event:FocusEvent):void { super.focusOutHandler(event); showFocusIndicator = false; if (focusManager && event.target == this) focusManager.defaultButtonEnabled = true; } /** * @private */ override public function drawFocus(isFocused:Boolean):void { drawHeaderFocus(_focusedIndex, isFocused); } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); if (!styleProp || styleProp == ""headerStyleName"" || styleProp == ""styleName"") { var headerStyleName:Object = getStyle(""headerStyleName""); var header:Button; if (headerStyleName) { if (FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0) { var headerStyleDecl:CSSStyleDeclaration = IStyleManager2(FlexGlobals.topLevelApplication.styleManager).getStyleDeclaration(""."" + headerStyleName); if (headerStyleDecl) { // Need to reset the header style declaration and // regenerate their style cache for (var i:int = 0; i < numChildren; i++) { header = getHeaderAt(i); if (header) { header.styleDeclaration = headerStyleDecl; header.regenerateStyleCache(true); header.styleChanged(null); } } } } else { for (var j:int = 0; j < numChildren; j++) { header = getHeaderAt(j); if (header) { header.styleName = headerStyleName; } } } } } else if (IStyleManager2(FlexGlobals.topLevelApplication.styleManager).isSizeInvalidatingStyle(styleProp)) { layoutStyleChanged = true; } } /** * @private * When asked to create an overlay mask, create it on the selected child * instead. That way, the chrome around the edge of the Accordion (e.g. the * header buttons) is not occluded by the overlay mask (bug 99029). */ override mx_internal function addOverlay(color:uint, targetArea:RoundedRectangle=null):void { // As we're switching the currently-selected child, don't // allow two children to both have an overlay at the same time. // This is done because it makes accounting a headache. If there's // a legitimate reason why two children both need overlays, this // restriction could be relaxed. if (overlayChild) removeOverlay(); // Remember which child has an overlay, so that we don't inadvertently // create an overlay on one child and later try to remove the overlay // of another child. (bug 100731) overlayChild = selectedChild as IUIComponent; if (!overlayChild) return; FLEX_TARGET_VERSION::flex4 { effectOverlayColor = color; } FLEX_TARGET_VERSION::flex3 { overlayColor = color; } overlayTargetArea = targetArea; if (selectedChild && selectedChild.numChildrenCreated == -1) // No children have been created { // Wait for the childrenCreated event before creating the overlay selectedChild.addEventListener(FlexEvent.INITIALIZE, initializeHandler); } else // Children already exist { initializeHandler(null); } } /** * @private * Called when we are running a Dissolve effect * and the initialize event has been dispatched * or the children already exist */ private function initializeHandler(event:FlexEvent):void { FLEX_TARGET_VERSION::flex4 { UIComponent(overlayChild).addOverlay(effectOverlayColor, overlayTargetArea); } FLEX_TARGET_VERSION::flex3 { UIComponent(overlayChild).addOverlay(overlayColor, overlayTargetArea); } } /** * @private * Handle key down events */ override mx_internal function removeOverlay():void { if (overlayChild) { UIComponent(overlayChild).removeOverlay(); overlayChild = null; } } // ------------------------------------------------------------------------- // StateInterface // ------------------------------------------------------------------------- /** * @copy mx.managers.IHistoryManagerClient#saveState() */ public function saveState():Object { var index:int = _selectedIndex == -1 ? 0 : _selectedIndex; return {selectedIndex: index}; } /** * @copy mx.managers.IHistoryManagerClient#loadState() */ public function loadState(state:Object):void { var newIndex:int = state ? int(state.selectedIndex) : 0; if (newIndex == -1) newIndex = initialSelectedIndex; if (newIndex == -1) newIndex = 0; if (newIndex != _selectedIndex) { // When loading a new state, we don't want to // save our current state in the history stack. bInLoadState = true; selectedIndex = newIndex; bInLoadState = false; } } //-------------------------------------------------------------------------- // // Public methods // //-------------------------------------------------------------------------- /** * Returns a reference to the navigator button for a child container. * * @param index Zero-based index of the child. * * @return Button object representing the navigator button. */ public function getHeaderAt(index:int):Button { return Button(rawChildren.getChildByName(HEADER_NAME_BASE + index)); } /** * @private * Returns the height of the header control. All header controls are the same * height. */ protected function getHeaderHeight():Number { var headerHeight:Number = getStyle(""headerHeight""); if (isNaN(headerHeight)) { headerHeight = 0; if (numChildren > 0) headerHeight = getHeaderAt(0).measuredHeight; } return headerHeight; } /** * @private * Returns the width of the header control. All header controls are the same * width. */ protected function getHeaderWidth():Number { var headerWidth:Number = getStyle(""headerWidth""); if (isNaN(headerWidth)) { headerWidth = 0; if (numChildren > 0) headerWidth = getHeaderAt(0).measuredHeight; } return headerWidth; } //-------------------------------------------------------------------------- // // Private methods // //-------------------------------------------------------------------------- /** * @private * Utility method to create the segment header */ private function createHeader(content:DisplayObject, i:int):void { // Before creating the header, un-select the currently selected // header. We will be selecting the correct header below. if (selectedIndex != -1 && getHeaderAt(selectedIndex)) getHeaderAt(selectedIndex).selected = false; // Create the header. // Notes: // 1) An accordion maintains a reference to // the header for its Nth child as _headerN. These references are // juggled when children and their headers are re-indexed or // removed, to ensure that _headerN is always a reference the // header for the Nth child. // 2) Always create the header with the index of the last item. // If needed, the headers will be shuffled below. var header:Button = Button(headerRenderer.newInstance()); header.name = HEADER_NAME_BASE + (numChildren - 1); if (FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0) { header.styleName = this; } var headerStyleName:String = getStyle(""headerStyleName""); if (headerStyleName) { if (FlexVersion.compatibilityVersion < FlexVersion.VERSION_3_0) { var headerStyleDecl:CSSStyleDeclaration = IStyleManager2(FlexGlobals.topLevelApplication.styleManager).getStyleDeclaration(""."" + headerStyleName); if (headerStyleDecl) header.styleDeclaration = headerStyleDecl; } else { header.styleName = headerStyleName; } } header.addEventListener(MouseEvent.CLICK, headerClickHandler); IDataRenderer(header).data = content; if (content is Container) { var contentContainer:Container = Container(content); header.label = contentContainer.label; if (contentContainer.icon) header.setStyle(""icon"", contentContainer.icon); // If the child has a toolTip, transfer it to the header. var toolTip:String = contentContainer.toolTip; if (toolTip && toolTip != """") { header.toolTip = toolTip; contentContainer.toolTip = null; } } rawChildren.addChild(header); // If the newly added child isn't at the end of our child list, shuffle // the headers accordingly. if (i != numChildren - 1) shuffleHeaders(numChildren - 1, i); // Make sure the correct header is selected if (selectedIndex != -1 && getHeaderAt(selectedIndex)) getHeaderAt(selectedIndex).selected = true; } /** * @private */ protected function calcContentWidth():Number { // Start with the width of the entire accordion. var contentWidth:Number = unscaledWidth; // Subtract the widths of the left and right borders. var vm:EdgeMetrics = viewMetricsAndPadding; contentWidth -= vm.left + vm.right; return contentWidth; } /** * @private */ protected function calcContentHeight():Number { // Start with the height of the entire accordion. var contentHeight:Number = unscaledHeight; // Subtract the heights of the top and bottom borders. var vm:EdgeMetrics = viewMetricsAndPadding; contentHeight -= vm.top + vm.bottom; // Subtract the header heights. var verticalGap:Number = getStyle(""verticalGap""); var headerHeight:Number = getHeaderHeight(); var n:int = numChildren; for (var i:int = 0; i < n; i++) { contentHeight -= headerHeight; if (i > 0) contentHeight -= verticalGap; } return contentHeight; } /** * @private */ protected function drawHeaderFocus(headerIndex:int, isFocused:Boolean):void { if (headerIndex != -1) getHeaderAt(headerIndex).drawFocus(isFocused); } /** * @private */ private function headerClickHandler(event:Event):void { var header:Button = Button(event.currentTarget); var oldIndex:int = selectedIndex; // content is placed onto the button so we have to access it via [] selectedChild = Container(IDataRenderer(header).data); var newIndex:int = selectedIndex; if (oldIndex != newIndex) dispatchChangeEvent(oldIndex, newIndex, event); } /** * @private */ private function commitSelectedIndex():void { if (proposedSelectedIndex == -1) return; var newIndex:int = proposedSelectedIndex; proposedSelectedIndex = -1; // The selectedIndex must be undefined if there are no children, // even if a selectedIndex has been proposed. if (numChildren == 0) { _selectedIndex = -1; return; } // Ensure that the new index is in bounds. if (newIndex < 0) newIndex = 0; else if (newIndex > numChildren - 1) newIndex = numChildren - 1; // Remember the old index. var oldIndex:int = _selectedIndex; // Bail if the index isn't changing. if (newIndex == oldIndex) return; // If we are currently playing a Dissolve effect, end it and restart it again currentDissolveEffect = null; if (isEffectStarted) { var dissolveInstanceClass:Class = Class(systemManager.getDefinitionByName(""mx.effects.effectClasses.DissolveInstance"")); for (var i:int = 0; i < _effectsStarted.length; i++) { // Avoid referencing the DissolveInstance class directly, so that // we don't create an unwanted linker dependency. if (dissolveInstanceClass && _effectsStarted[i] is dissolveInstanceClass) { // If we find the dissolve, save a pointer to the parent effect and end the instance currentDissolveEffect = _effectsStarted[i].effect; _effectsStarted[i].end(); break; } } } // Unfocus the old header. if (_focusedIndex != newIndex) drawHeaderFocus(_focusedIndex, false); // Deselect the old header. if (oldIndex != -1) getHeaderAt(oldIndex).selected = false; // Commit the new index. _selectedIndex = newIndex; // Remember our initial selected index so we can // restore to our default state when the history // manager requests it. if (initialSelectedIndex == -1) initialSelectedIndex = _selectedIndex; // Select the new header. getHeaderAt(newIndex).selected = true; if (_focusedIndex != newIndex) { // Focus the new header. _focusedIndex = newIndex; drawHeaderFocus(_focusedIndex, showFocusIndicator); } if (bSaveState) { HistoryManager.save(); bSaveState = false; } if (getStyle(""openDuration"") == 0 || oldIndex == -1) { // Need to set the new index to be visible here // in order for effects to work. Container(getChildAt(newIndex)).setVisible(true); // Now that the effects have been triggered, we can hide the // current view until it is properly sized and positioned below. Container(getChildAt(newIndex)).setVisible(false, true); if (oldIndex != -1) Container(getChildAt(oldIndex)).setVisible(false); instantiateChild(selectedChild); } else { if (tween) tween.endTween(); startTween(oldIndex, newIndex); } } /** * @private */ protected function instantiateChild(child:Container):void { // fix for bug#137430 // when the selectedChild index is -1 (invalid value due to any reason) // selectedContainer will not be valid. Before we proceed // we need to make sure of its validity. if (!child) return; // Performance optimization: don't call createComponents if we know // that createComponents has already been called. if (child && child.numChildrenCreated == -1) child.createComponentsFromDescriptors(); // Do the initial measurement/layout pass for the newly-instantiated // descendants. invalidateSize(); invalidateDisplayList(); if (child is IInvalidating) IInvalidating(child).invalidateSize(); } /** * @private */ private function dispatchChangeEvent(oldIndex:int, newIndex:int, cause:Event=null):void { var indexChangeEvent:IndexChangedEvent = new IndexChangedEvent(IndexChangedEvent.CHANGE); indexChangeEvent.oldIndex = oldIndex; indexChangeEvent.newIndex = newIndex; indexChangeEvent.relatedObject = getChildAt(newIndex); indexChangeEvent.triggerEvent = cause; dispatchEvent(indexChangeEvent); } /** * @private */ protected function startTween(oldSelectedIndex:int, newSelectedIndex:int):void { bSliding = true; // To improve the animation performance, we set up some invariants // used in onTweenUpdate. (Some of these, like contentHeight, are // too slow to recalculate at every tween step.) tweenViewMetrics = viewMetricsAndPadding; tweenContentWidth = calcContentWidth(); tweenContentHeight = calcContentHeight(); tweenOldSelectedIndex = oldSelectedIndex; tweenNewSelectedIndex = newSelectedIndex; // A single instance of Tween drives the animation. var openDuration:Number = getStyle(""openDuration""); tween = new Tween(this, 0, tweenContentHeight, openDuration); var easingFunction:Function = getStyle(""openEasingFunction"") as Function; if (easingFunction != null) tween.easingFunction = easingFunction; // Ideally, all tweening should be managed by the EffectManager. Since // this tween isn't managed by the EffectManager, we need this alternate // mechanism to tell the EffectManager that we're tweening. Otherwise, the // EffectManager might try to play another effect that animates the same // properties. if (oldSelectedIndex != -1) Container(getChildAt(oldSelectedIndex)).tweeningProperties = [""x"", ""y"", ""width"", ""height""]; Container(getChildAt(newSelectedIndex)).tweeningProperties = [""x"", ""y"", ""width"", ""height""]; // If the content of the new child hasn't been created yet, set the new child // to the content width/height. This way any background color will show up // properly during the animation. var newSelectedChild:Container = Container(getChildAt(newSelectedIndex)); if (newSelectedChild.numChildren == 0) { var paddingLeft:Number = getStyle(""paddingLeft""); var contentX:Number = borderMetrics.left + (paddingLeft > 0 ? paddingLeft : 0); newSelectedChild.move(contentX, newSelectedChild.y); newSelectedChild.setActualSize(tweenContentWidth, tweenContentHeight); } UIComponent.suspendBackgroundProcessing(); } /** * @private */ mx_internal function onTweenUpdate(value:Number):void { // Fetch the tween invariants we set up in startTween. var vm:EdgeMetrics = tweenViewMetrics; var contentWidth:Number = tweenContentWidth; var contentHeight:Number = tweenContentHeight; var oldSelectedIndex:int = tweenOldSelectedIndex; var newSelectedIndex:int = tweenNewSelectedIndex; // The tweened value is the height of the new content area, which varies // from 0 to the contentHeight. As the new content area grows, the // old content area shrinks. var newContentHeight:Number = value; var oldContentHeight:Number = contentHeight - value; // These offsets for the Y position of the content clips make the content // clips appear to be pushed up and pulled down. var oldOffset:Number = oldSelectedIndex < newSelectedIndex ? -newContentHeight : newContentHeight; var newOffset:Number = newSelectedIndex > oldSelectedIndex ? oldContentHeight : -oldContentHeight; // Loop over all the headers to arrange them vertically. // The loop is intentionally over ALL the headers, not just the ones that // need to move; this makes the animation look equally smooth // regardless of how many headers are moving. // We also reposition the two visible content clips. var y:Number = vm.top; var verticalGap:Number = getStyle(""verticalGap""); var n:int = numChildren; for (var i:int = 0; i < n; i++) { var header:Button = getHeaderAt(i); var content:Container = Container(getChildAt(i)); header.$y = y; y += header.height; if (i == oldSelectedIndex) { content.cacheAsBitmap = true; content.scrollRect = new Rectangle(0, -oldOffset, contentWidth, contentHeight); content.visible = true; y += oldContentHeight; } else if (i == newSelectedIndex) { content.cacheAsBitmap = true; content.scrollRect = new Rectangle(0, -newOffset, contentWidth, contentHeight); content.visible = true; y += newContentHeight; } y += verticalGap; } } /** * @private */ mx_internal function onTweenEnd(value:Number):void { bSliding = false; var oldSelectedIndex:int = tweenOldSelectedIndex; var vm:EdgeMetrics = tweenViewMetrics; var verticalGap:Number = getStyle(""verticalGap""); var headerHeight:Number = getHeaderHeight(); var localContentWidth:Number = calcContentWidth(); var localContentHeight:Number = calcContentHeight(); var y:Number = vm.top; var content:Container; var n:int = numChildren; for (var i:int = 0; i < n; i++) { var header:Button = getHeaderAt(i); header.$y = y; y += headerHeight; if (i == selectedIndex) { content = Container(getChildAt(i)); content.cacheAsBitmap = false; content.scrollRect = null; content.visible = true; y += localContentHeight; } y += verticalGap; } if (oldSelectedIndex != -1) { content = Container(getChildAt(oldSelectedIndex)); content.cacheAsBitmap = false; content.scrollRect = null; content.visible = false; content.tweeningProperties = null; } // Delete the temporary tween invariants we set up in startTween. tweenViewMetrics = null; tweenContentWidth = NaN; tweenContentHeight = NaN; tweenOldSelectedIndex = 0; tweenNewSelectedIndex = 0; tween = null; UIComponent.resumeBackgroundProcessing(); Container(getChildAt(selectedIndex)).tweeningProperties = null; // If we interrupted a Dissolve effect, restart it here if (currentDissolveEffect) { if (currentDissolveEffect.target != null) { currentDissolveEffect.play(); } else { currentDissolveEffect.play([this]); } } // Let the screen render the last frame of the animation before // we begin instantiating the new child. callLater(instantiateChild, [selectedChild]); } //-------------------------------------------------------------------------- // // Overridden event handlers // //-------------------------------------------------------------------------- /** * @private * Handles ""keyDown"" event. */ override protected function keyDownHandler(event:KeyboardEvent):void { // Only listen for events that have come from the accordion itself. if (event.target != this) return; var prevValue:int = selectedIndex; switch (event.keyCode) { case Keyboard.PAGE_DOWN: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = selectedIndex = (selectedIndex < numChildren - 1 ? selectedIndex + 1 : 0); drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); dispatchChangeEvent(prevValue, selectedIndex, event); break; } case Keyboard.PAGE_UP: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = selectedIndex = (selectedIndex > 0 ? selectedIndex - 1 : numChildren - 1); drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); dispatchChangeEvent(prevValue, selectedIndex, event); break; } case Keyboard.HOME: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = selectedIndex = 0; drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); dispatchChangeEvent(prevValue, selectedIndex, event); break; } case Keyboard.END: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = selectedIndex = numChildren - 1; drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); dispatchChangeEvent(prevValue, selectedIndex, event); break; } case Keyboard.DOWN: case Keyboard.RIGHT: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = (_focusedIndex < numChildren - 1 ? _focusedIndex + 1 : 0); drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); break; } case Keyboard.UP: case Keyboard.LEFT: { drawHeaderFocus(_focusedIndex, false); _focusedIndex = (_focusedIndex > 0 ? _focusedIndex - 1 : numChildren - 1); drawHeaderFocus(_focusedIndex, true); event.stopPropagation(); break; } case Keyboard.SPACE: case Keyboard.ENTER: { event.stopPropagation(); if (_focusedIndex != selectedIndex) { selectedIndex = _focusedIndex; dispatchChangeEvent(prevValue, selectedIndex, event); } break; } } } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private * Handles ""addedToStage"" event */ private function addedToStageHandler(event:Event):void { if (historyManagementEnabled) HistoryManager.register(this); } /** * @private * Handles ""removedFromStage"" event */ private function removedFromStageHandler(event:Event):void { HistoryManager.unregister(this); } /** * @private */ private function childAddHandler(event:ChildExistenceChangedEvent):void { childAddedOrRemoved = true; var child:DisplayObject = event.relatedObject; // Accordion creates all of its children initially invisible. // They are made as they become the selected child. child.visible = false; // Create the header associated with this child. createHeader(child, getChildIndex(child)); // If the child's label or icon changes, Accordion needs to know so that // the header label can be updated. This event is handled by // labelChanged(). // note: weak listeners child.addEventListener(""labelChanged"", labelChangedHandler, false, 0, true); child.addEventListener(""iconChanged"", iconChangedHandler, false, 0, true); // If we just created the first child and no selected index has // been proposed, then propose this child to be selected. if (numChildren == 1 && proposedSelectedIndex == -1) { selectedIndex = 0; // Select the new header. var newHeader:Button = getHeaderAt(0); newHeader.selected = true; // Focus the new header. _focusedIndex = 0; drawHeaderFocus(_focusedIndex, showFocusIndicator); } if (child as IAutomationObject) { IAutomationObject(child).showInAutomationHierarchy = true; } } /** * @private */ private function childRemoveHandler(event:ChildExistenceChangedEvent):void { childAddedOrRemoved = true; if (numChildren == 0) return; var child:DisplayObject = event.relatedObject; var oldIndex:int = selectedIndex; var newIndex:int; var index:int = getChildIndex(child); // Remove Event Listeners, in case children are referenced elsewhere. child.removeEventListener(""labelChanged"", labelChangedHandler); child.removeEventListener(""iconChanged"", iconChangedHandler); var nChildren:int = numChildren - 1; // number of children remaining after child has been removed rawChildren.removeChild(getHeaderAt(index)); // Shuffle all higher numbered headers down. for (var i:int = index; i < nChildren; i++) { getHeaderAt(i + 1).name = HEADER_NAME_BASE + i; } // If we just deleted the only child, the accordion is now empty, // and no child is now selected. if (nChildren == 0) { // There's no need to go through all of commitSelectedIndex(), // and it wouldn't do the right thing, anyway, because // it bails immediately if numChildren is 0. newIndex = _focusedIndex = -1; } else if (index > selectedIndex) { return; } // If we deleted a child before the selected child, the // index of that selected child is now 1 less than it was, // but the selected child itself hasn't changed. else if (index < selectedIndex) { newIndex = oldIndex - 1; } // Now handle the case that we deleted the selected child // and there is another child that we must select. else if (index == selectedIndex) { // If it was the last child, select the previous one. // Otherwise, select the next one. This next child now // has the same index as the one we just deleted, if (index == nChildren) { newIndex = oldIndex - 1; // if something's selected, instantiate it if (newIndex != -1) instantiateChild(Container(getChildAt(newIndex))); } else { newIndex = oldIndex; // can't do selectedChild because we need to actually do // newIndex + 1 because currently that's what the index // of the child is (SDK-12622) since this one isn't // actually removed from the display list yet instantiateChild(Container(getChildAt(newIndex + 1))); } // Select the new selected index header. var newHeader:Button = getHeaderAt(newIndex); newHeader.selected = true; } if (_focusedIndex > index) { _focusedIndex--; drawHeaderFocus(_focusedIndex, showFocusIndicator); } else if (_focusedIndex == index) { if (index == nChildren) _focusedIndex--; drawHeaderFocus(_focusedIndex, showFocusIndicator); } _selectedIndex = newIndex; dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); } /** * @private * Handles ""labelChanged"" event. */ private function labelChangedHandler(event:Event):void { var child:DisplayObject = DisplayObject(event.target); var childIndex:int = getChildIndex(child); var header:Button = getHeaderAt(childIndex); header.label = Container(event.target).label; } /** * @private * Handles ""iconChanged"" event. */ private function iconChangedHandler(event:Event):void { var child:DisplayObject = DisplayObject(event.target); var childIndex:int = getChildIndex(child); var header:Button = getHeaderAt(childIndex); header.setStyle(""icon"", Container(event.target).icon); //header.icon = Container(event.target).icon; } } } ",16332,True,2934.910113804202,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.charts.series { /* import flash.display.DisplayObject; import flash.display.Graphics; import flash.geom.Point; import flash.geom.Rectangle; import flash.utils.Dictionary; import mx.charts.DateTimeAxis; import mx.charts.HitData; import mx.charts.chartClasses.BoundedValue; import mx.charts.chartClasses.CartesianChart; import mx.charts.chartClasses.CartesianTransform; import mx.charts.chartClasses.DataDescription; import mx.charts.chartClasses.GraphicsUtilities; import mx.charts.chartClasses.IAxis; import mx.charts.chartClasses.InstanceCache; import mx.charts.chartClasses.LegendData; import mx.charts.chartClasses.NumericAxis; import mx.charts.chartClasses.Series; import mx.charts.renderers.LineRenderer; import mx.charts.series.items.LineSeriesItem; import mx.charts.series.items.LineSeriesSegment; import mx.charts.series.renderData.LineSeriesRenderData; import mx.charts.styles.HaloDefaults; import mx.collections.CursorBookmark; import mx.core.ClassFactory; import mx.core.IDataRenderer; import mx.core.IFactory; import mx.core.IFlexDisplayObject; import mx.core.IFlexModuleFactory; import mx.core.mx_internal; import mx.graphics.IFill; import mx.graphics.IStroke; import mx.graphics.LinearGradientStroke; import mx.graphics.SolidColor; import mx.graphics.SolidColorStroke; import mx.graphics.Stroke; import mx.styles.CSSStyleDeclaration; import mx.styles.ISimpleStyleClient; use namespace mx_internal; include ""../styles/metadata/FillStrokeStyles.as"" include ""../styles/metadata/ItemRendererStyles.as"" */ import org.apache.royale.charts.supportClasses.LineSeries; /** * Specifies the number of pixels by which radius of the chart item is to be * increased when highlighted or selected. * * @default 2 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ //[Style(name=""adjustedRadius"", type=""Number"", format=""Length"", inherit=""yes"")] /** * Specifies an Array of fill objects that define the fill for * each item in the series. This takes precedence over the fill style property. * If a custom method is specified by the fillFunction property, that takes precedence over this Array. * If you do not provide enough Array elements for every item, * Flex repeats the fill from the beginning of the Array. * *

To set the value of this property using CSS: *

 *    LineSeries {
 *      fills:#CC66FF, #9966CC, #9999CC;
 *    }
 *   
*

* *

To set the value of this property using MXML: *

 *    <mx:LineSeries ... >
 *     <mx:fills>
 *      <mx:SolidColor color=""0xCC66FF""/>
 *      <mx:SolidColor color=""0x9966CC""/>
 *      <mx:SolidColor color=""0x9999CC""/>
 *     </mx:fills>
 *    </mx:LineSeries>
 *   
*

* *

* If you specify the fills property and you * want to have a Legend control, you must manually create a Legend control and * add LegendItems to it. *

* * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ //[Style(name=""fills"", type=""Array"", arrayType=""mx.graphics.IFill"", inherit=""no"")] /** * Specifies the line type for the chart. * Possible values are: *
    *
  • ""curve"": * Draws curves between data points.
  • * *
  • ""horizontal"": * Draws only the vertical line from the x-coordinate * of the first point to the x-coordinate of the second point * at the y-coordinate of the second point. * Repeats this for each data point.
  • * *
  • ""vertical"": * Draws only the vertical line from the y-coordinate * of the first point to the y-coordinate of the second point * at the x-coordinate of the second point. * Repeats this for each data point.
  • * *
  • ""segment"": * Draws lines as connected segments that are angled * to connect at each data point in the series.
  • * *
  • ""step"": * Draws lines as horizontal segments. * At the first data point, draws a horizontal line * and then a vertical line to the second point, * and repeats for each data point.
  • * *
  • ""reverseStep"": * Draws lines as horizontal segments. * At the first data point, draws a vertical line * and then a horizontal line to the second point, * and repeats for each data point.
  • *
* The default is ""segment"". * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ //[Style(name=""form"", type=""String"", enumeration=""segment,step,reverseStep,vertical,horizontal,curve"", inherit=""no"")] /** * A factory that represents the class the series uses * to represent the individual line segments in the series. * This class is instantiated once * for each distinct segment of the series. * Classes used as lineSegmentRenderers should implement * the IFlexDisplayObject, ISimpleStyleClient, and IDataRenderer interfaces. * The data property is assigned an instance of * mx.charts.series.items.LineSeriesSegment * that describes the segment to render. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""lineSegmentRenderer"", type=""mx.core.IFactory"", inherit=""no"")] /** * Sets the stroke for the actual line segments. * The default value for a LineChart control is orange (0xE48701). * The default color for a LineSeries used in a CartesianChart control is black (0x000000). * The default value for the width is 3. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""lineStroke"", type=""mx.graphics.IStroke"", inherit=""no"")] /** * Specifies the radius, in pixels, of the chart elements for the data points. * This property applies only if you specify an item renderer * using the itemRenderer property. * You can specify the itemRenderer in MXML or using styles. * * @default 4 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ //[Style(name=""radius"", type=""Number"", format=""Length"", inherit=""no"")] /** * Defines a data series for a LineChart control. * By default, this class uses the ShadowLineRenderer class. * Optionally, you can define an itemRenderer for the data series. * The itemRenderer must implement the IDataRenderer interface. * * @mxml * *

The <mx:LineSeries> tag inherits all the properties * of its parent classes and adds the following properties:

* *
 *  <mx:LineSeries
 *    Properties
 *    fillFunction=""Internal fill function""
 *    horizontalAxis=""No default""
 *    interpolateValues=""false|true""
 *    sortOnXField=""false|true""
 *    verticalAxis=""No default""
 *    xField=""null""
 *    yField=""null""
 * 
 *    Styles
 *    adjustedRadius=""2""
 *    fill=""0xFFFFFF""
 *    fills=""IFill; no default""
 *    form=""segment|curve|horizontal|reverseStep|step|vertical""
 *    itemRenderer=""itemRenderer""
 *    legendMarkerRenderer=""Defaults to series's itemRenderer""
 *    lineSegmentRenderer=""ShadowLineRenderer""
 *    lineStroke=""Stroke(0xE47801,3)""
 *    radius=""4""
 *    stroke=""IStroke; no default"" 
 *  />
 *  
* * @see mx.charts.LineChart * @see mx.core.IDataRenderer * * @includeExample ../examples/Line_AreaChartExample.mxml * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class LineSeries extends org.apache.royale.charts.supportClasses.LineSeries { //extends Series //include ""../../core/Version.as""; //-------------------------------------------------------------------------- // // Class initialization // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function LineSeries() { super(); /* _pointInstanceCache = new InstanceCache(null, this, 1000); _pointInstanceCache.creationCallback = applyItemRendererProperties; _segmentInstanceCache = new InstanceCache(null, this, 0); _segmentInstanceCache.properties = { styleName: this }; dataTransform = new CartesianTransform(); // our style settings initStyles(); */ } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- //---------------------------------- // displayName copied from Series //---------------------------------- /** * @private * Storage for the displayName property. */ private var _displayName:String; [Inspectable(category=""Display"")] /** * The name of the series, for display to the user. * This property is used to represent the series in user-visible labels, * such as data tips. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get displayName():String { return _displayName; } /** * @private */ public function set displayName(value:String):void { _displayName = value; /* var c:ChartBase = chart; if (c) c.legendDataChanged(); */ } //---------------------------------- // styleName copied from UIComponent //---------------------------------- /** * @private * Storage for the styleName property. */ private var _styleName:Object /* String, CSSStyleDeclaration, or UIComponent */; [Inspectable(category=""General"")] /** * The class style used by this component. This can be a String, CSSStyleDeclaration * or an IStyleClient. * *

If this is a String, it is the name of one or more whitespace delimited class * declarations in an <fx:Style> tag or CSS file. You do not include the period * in the styleName. For example, if you have a class style named "".bigText"", * set the styleName property to ""bigText"" (no period).

* *

If this is an IStyleClient (typically a UIComponent), all styles in the * styleName object are used by this component.

* * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get styleName():Object /* String, CSSStyleDeclaration, or UIComponent */ { return _styleName; } /** * @private */ public function set styleName(value:Object /* String, CSSStyleDeclaration, or UIComponent */):void { if (_styleName === value) return; _styleName = value; // If inheritingStyles is undefined, then this object is being // initialized and we haven't yet generated the proto chain. // To avoid redundant work, don't bother to create // the proto chain here. /* if (inheritingStyles == StyleProtoChain.STYLE_UNINITIALIZED) return; regenerateStyleCache(true); initThemeColor(); styleChanged(""styleName""); notifyStyleChangeInChildren(""styleName"", true); */ } /** * @private */ //private static var _moduleFactoryInitialized:Dictionary = new Dictionary(true); /** * @private */ //private var _pointInstanceCache:InstanceCache; /** * @private */ //private var _renderData:LineSeriesRenderData; /** * @private */ //private var _segmentInstanceCache:InstanceCache; /** * @private */ //private var _localFills:Array /* of IFill */; /** * @private */ //private var _fillCount:int; /** * @private */ // private var _bAxesDirty:Boolean = false; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // legendData //---------------------------------- /** * @private */ // override public function get legendData():Array /* of LegendData */ // { // if (fillFunction!=defaultFillFunction || _fillCount!=0) // { // var keyItems:Array /* of LegendData */ = []; // return keyItems; // } // var radius:Number = getStyle(""radius"") // var itemRenderer:IFactory = getStyle(""itemRenderer""); // var markerAspectRatio:Number; // var color:int = 0; // var marker:IFlexDisplayObject; // var ld:LegendData = new LegendData(); // ld.element = this; // ld.label = displayName; // var markerFactory:IFactory = getStyle(""legendMarkerRenderer""); // if (markerFactory) // { // marker = markerFactory.newInstance(); // if (marker is ISimpleStyleClient) // (marker as ISimpleStyleClient).styleName = this; // ld.aspectRatio = 1; // } // else if (!itemRenderer || radius == 0 || isNaN(radius)) // { // marker = new LineSeriesLegendMarker(this); // } // else // { // markerFactory = getStyle(""itemRenderer""); // marker = markerFactory.newInstance(); // ld.aspectRatio = 1; // if (marker as ISimpleStyleClient) // (marker as ISimpleStyleClient).styleName = this; // } // ld.marker = marker; // return [ld]; // } //---------------------------------- // renderData //---------------------------------- /** * @private */ /* override protected function get renderData():Object { if (!_renderData|| !(_renderData.cache) || _renderData.cache.length == 0) { var renderDataType:Class = this.renderDataType; var ld:LineSeriesRenderData = new renderDataType(); ld.cache = ld.filteredCache = []; ld.segments = []; ld.radius = 0; return ld; } _renderData.radius = getStyle(""radius""); return _renderData; } */ //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //----------------------------------- // fillFunction //----------------------------------- /* [Bindable] [Inspectable(category=""General"")] */ /** * @private * Storage for fillFunction property */ /* private var _fillFunction:Function=defaultFillFunction; */ /** * Specifies a method that returns the fill for the current chart item in the series. * If this property is set, the return value of the custom fill function takes precedence over the * fill and fills style properties. * But if it returns null, then fills and fill will be * prefered in that order. * *

The custom fillFunction has the following signature: * *

     * function_name (item:ChartItem, index:Number):IFill { ... }
     * 
* * item is a reference to the chart item that is being rendered. * index is the index of the chart item in the renderData's cache. This is different * from the index of the chart's data provider because it is sorted based on the x, y, and z values. * This function returns an object that implements the IFill interface. *

* *

An example usage of a customized fillFunction is to return a fill * based on some threshold.

* * @example *
     * public function myFillFunction(item:ChartItem, index:Number):IFill {
     *      var curItem:LineSeriesItem = LineSeriesItem(item);
     *      if (curItem.yNumber > 10)
     *          return(new SolidColor(0x123456, .75));
     *      else
     *          return(new SolidColor(0x563412, .75));
     * }
     * 
* *

* If you specify a custom fill function for your chart series and you * want to have a Legend control, you must manually create a Legend control and * add LegendItems to it. *

* * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* public function get fillFunction():Function { return _fillFunction; } */ /** * @private */ /* public function set fillFunction(value:Function):void { if (value ==_fillFunction) return; if (value != null) _fillFunction = value; else _fillFunction = defaultFillFunction; invalidateDisplayList(); legendDataChanged(); } */ //---------------------------------- // horizontalAxis //---------------------------------- /** * @private * Storage for the horizontalAxis property. */ /* private var _horizontalAxis:IAxis; [Inspectable(category=""Data"")] */ /** * Defines the labels, tick marks, and data position * for items on the x-axis. * Use either the LinearAxis class or the CategoryAxis class * to set the properties of the horizontalAxis as a child tag in MXML * or create a LinearAxis or CategoryAxis object in ActionScript. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* public function get horizontalAxis():IAxis { return _horizontalAxis; } */ /** * @private */ /* public function set horizontalAxis(value:IAxis):void { _horizontalAxis = value; _bAxesDirty = true; invalidateData(); invalidateProperties(); } */ //---------------------------------- // interpolateValues //---------------------------------- /** * @private * Storage for the interpolateValues property. */ /* private var _interpolateValues:Boolean = false; [Inspectable(category=""General"")] */ /** * Specifies how to represent missing data. * *

Set to false to break the line at the missing value. * Set to true to draw a continuous line by interpolating the missing value.

* * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* public function get interpolateValues():Boolean { return _interpolateValues; } */ /** * @private */ /* public function set interpolateValues(value:Boolean):void { if (_interpolateValues != value) { _interpolateValues = value; invalidateData(); } } */ //---------------------------------- // items //---------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // override public function get items():Array /* of LineSeriesItem */ // { // return _renderData ? // _renderData.filteredCache : // null; // } //---------------------------------- // itemType //---------------------------------- // [Inspectable(environment=""none"")] /** * The subtype of ChartItem used by this series * to represent individual items. * Subclasses can override and return a more specialized class * if they need to store additional information in the items. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* protected function get itemType():Class { return LineSeriesItem; } */ //---------------------------------- // lineSegmentType //---------------------------------- //[Inspectable(environment=""none"")] /** * The class used by this series to store all data * necessary to represent a line segment. * Subclasses can override and return a more specialized class * if they need to store additional information for rendering. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* protected function get lineSegmentType():Class { return LineSeriesSegment; } */ //---------------------------------- // radius //---------------------------------- //[Inspectable(category=""Styles"")] /** * Specifies the radius, in pixels, of the chart elements * for the data points. * This property applies only if you specify an item renderer * using the itemRenderer property. * You can specify the itemRenderer in MXML or using styles. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* public function get radius():Number { return getStyle(""radius""); } */ /** * @private */ /* public function set radius(value:Number):void { setStyle(""radius"", value); } */ //---------------------------------- // renderDataType //---------------------------------- //[Inspectable(environment=""none"")] /** * The subtype of ChartRenderData used by this series * to store all data necessary to render. * Subclasses can override and return a more specialized class * if they need to store additional information for rendering. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* protected function get renderDataType():Class { return LineSeriesRenderData; } */ //---------------------------------- // sortOnXField //---------------------------------- /** * @private * Storage for the sortOnXField property. */ /* private var _sortOnXField:Boolean = true; [Inspectable] */ /** * Requests the line datapoints be sorted from left to right * before rendering. * *

By default, the LineSeries renders points from left to right. * Set this property to false to render the items * in the order they appear in the data provider.

* * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* public function get sortOnXField():Boolean { return _sortOnXField; } */ /** * @private */ /* public function set sortOnXField(value:Boolean):void { if (_sortOnXField == value) return; _sortOnXField = value; invalidateMapping(); } */ //---------------------------------- // verticalAxis //---------------------------------- /** * @private * Storage for the verticalAxis property. */ /* private var _verticalAxis:IAxis; [Inspectable(category=""Data"")] */ /** * Defines the labels, tick marks, and data position * for items on the y-axis. * Use either the LinearAxis class or the CategoryAxis class * to set the properties of the verticalAxis as a child tag in MXML * or create a LinearAxis or CategoryAxis object in ActionScript. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* public function get verticalAxis():IAxis { return _verticalAxis; } */ /** * @private */ /* public function set verticalAxis(value:IAxis):void { _verticalAxis = value; _bAxesDirty = true; invalidateData(); //invalidateChildOrder(); invalidateProperties(); } */ //---------------------------------- // xField //---------------------------------- /** * @private * Storage for the xField property. */ /* private var _xField:String = """"; [Inspectable(category=""General"")] */ /** * Specifies the field of the data provider * that determines the x-axis location of each data point. * If null, the data points are rendered * in the order they appear in the data provider. * * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* public function get xField():String { return _xField; } */ /** * @private */ /* public function set xField(value:String):void { _xField = value; dataChanged(); } */ //---------------------------------- // yField //---------------------------------- /** * @private * Storage for the yField property. */ /* private var _yField:String = """"; [Inspectable(category=""General"")] */ /** * Specifies the field of the data provider * that determines the y-axis location of each data point. * If null, the LineSeries assumes the data provider * is an Array of numbers, and uses the numbers as values. * * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* public function get yField():String { return _yField; } */ /** * @private */ /* public function set yField(value:String):void { _yField = value; dataChanged(); } */ //-------------------------------------------------------------------------- // // Overridden methods: UIComponent // //-------------------------------------------------------------------------- /** * @private */ /* private function initStyles():void { HaloDefaults.init(styleManager); var lineSeriesStyle:CSSStyleDeclaration = HaloDefaults.findStyleDeclaration(styleManager, ""mx.charts.series.LineSeries""); if (lineSeriesStyle) { lineSeriesStyle.setStyle(""lineSegmentRenderer"", new ClassFactory(LineRenderer)); lineSeriesStyle.setStyle(""fill"", new SolidColor(0xFFFFFF)); lineSeriesStyle.setStyle(""fills"", []); lineSeriesStyle.setStyle(""lineStroke"", new SolidColorStroke(0,3)); } else { //Fallback to set the style to this chart directly. setStyle(""lineSegmentRenderer"", new ClassFactory(LineRenderer)); setStyle(""fill"", new SolidColor(0xFFFFFF)); setStyle(""fills"", []); setStyle(""lineStroke"", new SolidColorStroke(0,3)); } } */ /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* override public function set moduleFactory(factory:IFlexModuleFactory):void { super.moduleFactory = factory; if (_moduleFactoryInitialized[factory]) return; _moduleFactoryInitialized[factory] = true; } */ /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* override protected function commitProperties():void { super.commitProperties(); if (dataTransform) { if (_horizontalAxis) { _horizontalAxis.chartDataProvider = dataProvider; CartesianTransform(dataTransform).setAxis( CartesianTransform.HORIZONTAL_AXIS,_horizontalAxis); } if (_verticalAxis) { _verticalAxis.chartDataProvider = dataProvider; CartesianTransform(dataTransform).setAxis( CartesianTransform.VERTICAL_AXIS, _verticalAxis); } } var c:CartesianChart = CartesianChart(chart); if (c) { if (!_horizontalAxis) { if (dataTransform.axes[CartesianTransform.HORIZONTAL_AXIS] != c.horizontalAxis) CartesianTransform(dataTransform).setAxis( CartesianTransform.HORIZONTAL_AXIS,c.horizontalAxis); } if (!_verticalAxis) { if (dataTransform.axes[CartesianTransform.VERTICAL_AXIS] != c.verticalAxis) CartesianTransform(dataTransform).setAxis( CartesianTransform.VERTICAL_AXIS, c.verticalAxis); } } dataTransform.elements = [this]; } */ /** * @private */ // override protected function updateDisplayList(unscaledWidth:Number, // unscaledHeight:Number):void // { // super.updateDisplayList(unscaledWidth, unscaledHeight); // var renderData:LineSeriesRenderData = (transitionRenderData)? LineSeriesRenderData(transitionRenderData) :_renderData; // if (!renderData || !(renderData.filteredCache)) // return; // var g:Graphics = graphics; // g.clear(); // var radius:Number = getStyle(""radius""); // var sampleCount:int = renderData.filteredCache.length; // var i:int; // var segCount:int = renderData.segments.length; // var activeRenderCache:Array /* of LineSeriesItem */; ////figure out what cache we're rendering from. If there's a bounds based transtion underway, we need ////to rebuild our cache from the bounds // if (renderData == transitionRenderData && renderData.elementBounds) // { // var elementBounds:Array /* of Rectangle */ = renderData.elementBounds; // sampleCount= elementBounds.length; // activeRenderCache = renderData.filteredCache; // for (i = 0; i < sampleCount; i++) // { // var rcBounds:Object = elementBounds[i]; // var localData:LineSeriesItem = activeRenderCache[i]; // localData.x = (rcBounds.left + rcBounds.right)/2; // localData.y = (rcBounds.bottom + rcBounds.top)/2; // } // } // else // { // activeRenderCache = renderData.filteredCache; // } ////now position each segment // _segmentInstanceCache.factory = getStyle(""lineSegmentRenderer""); // _segmentInstanceCache.count = segCount; // var instances:Array /* of IFlexDisplayObject */ = _segmentInstanceCache.instances; // var v:LineSeriesItem; // for (i = 0; i < segCount; i++) // { // var segment:IFlexDisplayObject = instances[i]; // if (segment is IDataRenderer) // IDataRenderer(segment).data = renderData.segments[i]; // segment.setActualSize(unscaledWidth,unscaledHeight); // } ////if the user has asked for markers at each datapoint, position those as well // if (radius > 0) // { // _pointInstanceCache.factory = getStyle(""itemRenderer""); // _pointInstanceCache.count = renderData.validPoints; // instances = _pointInstanceCache.instances; // var nextInstanceIdx:int = 0; // var bSetData:Boolean = (sampleCount > 0 && (instances[0] is IDataRenderer)) // var rc:Rectangle; // var inst:IFlexDisplayObject; // if (renderData == transitionRenderData && renderData.elementBounds) // { // for (i = 0; i < sampleCount; i++) // { // v = activeRenderCache[i]; // inst = instances[nextInstanceIdx++]; // v.itemRenderer = inst; // v.fill = fillFunction(v,i); // if (!(v.fill)) // v.fill = defaultFillFunction(v,i); // if (v.itemRenderer && (v.itemRenderer as Object).hasOwnProperty('invalidateDisplayList')) // (v.itemRenderer as Object).invalidateDisplayList(); // if (inst) // { // if (bSetData) // IDataRenderer(inst).data = v; // rc = elementBounds[i]; // inst.move(rc.left,rc.top); // inst.setActualSize(rc.width,rc.height); // } // } // } // else // { // for (i = 0; i < sampleCount; i++) // { // v = activeRenderCache[i]; // var e:Object = renderData.filteredCache[i]; //// if (filterData && (isNaN(e.xFilter) || isNaN(e.yFilter))) // if(filterFunction == defaultFilterFunction && // ((filterDataValues == ""outsideRange"" && (isNaN(e.xFilter) || isNaN(e.yFilter))) || // (filterDataValues == ""nulls"" && (isNaN(e.xNumber) || isNaN(e.yNumber))))) // continue; // inst = instances[nextInstanceIdx++]; // v.itemRenderer = inst; // v.fill = fillFunction(v,i); // if (!(v.fill)) // v.fill = defaultFillFunction(v,i); // if (v.itemRenderer && (v.itemRenderer as Object).hasOwnProperty('invalidateDisplayList')) // (v.itemRenderer as Object).invalidateDisplayList(); // if (inst) // { // if (bSetData) // IDataRenderer(inst).data = v; // inst.move(v.x-radius,v.y - radius); // inst.setActualSize(2*radius,2*radius); // } // } // if (chart && allSeriesTransform && chart.chartState == 0) // chart.updateAllDataTips(); // } // } // } /** * @private */ /* override public function stylesInitialized():void { _localFills = getStyle('fills'); if (_localFills != null) _fillCount = _localFills.length; else _fillCount = 0; super.stylesInitialized(); } */ /** * @private */ /* override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); var styles:String = ""fills"" if (styles.indexOf(styleProp)!=-1) { _localFills = getStyle('fills'); if (_localFills != null) _fillCount = _localFills.length; else _fillCount = 0; } if (styleProp == ""itemRenderer"") { _pointInstanceCache.remove = true; _pointInstanceCache.discard = true; _pointInstanceCache.count = 0; _pointInstanceCache.discard = false; _pointInstanceCache.remove = false; } if (styleProp == ""lineSegmentRenderer"") { _segmentInstanceCache.remove = true; _segmentInstanceCache.discard = true; _segmentInstanceCache.count = 0; _segmentInstanceCache.discard = false; _segmentInstanceCache.remove = false; } invalidateDisplayList(); legendDataChanged(); } */ //-------------------------------------------------------------------------- // // Overridden methods: ??? // //-------------------------------------------------------------------------- /** * @private */ /* override protected function updateData():void { var renderDataType:Class = this.renderDataType; _renderData= new renderDataType(); _renderData.cache = []; if (dataProvider) { cursor.seek(CursorBookmark.FIRST); var i:int = 0; var itemClass:Class = itemType; while (!cursor.afterLast) { _renderData.cache[i] = new itemClass(this,cursor.current,i); i++; cursor.moveNext(); } cacheDefaultValues(_yField,_renderData.cache,""yValue""); cacheIndexValues(_xField,_renderData.cache,""xValue""); } if(dataTransform && dataTransform.getAxis(CartesianTransform.VERTICAL_AXIS) is NumericAxis && !(dataTransform.getAxis(CartesianTransform.VERTICAL_AXIS) is DateTimeAxis) && (dataTransform.getAxis(CartesianTransform.VERTICAL_AXIS) as NumericAxis).direction == ""inverted"") _renderData.cache = reverseYValues(_renderData.cache); if(dataTransform && dataTransform.getAxis(CartesianTransform.HORIZONTAL_AXIS) is NumericAxis && !(dataTransform.getAxis(CartesianTransform.HORIZONTAL_AXIS) is DateTimeAxis) && (dataTransform.getAxis(CartesianTransform.HORIZONTAL_AXIS) as NumericAxis).direction == ""inverted"") _renderData.cache = reverseXValues(_renderData.cache); _renderData.validPoints = _renderData.cache.length; super.updateData(); } */ /** * @private */ /* override protected function updateMapping():void { dataTransform.getAxis(CartesianTransform.HORIZONTAL_AXIS).mapCache(_renderData.cache,""xValue"",""xNumber"", (_xField == """")); dataTransform.getAxis(CartesianTransform.VERTICAL_AXIS).mapCache(_renderData.cache,""yValue"",""yNumber""); // now convert if (_xField != """" && _sortOnXField) _renderData.cache.sortOn(""xNumber"",Array.NUMERIC); super.updateMapping(); } */ /** * @private */ /* override protected function updateFilter():void { _renderData.segments = []; var lineSegmentType:Class = this.lineSegmentType; _renderData.filteredCache = filterFunction(_renderData.cache); if(filterFunction != defaultFilterFunction) // we do this only for custom filter function because default filter function //already does this as part of the function. { createLineSegments(_renderData.filteredCache); } super.updateFilter(); } */ /** * @private */ /* override protected function updateTransform():void { dataTransform.transformCache(_renderData.filteredCache,""xNumber"",""x"",""yNumber"",""y""); super.updateTransform(); allSeriesTransform = true; if (chart && chart is CartesianChart) { var cChart:CartesianChart = CartesianChart(chart); var n:int = cChart.series.length; for (var i:int = 0; i < n; i++) { if (cChart.getSeriesTransformState(cChart.series[i])) allSeriesTransform = false; } if (allSeriesTransform) cChart.measureLabels(); } } */ /** * @private */ // override public function describeData(dimension:String, // requiredFields:uint):Array /* of DataDescription */ // { // validateData(); // if (_renderData.cache.length == 0) // return []; // var description:DataDescription = new DataDescription(); // description.boundedValues = null; // var dataMargin:Number; // var stroke:IStroke; // var radius:Number; // var renderer:Object; // if (dimension == CartesianTransform.VERTICAL_AXIS) // { // extractMinMax(_renderData.cache,""yNumber"",description); // if ((requiredFields & DataDescription.REQUIRED_BOUNDED_VALUES) != 0) // { // dataMargin = 0; // stroke = getStyle(""lineStroke""); // if (stroke) // dataMargin = stroke.weight/2; // radius = getStyle(""radius""); // renderer = getStyle(""itemRenderer""); // if (radius > 0 && renderer) // { // stroke = getStyle(""stroke""); // if (stroke) // radius += stroke.weight/2; // dataMargin = Math.max(radius,dataMargin); // } // if (dataMargin > 0) // { // description.boundedValues= []; // description.boundedValues.push(new BoundedValue(description.max,0,dataMargin)); // description.boundedValues.push(new BoundedValue(description.min,dataMargin,0)); // } // } // } // else if (dimension == CartesianTransform.HORIZONTAL_AXIS) // { // if (_xField != """") // { // if ((requiredFields & DataDescription.REQUIRED_MIN_INTERVAL) != 0) // { //// if we need to know the min interval, then we rely on the cache being in order. So we need to sort it if it //// hasn't already been sorted // var cache:Array /* of LineSeriesItem */ = _renderData.cache; // if (_sortOnXField == false) // { // cache = _renderData.cache.concat(); // cache.sortOn(""xNumber"",Array.NUMERIC); // } // extractMinMax(cache,""xNumber"",description,(0 != (requiredFields & DataDescription.REQUIRED_MIN_INTERVAL))); // } // else // { // extractMinMax(_renderData.cache,""xNumber"",description, (requiredFields & DataDescription.REQUIRED_MIN_INTERVAL) != 0); // } // } // else // { // description.min = _renderData.cache[0].xNumber; // description.max = _renderData.cache[_renderData.cache.length-1].xNumber; // if ((requiredFields & DataDescription.REQUIRED_MIN_INTERVAL) != 0) // { // extractMinInterval(_renderData.cache,""xNumber"",description); // } // } // if ((requiredFields & DataDescription.REQUIRED_BOUNDED_VALUES) != 0) // { // dataMargin = 0; // stroke = getStyle(""lineStroke""); // if (stroke) // dataMargin = stroke.weight/2; // radius = getStyle(""radius""); // renderer = getStyle(""itemRenderer""); // if (radius > 0 && renderer) // { // stroke = getStyle(""stroke""); // if (stroke) // radius += stroke.weight/2; // dataMargin = Math.max(radius,dataMargin); // } // if (dataMargin > 0) // { // description.boundedValues= []; // description.boundedValues.push(new BoundedValue(description.max,0,dataMargin)); // description.boundedValues.push(new BoundedValue(description.min,dataMargin,0)); // } // } // } // else // { // return []; // } // return [ description ]; // } /** * @private */ // override public function getAllDataPoints():Array /* of HitData */ // { // if (!_renderData) // return []; // if (!(_renderData.filteredCache)) // return []; // var itemArr:Array /* of LineSeriesItem */ = []; // if (chart && chart.dataTipItemsSet && dataTipItems) // itemArr = dataTipItems; // else if (chart && chart.showAllDataTips && _renderData.filteredCache) // itemArr = _renderData.filteredCache; // else // itemArr = []; // var n:uint = itemArr.length; // var i:uint; // var result:Array /* of HitData */ = []; // for (i = 0; i < n; i++) // { // var v:LineSeriesItem = itemArr[i]; // if (_renderData.filteredCache.indexOf(v) == -1) // { // var itemExists:Boolean = false; // var m:int = _renderData.filteredCache.length; // for (var j:int = 0; j < m; j++) // { // if (v.item == _renderData.filteredCache[j].item) // { // v = _renderData.filteredCache[j]; // itemExists = true; // break; // } // } // if (!itemExists) // continue; // } // if (v) // { // var hd:HitData = new HitData(createDataID(v.index),Math.sqrt(0),v.x,v.y,v); // var istroke:IStroke = getStyle(""lineStroke""); // if (istroke is SolidColorStroke) // hd.contextColor = SolidColorStroke(istroke).color; // else if (istroke is LinearGradientStroke) // { // var gb:LinearGradientStroke = LinearGradientStroke(istroke); // if (gb.entries.length > 0) // hd.contextColor = gb.entries[0].color; // } // hd.dataTipFunction = formatDataTip; // result.push(hd); // } // } // return result; // } /** * @private */ // override public function findDataPoints(x:Number,y:Number,sensitivity:Number):Array /* of HitData */ // { // // esg, 8/7/06: if your mouse is over a series when it gets added and displayed for the first time, this can get called // // before updateData, and before and render data is constructed. The right long term fix is to make sure a stubbed out // // render data is _always_ present, but that's a little disruptive right now. // // if (interactive == false || !_renderData) // return []; // var pr:Number = getStyle(""radius""); // var minDist2:Number = pr + sensitivity; // minDist2 *= minDist2; // var minItem:LineSeriesItem = null; // var pr2:Number = pr * pr; // var n:int = _renderData.filteredCache.length; // if (n == 0) // return []; // if (sortOnXField == true) // { // var low:Number = 0; // var high:Number = n; // var cur:Number = Math.floor((low+high)/2); // var bFirstIsNaN:Boolean = isNaN(_renderData.filteredCache[0]); // while (true) // { // var v:LineSeriesItem = _renderData.filteredCache[cur]; // if (!isNaN(v.yNumber) && !isNaN(v.xNumber)) // { // var dist:Number = (v.x - x)*(v.x - x) + (v.y - y)*(v.y -y); // if (dist <= minDist2) // { // minDist2 = dist; // minItem = v; // } // } // var a:Number; // var b:Number; // if(dataTransform && dataTransform.getAxis(CartesianTransform.HORIZONTAL_AXIS) is NumericAxis && // (dataTransform.getAxis(CartesianTransform.HORIZONTAL_AXIS) as NumericAxis).direction == ""inverted"") // { // a = x; // b = v.x; // } // else // { // a = v.x; // b = x; // } //// if there are NaNs in this array, it's for one of a couple of reasons: //// 1) there were NaNs in the data, which menas an xField was provided, which means they got sorted to the end //// 2) some values got filtered out, in which case we can (sort of) safely assumed that the got filtered from one side, the other, or the entire thing. //// we'll assume that an axis hasn't filtered a middle portion of the array. //// since we can assume that any NaNs are at the beginning or the end, we'll rely on that in our binary search. If there was a NaN in the first slot, //// then we'll assume it's safe to move up the array if we encounter a NaN. It's possible the entire array is NaN, but then nothing will match, so that's ok. // if (a < b || (isNaN(v.x) && bFirstIsNaN)) // { // low = cur; // cur = Math.floor((low + high)/2); // if (cur == low) // break; // } // else // { // high = cur; // cur = Math.floor((low + high)/2); // if (cur == high) // break; // } // } // } // else // { // var i:uint; // for (i = 0; i < n; i++) // { // v = _renderData.filteredCache[i]; // if (!isNaN(v.yNumber) && !isNaN(v.xNumber)) // { // dist = (v.x - x)*(v.x - x) + (v.y - y)*(v.y -y); // if (dist <= minDist2) // { // minDist2 = dist; // minItem = v; // } // } // } // } // if (minItem) // { // var hd:HitData = new HitData(createDataID(minItem.index),Math.sqrt(minDist2),minItem.x,minItem.y,minItem); // var istroke:IStroke = getStyle(""lineStroke""); // if (istroke is SolidColorStroke) // hd.contextColor = SolidColorStroke(istroke).color; // else if (istroke is LinearGradientStroke) // { // var gb:LinearGradientStroke = LinearGradientStroke(istroke); // if (gb.entries.length > 0) // hd.contextColor = gb.entries[0].color; // } // hd.dataTipFunction = formatDataTip; // return [ hd ]; // } // return []; // } /** * @private */ // override public function getElementBounds(renderData:Object):void // { // var cache :Array /* of LineSeriesItem */ = renderData.cache; // var segments:Array /* of LineSeriesSegment */ = renderData.segments; // var rb :Array /* of Rectangle */ = []; // var sampleCount:int = cache.length; // if (sampleCount == 0) // maxBounds = new Rectangle(); // else // { // var radius:Number = renderData.radius; // if (radius == 0 || isNaN(radius)) // radius = 1; // var segCount:int = segments.length; // if (segCount) // { // var v:Object = cache[renderData.segments[0].start]; // var maxBounds:Rectangle = new Rectangle(v.x,v.y,0,0); // } // for (var i:int = 0; i < segCount; i++) // { // var j:int; // var seg:Object = renderData.segments[i]; // if (i > 0){ // var prevSeg:Object = renderData.segments[i-1]; // if (seg.start > prevSeg.end + 1){ // for (j = prevSeg.end + 1; j < seg.start ; j++){ // var rect:Rectangle = new Rectangle(0, 0, 0, 0); // rb[j] = rect; // } // } // } // for (j = seg.start; j <= seg.end; j++) // { // v = cache[j]; // var b:Rectangle = new Rectangle(v.x-radius,v.y-radius,2*radius,2*radius); // maxBounds.left = Math.min(maxBounds.left,b.left); // maxBounds.top = Math.min(maxBounds.top,b.top); // maxBounds.right = Math.max(maxBounds.right,b.right); // maxBounds.bottom = Math.max(maxBounds.bottom,b.bottom); // rb[j] = b; // } // } // } // renderData.elementBounds = rb; // renderData.bounds = maxBounds; // } /** * @private */ // override public function beginInterpolation(sourceRenderData:Object, // destRenderData:Object):Object // { // var idata:Object = initializeInterpolationData( // sourceRenderData.cache, destRenderData.cache, // { x: true, y: true }, itemType, // { sourceRenderData: sourceRenderData, // destRenderData: destRenderData }); // var interpolationRenderData:LineSeriesRenderData = LineSeriesRenderData(destRenderData.clone()); // interpolationRenderData.cache = idata.cache; // interpolationRenderData.filteredCache = idata.cache; // /* the segments in the renderdata have pointers back to the filetered cache. since we just replaced the filtered cache, we need to iterate through and // / update those */ // var segs:Array /* of LineSeriesSegment */ = interpolationRenderData.segments; // var n:int = segs.length; // for (var i:int = 0; i < n; i++) // { // segs[i].items = idata.cache; // } // transitionRenderData = interpolationRenderData; // return idata; // } /** * @private */ // override protected function getMissingInterpolationValues( // sourceProps:Object, srcCache:Array /* of LineSeriesItem */, // destProps:Object, destCache:Array /* of LineSeriesItem */, // index:Number, customData:Object):void // { // var cache:Array /* of LineSeriesItem */ = customData.sourceRenderData.cache; // var dstCache:Array /* of LineSeriesItem */ = customData.destRenderData.cache; // for (var p:String in sourceProps) // { // var src:Number = sourceProps[p]; // var dst:Number = destProps[p]; // var lastValidIndex:int = index; // if (isNaN(src)) // { // if (cache.length == 0) // { // src = (p == ""x"")? dstCache[index].x : unscaledHeight; // } // else // { // if (lastValidIndex >= cache.length) // lastValidIndex = cache.length-1; // while (lastValidIndex >= 0 && isNaN(cache[lastValidIndex][p])) // { // lastValidIndex--; // } // if (lastValidIndex >= 0) // src = cache[lastValidIndex][p] + .01 * (lastValidIndex - index); // if (isNaN(src)) // { // lastValidIndex = index+1; // var cachelen:int = cache.length; // while (lastValidIndex < cachelen && isNaN(cache[lastValidIndex][p])) // { // lastValidIndex++; // } // if (lastValidIndex < cachelen) // { // src = cache[lastValidIndex][p] + .01 * (lastValidIndex - index); // } // } // } // } // sourceProps[p] = src; // destProps[p] = dst; // } // } /** * @private */ // override public function dataToLocal(... dataValues):Point // { // var data:Object = {}; // var da:Array /* of Object */ = [ data ]; // var n:int = dataValues.length; // if (n > 0) // { // data[""d0""] = dataValues[0]; // dataTransform.getAxis(CartesianTransform.HORIZONTAL_AXIS). // mapCache(da, ""d0"", ""v0""); // } // if (n > 1) // { // data[""d1""] = dataValues[1]; // dataTransform.getAxis(CartesianTransform.VERTICAL_AXIS). // mapCache(da, ""d1"", ""v1""); // } // dataTransform.transformCache(da,""v0"",""s0"",""v1"",""s1""); // return new Point(data.s0 + this.x, // data.s1 + this.y); // } /** * @private */ // override public function localToData(v:Point):Array /* of Object */ // { // var values:Array /* of Object */ = dataTransform.invertTransform( // v.x - this.x, // v.y - this.y); // return values; // } /** * @private */ // override public function getItemsInRegion(r:Rectangle):Array /* of LineSeriesItem */ // { // if (interactive == false || !_renderData) // return []; // var arrItems:Array /* of LineSeriesItem */ = []; // var rc:Rectangle = new Rectangle(); // var localRectangle:Rectangle = new Rectangle(); // var n:uint = _renderData.filteredCache.length; // localRectangle.topLeft = globalToLocal(r.topLeft); // localRectangle.bottomRight = globalToLocal(r.bottomRight); // for (var i:int = 0; i < n; i++) // { // var v:LineSeriesItem = _renderData.filteredCache[i]; // if (localRectangle.contains(v.x,v.y)) // arrItems.push(v); // } // return arrItems; // } /** * @private */ // override protected function defaultFilterFunction(cache:Array /*of LineSeriesItem */ ):Array /*of LineeriesItem*/ // { // var filteredCache:Array /*of LineSeriesItem*/ = []; // var start:int; // var end:int = -1; // var n:int; // var i:int; // var v:LineSeriesItem; // if (filterDataValues == ""outsideRange"") // { // filteredCache = cache.concat(); // dataTransform.getAxis(CartesianTransform.HORIZONTAL_AXIS).filterCache(filteredCache,""xNumber"",""xFilter"") // dataTransform.getAxis(CartesianTransform.VERTICAL_AXIS).filterCache(filteredCache,""yNumber"",""yFilter""); //// since all nulls will end up out at the edges, we can safely strip this early // if (xField != """" && sortOnXField) // stripNaNs(filteredCache,""xFilter""); // _renderData.validPoints = filteredCache.length; // if (_interpolateValues == false) // { // n = filteredCache.length; // while (end 1) // _renderData.segments.push(new lineSegmentType(this,0,filteredCache,start,filteredCache.length-1)); // } // } // else if (filterDataValues == ""nulls"") // { // filteredCache = cache.concat(); ////since all nulls will end up out at the edges, we can safely strip this early // if (xField != """" && sortOnXField) // stripNaNs(filteredCache,""xNumber""); // _renderData.validPoints = filteredCache.length; // if (_interpolateValues == false) // { // n = filteredCache.length; // while (end 1) // _renderData.segments.push(new lineSegmentType(this,0,filteredCache,start,filteredCache.length-1)); // } // } // else if (filterDataValues == ""none"") // { // filteredCache = cache; // _renderData.segments.push(new lineSegmentType(this,0,filteredCache,start,filteredCache.length-1)); // } // return filteredCache; // } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * This method is to create line segments for the cache returned * by custom filter function */ // private function createLineSegments(filteredCache:Array /* of LineSeriesItem */):void // { // _renderData.validPoints = filteredCache.length; // if (_interpolateValues == false) // { // var start:int; // var end:int = -1; // var n:int = filteredCache.length; // var i:int; // var v:LineSeriesItem; // while (end 1) // _renderData.segments.push(new lineSegmentType(this,0,filteredCache,start,filteredCache.length-1)); // } // } /** * Customizes the item renderer instances that are used to represent the chart. This method is called automatically * whenever a new item renderer is needed while the chart is being rendered. You can override this method to add your own customization as necessary. * @param instance The new item renderer instance that is being created. * @param cache The InstanceCache that is used to manage the item renderer instances. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // protected function applyItemRendererProperties(instance:DisplayObject, // cache:InstanceCache):void // { // if (instance is ISimpleStyleClient) // ISimpleStyleClient(instance).styleName = this; // } /** * @private */ // private function formatDataTip(hd:HitData):String // { // var dt:String = """"; // var n:String = displayName; // if (n && n != """") // dt += """" + n + ""
""; // var xName:String = dataTransform.getAxis(CartesianTransform.HORIZONTAL_AXIS).displayName; // if (xName != """") // dt += """" + xName+ "": ""; // dt += dataTransform.getAxis(CartesianTransform.HORIZONTAL_AXIS).formatForScreen( // LineSeriesItem(hd.chartItem).xValue) + ""\\n""; // var yName:String = dataTransform.getAxis(CartesianTransform.VERTICAL_AXIS).displayName; // if (yName != """") // dt += """" + yName + "": ""; // dt += dataTransform.getAxis(CartesianTransform.VERTICAL_AXIS).formatForScreen( // LineSeriesItem(hd.chartItem).yValue) + ""\\n""; // return dt; // } /** * @private */ /* private function defaultFillFunction(element:LineSeriesItem,i:Number):IFill { if (_fillCount!=0) { return(GraphicsUtilities.fillFromStyle(_localFills[i % _fillCount])); } else return(GraphicsUtilities.fillFromStyle(getStyle(""fill""))); } */ /* private function reverseYValues(cache:Array):Array { var i:int = 0; var n:int = cache.length; for(i = 0; i < n ; i++) { cache[i][""yValue""] = -(cache[i][""yValue""]); } return cache; } */ /* private function reverseXValues(cache:Array):Array { var i:int = 0; var n:int = cache.length; for(i = 0; i < n ; i++) { cache[i][""xValue""] = -(cache[i][""xValue""]); } return cache; } */ } } //////////////////////////////////////////////////////////////////////////////// // // Helper class: LineSeriesLegendMarker // //////////////////////////////////////////////////////////////////////////////// /* import flash.display.Graphics; import mx.charts.series.LineSeries; import mx.graphics.IStroke; import mx.graphics.LinearGradientStroke; import mx.graphics.SolidColorStroke; import mx.skins.ProgrammaticSkin; */ /** * @private */ //class LineSeriesLegendMarker extends ProgrammaticSkin //{ //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * @private * Constructor. */ /* public function LineSeriesLegendMarker(element:LineSeries) { super(); _element = element; styleName = _element; } */ //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private */ //private var _element:LineSeries; //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ /* override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth,unscaledHeight); var fillStroke:IStroke = getStyle(""lineStroke""); var color:Number; if (fillStroke is SolidColorStroke) { color = SolidColorStroke(fillStroke).color; } else if (fillStroke is LinearGradientStroke) { var gb:LinearGradientStroke = LinearGradientStroke(fillStroke); if (gb.entries.length > 0) color = gb.entries[0].color; } var g:Graphics = graphics; g.clear(); g.moveTo(0, 0); g.lineStyle(0, 0, 0); g.beginFill(color); g.lineTo(width, 0); g.lineTo(width, height); g.lineTo(0, height); g.lineTo(0, 0); g.endFill(); } */ //} ",16259,True,2977.0356054155827,median "package flashx.textLayout.edit { import flash.desktop.Clipboard; import flash.desktop.ClipboardFormats; import flash.display.BitmapData; import flash.display.DisplayObject; import flash.display.InteractiveObject; import flash.display.Shape; import flash.display.Stage; import flash.errors.IllegalOperationError; import flash.events.ContextMenuEvent; import flash.events.Event; import flash.events.FocusEvent; import flash.events.IMEEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TextEvent; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.text.engine.TextLine; import flash.text.engine.TextLineValidity; import flash.text.engine.TextRotation; import flash.ui.ContextMenu; import flash.ui.Keyboard; import flash.ui.Mouse; import flash.ui.MouseCursor; import flash.ui.MouseCursorData; import flash.utils.getQualifiedClassName; import flashx.textLayout.compose.IFlowComposer; import flashx.textLayout.compose.TextFlowLine; import flashx.textLayout.compose.TextFlowTableBlock; import flashx.textLayout.container.ColumnState; import flashx.textLayout.container.ContainerController; import flashx.textLayout.elements.CellContainer; import flashx.textLayout.elements.CellCoordinates; import flashx.textLayout.elements.CellRange; import flashx.textLayout.elements.Configuration; import flashx.textLayout.elements.GlobalSettings; import flashx.textLayout.elements.ParagraphElement; import flashx.textLayout.elements.TableCellElement; import flashx.textLayout.elements.TableColElement; import flashx.textLayout.elements.TableElement; import flashx.textLayout.elements.TableRowElement; import flashx.textLayout.elements.TextFlow; import flashx.textLayout.elements.TextRange; import flashx.textLayout.events.FlowOperationEvent; import flashx.textLayout.events.SelectionEvent; import flashx.textLayout.formats.BlockProgression; import flashx.textLayout.formats.Direction; import flashx.textLayout.formats.ITextLayoutFormat; import flashx.textLayout.formats.TextLayoutFormat; import flashx.textLayout.operations.CopyOperation; import flashx.textLayout.operations.FlowOperation; import flashx.textLayout.tlf_internal; import flashx.textLayout.utils.NavigationUtil; use namespace tlf_internal; public class SelectionManager implements ISelectionManager { tlf_internal static var useTableSelectionCursors:Boolean = false; public static var SelectTable:String = ""selectTable""; public static var SelectTableRow:String = ""selectTableRow""; public static var SelectTableColumn:String = ""selectTableColumn""; private var _focusedSelectionFormat:SelectionFormat; private var _unfocusedSelectionFormat:SelectionFormat; private var _inactiveSelectionFormat:SelectionFormat; private var _focusedCellSelectionFormat:SelectionFormat; private var _unfocusedCellSelectionFormat:SelectionFormat; private var _inactiveCellSelectionFormat:SelectionFormat; private var _selFormatState:String = ""unfocused""; private var _isActive:Boolean; private var _textFlow:TextFlow; protected var _subManager:ISelectionManager; protected var _superManager:ISelectionManager; private var _currentTable:TableElement; private var _cellRange:CellRange; private var anchorMark:Mark; private var activeMark:Mark; private var _anchorCellPosition:CellCoordinates; private var _activeCellPosition:CellCoordinates; private var _pointFormat:ITextLayoutFormat; protected var ignoreNextTextEvent:Boolean = false; protected var allowOperationMerge:Boolean = false; private var _mouseOverSelectionArea:Boolean = false; private var marks:Array; private var cellMarks:Array; public var selectTableCursorPoints:Vector.; public var selectTableCursorDrawCommands:Vector.; public function SelectionManager() { this.marks = []; this.cellMarks = []; this.selectTableCursorPoints = new [1,3,11,3,11,0,12,0,16,4,12,8,11,8,11,5,1,5,1,3]; this.selectTableCursorDrawCommands = new [1,2,2,2,2,2,2,2,2,2]; super(); this._textFlow = null; this.anchorMark = this.createMark(); this.activeMark = this.createMark(); this.anchorCellPosition = this.createCellMark(); this.activeCellPosition = this.createCellMark(); this._pointFormat = null; this._isActive = false; Mouse.registerCursor(SelectTable,this.createSelectTableCursor()); Mouse.registerCursor(SelectTableRow,this.createSelectTableRowCursor()); Mouse.registerCursor(SelectTableColumn,this.createSelectTableColumnCursor()); } private static function computeSelectionIndexInContainer(textFlow:TextFlow, controller:ContainerController, localX:Number, localY:Number) : int { var result:int = 0; var rtline:TextFlowLine = null; var rtTextLine:TextLine = null; var bounds:Rectangle = null; var linePerpCoor:Number = NaN; var midPerpCoor:Number = NaN; var isLineBelow:Boolean = false; var prevPerpCoor:Number = NaN; var inPrevLine:Boolean = false; var textLine:TextLine = null; var startOnNextLineIfNecessary:Boolean = false; var lastAtom:int = 0; var lastAtomRect:Rectangle = null; var lastLinePosInPar:int = 0; var lastChar:String = null; var lineIndex:int = -1; var firstCharVisible:int = controller.absoluteStart; var length:int = controller.textLength; var bp:String = textFlow.computedFormat.blockProgression; var isTTB:* = bp == BlockProgression.RL; var isDirectionRTL:* = textFlow.computedFormat.direction == Direction.RTL; var perpCoor:Number = !!isTTB ? Number(localX) : Number(localY); var nearestColIdx:int = locateNearestColumn(controller,localX,localY,textFlow.computedFormat.blockProgression,textFlow.computedFormat.direction); var prevLineBounds:Rectangle = null; var previousLineIndex:int = -1; var lastLineIndexInColumn:int = -1; for(var testIndex:int = textFlow.flowComposer.numLines - 1; testIndex >= 0; testIndex--) { rtline = textFlow.flowComposer.getLineAt(testIndex); if(rtline.controller != controller || rtline.columnIndex != nearestColIdx) { if(lastLineIndexInColumn != -1) { lineIndex = testIndex + 1; break; } } else if(!(rtline.absoluteStart < firstCharVisible || rtline.absoluteStart >= firstCharVisible + length)) { rtTextLine = rtline.getTextLine(); if(!(rtTextLine == null || rtTextLine.parent == null)) { if(lastLineIndexInColumn == -1) { lastLineIndexInColumn = testIndex; } bounds = rtTextLine.getBounds(DisplayObject(controller.container)); linePerpCoor = !!isTTB ? Number(bounds.left) : Number(bounds.bottom); midPerpCoor = -1; if(prevLineBounds) { prevPerpCoor = !!isTTB ? Number(prevLineBounds.right) : Number(prevLineBounds.top); midPerpCoor = (linePerpCoor + prevPerpCoor) / 2; } isLineBelow = !!isTTB ? linePerpCoor > perpCoor : linePerpCoor < perpCoor; if(isLineBelow || testIndex == 0) { inPrevLine = midPerpCoor != -1 && (!!isTTB ? perpCoor < midPerpCoor : perpCoor > midPerpCoor); lineIndex = inPrevLine && testIndex != lastLineIndexInColumn ? int(testIndex + 1) : int(testIndex); break; } prevLineBounds = bounds; previousLineIndex = testIndex; } } } if(lineIndex == -1) { lineIndex = previousLineIndex; if(lineIndex == -1) { return -1; } } var textFlowLine:TextFlowLine = textFlow.flowComposer.getLineAt(lineIndex); if(textFlowLine is TextFlowTableBlock) { result = TextFlowTableBlock(textFlowLine).absoluteStart; } else { textLine = textFlowLine.getTextLine(true); localX -= textLine.x; localY -= textLine.y; startOnNextLineIfNecessary = false; lastAtom = -1; if(isDirectionRTL) { lastAtom = textLine.atomCount - 1; } else if(textFlowLine.absoluteStart + textFlowLine.textLength >= textFlowLine.paragraph.getAbsoluteStart() + textFlowLine.paragraph.textLength) { if(textLine.atomCount > 1) { lastAtom = textLine.atomCount - 2; } } else { lastLinePosInPar = textFlowLine.absoluteStart + textFlowLine.textLength - 1; lastChar = textLine.textBlock.content.rawText.charAt(lastLinePosInPar); if(lastChar == "" "") { if(textLine.atomCount > 1) { lastAtom = textLine.atomCount - 2; } } else { startOnNextLineIfNecessary = true; if(textLine.atomCount > 0) { lastAtom = textLine.atomCount - 1; } } } lastAtomRect = lastAtom > 0 ? textLine.getAtomBounds(lastAtom) : new Rectangle(0,0,0,0); if(!isTTB) { if(localX < 0) { localX = 0; } else if(localX > lastAtomRect.x + lastAtomRect.width) { if(startOnNextLineIfNecessary) { return textFlowLine.absoluteStart + textFlowLine.textLength - 1; } if(lastAtomRect.x + lastAtomRect.width > 0) { localX = lastAtomRect.x + lastAtomRect.width; } } } else if(localY < 0) { localY = 0; } else if(localY > lastAtomRect.y + lastAtomRect.height) { if(startOnNextLineIfNecessary) { return textFlowLine.absoluteStart + textFlowLine.textLength - 1; } if(lastAtomRect.y + lastAtomRect.height > 0) { localY = lastAtomRect.y + lastAtomRect.height; } } result = computeSelectionIndexInLine(textFlow,textLine,localX,localY); } return result != -1 ? int(result) : int(firstCharVisible + length); } private static function locateNearestColumn(container:ContainerController, localX:Number, localY:Number, wm:String, direction:String) : int { var curCol:Rectangle = null; var nextCol:Rectangle = null; var colIdx:int = 0; var columnState:ColumnState = container.columnState; while(colIdx < columnState.columnCount - 1) { curCol = columnState.getColumnAt(colIdx); nextCol = columnState.getColumnAt(colIdx + 1); if(curCol.contains(localX,localY)) { break; } if(nextCol.contains(localX,localY)) { colIdx++; break; } if(wm == BlockProgression.RL) { if(localY < curCol.top || localY < nextCol.top && Math.abs(curCol.bottom - localY) <= Math.abs(nextCol.top - localY)) { break; } if(localY > nextCol.top) { colIdx++; break; } } else if(direction == Direction.LTR) { if(localX < curCol.left || localX < nextCol.left && Math.abs(curCol.right - localX) <= Math.abs(nextCol.left - localX)) { break; } if(localX < nextCol.left) { colIdx++; break; } } else { if(localX > curCol.right || localX > nextCol.right && Math.abs(curCol.left - localX) <= Math.abs(nextCol.right - localX)) { break; } if(localX > nextCol.right) { colIdx++; break; } } colIdx++; } return colIdx; } private static function computeSelectionIndexInLine(textFlow:TextFlow, textLine:TextLine, localX:Number, localY:Number) : int { var paraSelectionIdx:int = 0; if(!(textLine.userData is TextFlowLine)) { return -1; } var rtline:TextFlowLine = TextFlowLine(textLine.userData); if(rtline.validity == TextLineValidity.INVALID) { return -1; } textLine = rtline.getTextLine(true); var isTTB:* = textFlow.computedFormat.blockProgression == BlockProgression.RL; var perpCoor:Number = !!isTTB ? Number(localX) : Number(localY); var pt:Point = new Point(); pt.x = localX; pt.y = localY; pt = textLine.localToGlobal(pt); var elemIdx:int = textLine.getAtomIndexAtPoint(pt.x,pt.y); if(elemIdx == -1) { pt.x = localX; pt.y = localY; if(pt.x < 0 || isTTB && perpCoor > textLine.ascent) { pt.x = 0; } if(pt.y < 0 || !isTTB && perpCoor > textLine.descent) { pt.y = 0; } pt = textLine.localToGlobal(pt); elemIdx = textLine.getAtomIndexAtPoint(pt.x,pt.y); } if(elemIdx == -1) { pt.x = localX; pt.y = localY; pt = textLine.localToGlobal(pt); if(textLine.parent) { pt = textLine.parent.globalToLocal(pt); } if(!isTTB) { return pt.x <= textLine.x ? int(rtline.absoluteStart) : int(rtline.absoluteStart + rtline.textLength - 1); } return pt.y <= textLine.y ? int(rtline.absoluteStart) : int(rtline.absoluteStart + rtline.textLength - 1); } var glyphRect:Rectangle = textLine.getAtomBounds(elemIdx); var leanRight:* = false; if(glyphRect) { if(isTTB && textLine.getAtomTextRotation(elemIdx) != TextRotation.ROTATE_0) { leanRight = localY > glyphRect.y + glyphRect.height / 2; } else { leanRight = localX > glyphRect.x + glyphRect.width / 2; } } if(textLine.getAtomBidiLevel(elemIdx) % 2 != 0) { paraSelectionIdx = !!leanRight ? int(textLine.getAtomTextBlockBeginIndex(elemIdx)) : int(textLine.getAtomTextBlockEndIndex(elemIdx)); } else { paraSelectionIdx = !!leanRight ? int(textLine.getAtomTextBlockEndIndex(elemIdx)) : int(textLine.getAtomTextBlockBeginIndex(elemIdx)); } return rtline.paragraph.getTextBlockAbsoluteStart(textLine.textBlock) + paraSelectionIdx; } private static function checkForDisplayed(container:DisplayObject) : Boolean { try { while(container) { if(!container.visible) { return false; } var container:DisplayObject = container.parent; if(container is Stage) { return true; } } } catch(e:Error) { return true; } return false; } private static function findController(textFlow:TextFlow, target:Object, currentTarget:Object, localPoint:Point) : ContainerController { var controller:ContainerController = null; var containerPoint:Point = null; var candidateLocalX:Number = NaN; var candidateLocalY:Number = NaN; var testController:ContainerController = null; var curContainerController:ContainerController = null; var bounds:Rectangle = null; var containerWidth:Number = NaN; var containerHeight:Number = NaN; var adjustX:Number = NaN; var adjustY:Number = NaN; var relDistanceX:Number = NaN; var relDistanceY:Number = NaN; var tempDist:Number = NaN; var localX:Number = localPoint.x; var localY:Number = localPoint.y; var globalPoint:Point = DisplayObject(target).localToGlobal(new Point(localX,localY)); for(var idx:int = 0; idx < textFlow.flowComposer.numControllers; idx++) { testController = textFlow.flowComposer.getControllerAt(idx); if(testController.container == target || testController.container == currentTarget) { controller = testController; break; } } if(controller) { if(target != controller.container) { containerPoint = DisplayObject(controller.container).globalToLocal(globalPoint); localPoint.x = containerPoint.x; localPoint.y = containerPoint.y; } return controller; } var controllerCandidate:ContainerController = null; var relDistance:Number = Number.MAX_VALUE; for(var containerIndex:int = 0; containerIndex < textFlow.flowComposer.numControllers; containerIndex++) { curContainerController = textFlow.flowComposer.getControllerAt(containerIndex); if(checkForDisplayed(curContainerController.container as DisplayObject)) { bounds = curContainerController.getContentBounds(); containerWidth = !!isNaN(curContainerController.compositionWidth) ? Number(curContainerController.getTotalPaddingLeft() + bounds.width) : Number(curContainerController.compositionWidth); containerHeight = !!isNaN(curContainerController.compositionHeight) ? Number(curContainerController.getTotalPaddingTop() + bounds.height) : Number(curContainerController.compositionHeight); containerPoint = DisplayObject(curContainerController.container).globalToLocal(globalPoint); adjustX = 0; adjustY = 0; if(curContainerController.hasScrollRect) { containerPoint.x -= adjustX = curContainerController.container.scrollRect.x; containerPoint.y -= adjustY = curContainerController.container.scrollRect.y; } if(containerPoint.x >= 0 && containerPoint.x <= containerWidth && containerPoint.y >= 0 && containerPoint.y <= containerHeight) { controllerCandidate = curContainerController; candidateLocalX = containerPoint.x + adjustX; candidateLocalY = containerPoint.y + adjustY; break; } relDistanceX = 0; relDistanceY = 0; if(containerPoint.x < 0) { relDistanceX = containerPoint.x; if(containerPoint.y < 0) { relDistanceY = containerPoint.y; } else if(containerPoint.y > containerHeight) { relDistanceY = containerPoint.y - containerHeight; } } else if(containerPoint.x > containerWidth) { relDistanceX = containerPoint.x - containerWidth; if(containerPoint.y < 0) { relDistanceY = containerPoint.y; } else if(containerPoint.y > containerHeight) { relDistanceY = containerPoint.y - containerHeight; } } else if(containerPoint.y < 0) { relDistanceY = -containerPoint.y; } else { relDistanceY = containerPoint.y - containerHeight; } tempDist = relDistanceX * relDistanceX + relDistanceY * relDistanceY; if(tempDist <= relDistance) { relDistance = tempDist; controllerCandidate = curContainerController; candidateLocalX = containerPoint.x + adjustX; candidateLocalY = containerPoint.y + adjustY; } } } localPoint.x = candidateLocalX; localPoint.y = candidateLocalY; return controllerCandidate; } tlf_internal static function computeCellCoordinates(textFlow:TextFlow, target:Object, currentTarget:Object, localX:Number, localY:Number) : CellCoordinates { var rslt:CellCoordinates = null; var containerPoint:Point = null; var cell:TableCellElement = null; if(target is TextLine) { return null; } if(target is CellContainer) { cell = (target as CellContainer).element; return new CellCoordinates(cell.rowIndex,cell.colIndex,cell.getTable()); } var localPoint:Point = new Point(localX,localY); var controller:ContainerController = findController(textFlow,target,currentTarget,localPoint); if(!controller) { return null; } return controller.findCellAtPosition(localPoint); } tlf_internal static function computeSelectionIndex(textFlow:TextFlow, target:Object, currentTarget:Object, localX:Number, localY:Number) : int { var containerPoint:Point = null; var tfl:TextFlowLine = null; var para:ParagraphElement = null; var localPoint:Point = null; var controller:ContainerController = null; var rslt:int = 0; var useTargetedTextLine:Boolean = false; if(target is TextLine) { tfl = TextLine(target).userData as TextFlowLine; if(tfl) { para = tfl.paragraph; if(para.getTextFlow() == textFlow) { useTargetedTextLine = true; } } } if(useTargetedTextLine) { rslt = computeSelectionIndexInLine(textFlow,TextLine(target),localX,localY); } else { localPoint = new Point(localX,localY); controller = findController(textFlow,target,currentTarget,localPoint); rslt = !!controller ? int(computeSelectionIndexInContainer(textFlow,controller,localPoint.x,localPoint.y)) : -1; } if(rslt >= textFlow.textLength) { rslt = textFlow.textLength - 1; } return rslt; } public function get currentTable() : TableElement { return this._currentTable; } public function set currentTable(table:TableElement) : void { this._currentTable = table; } public function hasCellRangeSelection() : Boolean { if(!this._currentTable) { return false; } if(!this._cellRange) { return false; } return true; } public function selectCellTextFlow(cell:TableCellElement) : void { var selectionManager:SelectionManager = null; if(cell && cell.table) { selectionManager = cell.textFlow.interactionManager as SelectionManager; this.clear(); if(selectionManager) { selectionManager.currentTable = cell.table; selectionManager.selectAll(); selectionManager.setFocus(); } } } public function selectCell(cell:TableCellElement) : void { var beginCoordinates:CellCoordinates = null; var endCoordinates:CellCoordinates = null; if(cell) { beginCoordinates = new CellCoordinates(cell.rowIndex,cell.colIndex); endCoordinates = new CellCoordinates(cell.rowIndex,cell.colIndex); if(beginCoordinates.isValid()) { this.selectCellRange(beginCoordinates,endCoordinates); } } } public function selectCellAt(table:TableElement, rowIndex:int, colIndex:int) : void { var cell:TableCellElement = table.getCellAt(rowIndex,colIndex); if(cell) { this.selectCell(cell); } } public function selectCells(cells:Vector.) : void { var cell:TableCellElement = null; var table:TableElement = null; var col:int = 0; var row:int = 0; var startX:int = int.MAX_VALUE; var startY:int = int.MAX_VALUE; var endX:int = int.MIN_VALUE; var endY:int = int.MIN_VALUE; for each(cell in cells) { if(cell) { if(table == null) { table = cell.getTable(); } col = cell.colIndex; row = cell.rowIndex; if(col < startX) { startX = col; } if(col > endX) { endX = col; } if(row < startY) { startY = row; } if(row > endY) { endY = row; } } } if(startX <= endX && startY <= endY) { this.selectCellRange(new CellCoordinates(startY,startX,table),new CellCoordinates(endY,endX,table)); } } public function selectRow(row:TableRowElement) : void { var beginCoordinates:CellCoordinates = null; var endCoordinates:CellCoordinates = null; if(row) { beginCoordinates = new CellCoordinates(row.rowIndex,0); endCoordinates = new CellCoordinates(row.rowIndex,row.numCells); if(beginCoordinates.isValid() && endCoordinates.isValid()) { this.selectCellRange(beginCoordinates,endCoordinates); } } } public function selectRowAt(table:TableElement, index:int) : void { var row:TableRowElement = !!table ? table.getRowAt(index) : null; if(row) { this.selectRow(row); } } public function selectRows(rows:Array) : void { var table:TableElement = null; var cell:TableCellElement = null; var i:int = 0; var row:TableRowElement = null; var cells:Vector. = new Vector.(); if(rows && rows.length) { while(i < rows.length) { row = rows[i] as TableRowElement; if(row) { for each(cell in row.cells) { cells.push(cell); } } i++; } this.selectCells(cells); } } public function selectColumn(column:TableColElement) : void { var table:TableElement = column.table; if(column && table) { this.selectCells(table.getCellsForColumn(column)); } } public function selectColumnAt(table:TableElement, index:int) : void { var column:TableColElement = table.getColumnAt(index); if(column && table) { return this.selectColumn(column); } } public function selectColumns(columns:Array) : void { var cell:TableCellElement = null; var i:int = 0; var column:TableColElement = null; var cells:Vector. = new Vector.(); if(columns && columns.length) { while(i < columns.length) { column = columns[i] as TableColElement; if(column) { for each(cell in column.cells) { cells.push(cell); } } i++; } this.selectCells(cells); } } public function selectTable(table:TableElement) : void { var startCoords:CellCoordinates = null; var endCoords:CellCoordinates = null; if(table) { startCoords = new CellCoordinates(0,0,table); endCoords = new CellCoordinates(table.numRows - 1,table.numColumns - 1,table); this.selectCellRange(startCoords,endCoords); } } public function selectCellRange(anchorCoords:CellCoordinates, activeCoords:CellCoordinates) : void { var blocks:Vector. = null; var block:TextFlowTableBlock = null; var controller:ContainerController = null; if(this.selectionType == SelectionType.TEXT) { this.clear(); } this.clearCellSelections(); if(anchorCoords && activeCoords) { this._cellRange = new CellRange(this._currentTable,anchorCoords,activeCoords); this.activeCellPosition = activeCoords; blocks = this._currentTable.getTableBlocksInRange(anchorCoords,activeCoords); for each(block in blocks) { block.controller.clearSelectionShapes(); block.controller.addCellSelectionShapes(this.currentCellSelectionFormat.rangeColor,block,anchorCoords,activeCoords); } if(this.subManager) { this.subManager.selectRange(-1,-1); this.subManager = null; } } else { this._cellRange = null; this.activeCellPosition.column = -1; this.activeCellPosition.row = -1; } this.selectionChanged(); } public function getCellRange() : CellRange { return this._cellRange; } public function setCellRange(range:CellRange) : void { this.selectCellRange(range.anchorCoordinates,range.activeCoordinates); } protected function get pointFormat() : ITextLayoutFormat { return this._pointFormat; } public function getSelectionState() : SelectionState { if(this.subManager) { return this.subManager.getSelectionState(); } return new SelectionState(this._textFlow,this.anchorMark.position,this.activeMark.position,this.pointFormat,this._cellRange); } public function setSelectionState(sel:SelectionState) : void { this.internalSetSelection(sel.textFlow,sel.anchorPosition,sel.activePosition,sel.pointFormat); } public function hasSelection() : Boolean { return this.selectionType == SelectionType.TEXT; } public function hasAnySelection() : Boolean { return this.selectionType != SelectionType.NONE; } public function get selectionType() : String { if(this.anchorMark.position != -1) { return SelectionType.TEXT; } if(this.anchorCellPosition.isValid()) { return SelectionType.CELLS; } return SelectionType.NONE; } public function isRangeSelection() : Boolean { return this.anchorMark.position != -1 && this.anchorMark.position != this.activeMark.position; } public function get textFlow() : TextFlow { return this._textFlow; } public function set textFlow(value:TextFlow) : void { if(this._textFlow != value) { if(this._textFlow) { this.flushPendingOperations(); } this.clear(); this.clearCellSelections(); this._cellRange = null; if(!value) { this.setMouseCursor(MouseCursor.AUTO); } this._textFlow = value; if(this._textFlow && this._textFlow.interactionManager != this) { this._textFlow.interactionManager = this; } } } public function get editingMode() : String { return EditingMode.READ_SELECT; } public function get windowActive() : Boolean { return this._selFormatState != SelectionFormatState.INACTIVE; } public function get focused() : Boolean { return this._selFormatState == SelectionFormatState.FOCUSED; } public function get currentSelectionFormat() : SelectionFormat { if(this._selFormatState == SelectionFormatState.UNFOCUSED) { return this.unfocusedSelectionFormat; } if(this._selFormatState == SelectionFormatState.INACTIVE) { return this.inactiveSelectionFormat; } return this.focusedSelectionFormat; } public function get currentCellSelectionFormat() : SelectionFormat { if(this._selFormatState == SelectionFormatState.UNFOCUSED) { return this.unfocusedCellSelectionFormat; } if(this._selFormatState == SelectionFormatState.INACTIVE) { return this.inactiveCellSelectionFormat; } return this.focusedCellSelectionFormat; } public function set focusedSelectionFormat(val:SelectionFormat) : void { this._focusedSelectionFormat = val; if(this._selFormatState == SelectionFormatState.FOCUSED) { this.refreshSelection(); } } public function get focusedSelectionFormat() : SelectionFormat { return !!this._focusedSelectionFormat ? this._focusedSelectionFormat : (!!this._textFlow ? this._textFlow.configuration.focusedSelectionFormat : null); } public function set unfocusedSelectionFormat(val:SelectionFormat) : void { this._unfocusedSelectionFormat = val; if(this._selFormatState == SelectionFormatState.UNFOCUSED) { this.refreshSelection(); } } public function get unfocusedSelectionFormat() : SelectionFormat { return !!this._unfocusedSelectionFormat ? this._unfocusedSelectionFormat : (!!this._textFlow ? this._textFlow.configuration.unfocusedSelectionFormat : null); } public function set inactiveSelectionFormat(val:SelectionFormat) : void { this._inactiveSelectionFormat = val; if(this._selFormatState == SelectionFormatState.INACTIVE) { this.refreshSelection(); } } public function get inactiveSelectionFormat() : SelectionFormat { return !!this._inactiveSelectionFormat ? this._inactiveSelectionFormat : (!!this._textFlow ? this._textFlow.configuration.inactiveSelectionFormat : null); } public function set focusedCellSelectionFormat(val:SelectionFormat) : void { this._focusedCellSelectionFormat = val; if(this._selFormatState == SelectionFormatState.FOCUSED) { this.refreshSelection(); } } public function get focusedCellSelectionFormat() : SelectionFormat { return !!this._focusedCellSelectionFormat ? this._focusedCellSelectionFormat : (!!this._textFlow ? this._textFlow.configuration.focusedSelectionFormat : null); } public function set unfocusedCellSelectionFormat(val:SelectionFormat) : void { this._unfocusedCellSelectionFormat = val; if(this._selFormatState == SelectionFormatState.UNFOCUSED) { this.refreshSelection(); } } public function get unfocusedCellSelectionFormat() : SelectionFormat { return !!this._unfocusedCellSelectionFormat ? this._unfocusedCellSelectionFormat : (!!this._textFlow ? this._textFlow.configuration.unfocusedSelectionFormat : null); } public function set inactiveCellSelectionFormat(val:SelectionFormat) : void { this._inactiveCellSelectionFormat = val; if(this._selFormatState == SelectionFormatState.INACTIVE) { this.refreshSelection(); } } public function get inactiveCellSelectionFormat() : SelectionFormat { return !!this._inactiveCellSelectionFormat ? this._inactiveCellSelectionFormat : (!!this._textFlow ? this._textFlow.configuration.inactiveSelectionFormat : null); } tlf_internal function get selectionFormatState() : String { return this._selFormatState; } tlf_internal function setSelectionFormatState(selFormatState:String) : void { var oldSelectionFormat:SelectionFormat = null; var newSelectionFormat:SelectionFormat = null; if(selFormatState != this._selFormatState) { oldSelectionFormat = this.currentSelectionFormat; this._selFormatState = selFormatState; newSelectionFormat = this.currentSelectionFormat; if(!newSelectionFormat.equals(oldSelectionFormat)) { this.refreshSelection(); } } } tlf_internal function cloneSelectionFormatState(oldISelectionManager:ISelectionManager) : void { var oldSelectionManager:SelectionManager = oldISelectionManager as SelectionManager; if(oldSelectionManager) { this._isActive = oldSelectionManager._isActive; this._mouseOverSelectionArea = oldSelectionManager._mouseOverSelectionArea; this.setSelectionFormatState(oldSelectionManager.selectionFormatState); } } private function selectionPoint(currentTarget:Object, target:InteractiveObject, localX:Number, localY:Number, extendSelection:Boolean = false) : SelectionState { if(!this._textFlow) { return null; } if(!this.hasSelection()) { extendSelection = false; } var begIdx:int = this.anchorMark.position; var endIdx:int = this.activeMark.position; endIdx = computeSelectionIndex(this._textFlow,target,currentTarget,localX,localY); if(endIdx == -1) { return null; } endIdx = Math.min(endIdx,this._textFlow.textLength - 1); if(!extendSelection) { begIdx = endIdx; } if(begIdx == endIdx) { begIdx = NavigationUtil.updateStartIfInReadOnlyElement(this._textFlow,begIdx); endIdx = NavigationUtil.updateEndIfInReadOnlyElement(this._textFlow,endIdx); } else { endIdx = NavigationUtil.updateEndIfInReadOnlyElement(this._textFlow,endIdx); } return new SelectionState(this.textFlow,begIdx,endIdx); } public function setFocus() : void { if(!this._textFlow) { return; } if(this._textFlow.flowComposer) { this._textFlow.flowComposer.setFocus(this.activePosition,false); } this.setSelectionFormatState(SelectionFormatState.FOCUSED); } protected function setMouseCursor(cursor:String) : void { Mouse.cursor = Configuration.getCursorString(this.textFlow.configuration,cursor); } public function get anchorPosition() : int { return this.anchorMark.position; } public function get activePosition() : int { return this.activeMark.position; } public function get absoluteStart() : int { return this.anchorMark.position < this.activeMark.position ? int(this.anchorMark.position) : int(this.activeMark.position); } public function get absoluteEnd() : int { return this.anchorMark.position > this.activeMark.position ? int(this.anchorMark.position) : int(this.activeMark.position); } public function selectAll() : void { var lastSelectablePos:int = 0; if(this.subManager) { this.subManager.selectAll(); } else { lastSelectablePos = this._textFlow.textLength > 0 ? int(this._textFlow.textLength - 1) : 0; this.selectRange(0,lastSelectablePos); } } public function selectRange(anchorPosition:int, activePosition:int) : void { var cell:TableCellElement = null; this.flushPendingOperations(); if(this.subManager && (anchorPosition != -1 || activePosition != -1)) { this.subManager.selectRange(-1,-1); this.subManager = null; } if(this.textFlow.nestedInTable()) { cell = this.textFlow.parentElement as TableCellElement; this.superManager = cell.getTextFlow().interactionManager; this.superManager.currentTable = cell.getTable(); this.superManager.deselect(); this.superManager.anchorCellPosition.column = cell.colIndex; this.superManager.anchorCellPosition.row = cell.rowIndex; this.superManager.subManager = this; } if(anchorPosition != this.anchorMark.position || activePosition != this.activeMark.position) { this.clearSelectionShapes(); this.clearCellSelections(); this._cellRange = null; this.internalSetSelection(this._textFlow,anchorPosition,activePosition,this._pointFormat); this.selectionChanged(); this.allowOperationMerge = false; } } public function selectFirstPosition() : void { this.selectRange(0,0); } public function selectLastPosition() : void { this.selectRange(int.MAX_VALUE,int.MAX_VALUE); } public function deselect() : void { if(this.hasAnySelection()) { this.clearSelectionShapes(); this.clearCellSelections(); this.addSelectionShapes(); } this.selectRange(-1,-1); this._cellRange = null; } private function internalSetSelection(root:TextFlow, anchorPosition:int, activePosition:int, format:ITextLayoutFormat = null) : void { this._textFlow = root; if(anchorPosition < 0 || activePosition < 0) { anchorPosition = -1; activePosition = -1; } else if(this.subManager) { this.subManager.flushPendingOperations(); this.subManager = null; } var lastSelectablePos:int = this._textFlow.textLength > 0 ? int(this._textFlow.textLength - 1) : 0; if(anchorPosition != -1 && activePosition != -1) { if(anchorPosition > lastSelectablePos) { anchorPosition = lastSelectablePos; } if(activePosition > lastSelectablePos) { activePosition = lastSelectablePos; } } this._pointFormat = format; this.anchorMark.position = anchorPosition; this.activeMark.position = activePosition; } private function clear() : void { if(this.hasSelection()) { this.flushPendingOperations(); this.clearSelectionShapes(); this.internalSetSelection(this._textFlow,-1,-1); this.selectionChanged(); this.allowOperationMerge = false; } } private function clearCellSelections() : void { var blocks:Vector. = null; var block:TextFlowTableBlock = null; var controller:ContainerController = null; if(this._cellRange) { blocks = this._cellRange.table.getTableBlocksInRange(this._cellRange.anchorCoordinates,this._cellRange.activeCoordinates); for each(block in blocks) { if(controller != block.controller) { block.controller.clearSelectionShapes(); } controller = block.controller; } } if(block) { block.controller.clearSelectionShapes(); } } private function addSelectionShapes() : void { var containerIter:int = 0; if(this._textFlow.flowComposer) { this.internalSetSelection(this._textFlow,this.anchorMark.position,this.activeMark.position,this._pointFormat); if(this.currentSelectionFormat && (this.absoluteStart == this.absoluteEnd && this.currentSelectionFormat.pointAlpha != 0 || this.absoluteStart != this.absoluteEnd && this.currentSelectionFormat.rangeAlpha != 0)) { containerIter = 0; while(containerIter < this._textFlow.flowComposer.numControllers) { this._textFlow.flowComposer.getControllerAt(containerIter++).addSelectionShapes(this.currentSelectionFormat,this.absoluteStart,this.absoluteEnd); } } } } private function clearSelectionShapes() : void { var containerIter:int = 0; var flowComposer:IFlowComposer = !!this._textFlow ? this._textFlow.flowComposer : null; if(flowComposer) { containerIter = 0; while(containerIter < flowComposer.numControllers) { flowComposer.getControllerAt(containerIter++).clearSelectionShapes(); } } } public function refreshSelection() : void { if(this.hasAnySelection()) { this.clearSelectionShapes(); this.clearCellSelections(); this.addSelectionShapes(); } } public function clearSelection() : void { if(this.hasAnySelection()) { this.clearSelectionShapes(); this.clearCellSelections(); } } tlf_internal function selectionChanged(doDispatchEvent:Boolean = true, resetPointFormat:Boolean = true) : void { if(resetPointFormat) { this._pointFormat = null; } if(doDispatchEvent && this._textFlow) { if(this.textFlow.parentElement && this.textFlow.parentElement.getTextFlow()) { this.textFlow.parentElement.getTextFlow().dispatchEvent(new SelectionEvent(SelectionEvent.SELECTION_CHANGE,false,false,!!this.hasSelection() ? this.getSelectionState() : null)); } else { this.textFlow.dispatchEvent(new SelectionEvent(SelectionEvent.SELECTION_CHANGE,false,false,!!this.hasSelection() ? this.getSelectionState() : null)); } } } tlf_internal function setNewSelectionPoint(currentTarget:Object, target:InteractiveObject, localX:Number, localY:Number, extendSelection:Boolean = false) : Boolean { var selState:SelectionState = this.selectionPoint(currentTarget,target,localX,localY,extendSelection); if(selState == null) { return false; } if(selState.anchorPosition != this.anchorMark.position || selState.activePosition != this.activeMark.position) { this.selectRange(selState.anchorPosition,selState.activePosition); return true; } return false; } public function mouseDownHandler(event:MouseEvent) : void { var coords:CellCoordinates = null; if(this.subManager) { this.subManager.selectRange(-1,-1); } var cell:TableCellElement = this._textFlow.parentElement as TableCellElement; if(!cell) { coords = computeCellCoordinates(this.textFlow,event.target,event.currentTarget,event.localX,event.localY); } if(cell || coords) { if(coords) { cell = coords.table.findCell(coords); } this.superManager = cell.getTextFlow().interactionManager; if(event.shiftKey && cell.getTable() == this.superManager.currentTable) { this.flushPendingOperations(); coords = new CellCoordinates(cell.rowIndex,cell.colIndex); if(!CellCoordinates.areEqual(coords,this.superManager.anchorCellPosition) || this.superManager.activeCellPosition.isValid()) { this.superManager.selectCellRange(this.superManager.anchorCellPosition,coords); this.superManager.subManager = null; this.allowOperationMerge = false; event.stopPropagation(); return; } } if(this.superManager == this) { if(cell.textFlow.interactionManager) { cell.textFlow.interactionManager.mouseDownHandler(event); } return; } this.superManager.currentTable = cell.getTable(); this.superManager.deselect(); this.superManager.anchorCellPosition.column = cell.colIndex; this.superManager.anchorCellPosition.row = cell.rowIndex; this.superManager.subManager = this; } this.handleMouseEventForSelection(event,event.shiftKey,cell != null); } public function mouseMoveHandler(event:MouseEvent) : void { var cell:TableCellElement = null; var cellCoords:CellCoordinates = null; var coords:CellCoordinates = null; var wmode:String = this.textFlow.computedFormat.blockProgression; if(wmode != BlockProgression.RL) { this.setMouseCursor(MouseCursor.IBEAM); } if(event.buttonDown) { cell = this._textFlow.parentElement as TableCellElement; if(cell) { do { cellCoords = new CellCoordinates(cell.rowIndex,cell.colIndex,cell.getTable()); coords = computeCellCoordinates(cell.getTextFlow(),event.target,event.currentTarget,event.localX,event.localY); if(!coords) { break; } if(CellCoordinates.areEqual(cellCoords,coords) && (!this.superManager.activeCellPosition.isValid() || CellCoordinates.areEqual(coords,this.superManager.activeCellPosition))) { break; } if(coords.table != cellCoords.table) { break; } this.superManager = cell.getTextFlow().interactionManager; if(!CellCoordinates.areEqual(coords,this.superManager.activeCellPosition)) { this.allowOperationMerge = false; this.superManager.selectCellRange(this.superManager.anchorCellPosition,coords); event.stopPropagation(); return; } } while(0); } if(this.superManager && this.superManager.getCellRange()) { return; } this.handleMouseEventForSelection(event,true,this._textFlow.parentElement != null); } } tlf_internal function handleMouseEventForSelection(event:MouseEvent, allowExtend:Boolean, stopPropogate:Boolean = false) : void { var startSelectionActive:Boolean = this.hasSelection(); if(this.setNewSelectionPoint(event.currentTarget,event.target as InteractiveObject,event.localX,event.localY,startSelectionActive && allowExtend)) { if(startSelectionActive) { this.clearSelectionShapes(); } if(this.hasSelection()) { this.addSelectionShapes(); } } this.allowOperationMerge = false; if(stopPropogate) { event.stopPropagation(); } } public function mouseUpHandler(event:MouseEvent) : void { if(!this._mouseOverSelectionArea) { this.setMouseCursor(MouseCursor.AUTO); } } private function atBeginningWordPos(activePara:ParagraphElement, pos:int) : Boolean { if(pos == 0) { return true; } var paraEnd:Number = activePara.getAbsoluteStart() + activePara.textLength; activePara.getTextFlow().flowComposer.composeToPosition(paraEnd); var nextPos:int = activePara.findNextWordBoundary(pos); nextPos = activePara.findPreviousWordBoundary(nextPos); return pos == nextPos; } public function mouseDoubleClickHandler(event:MouseEvent) : void { var newActiveIndex:int = 0; var newAnchorIndex:int = 0; var anchorPara:ParagraphElement = null; var anchorParaStart:int = 0; if(!this.hasSelection()) { return; } var activePara:ParagraphElement = this._textFlow.findAbsoluteParagraph(this.activeMark.position); var activeParaStart:int = activePara.getAbsoluteStart(); if(this.anchorMark.position <= this.activeMark.position) { newActiveIndex = activePara.findNextWordBoundary(this.activeMark.position - activeParaStart) + activeParaStart; } else { newActiveIndex = activePara.findPreviousWordBoundary(this.activeMark.position - activeParaStart) + activeParaStart; } if(newActiveIndex == activeParaStart + activePara.textLength) { newActiveIndex--; } if(event.shiftKey) { newAnchorIndex = this.anchorMark.position; } else { anchorPara = this._textFlow.findAbsoluteParagraph(this.anchorMark.position); anchorParaStart = anchorPara.getAbsoluteStart(); if(this.atBeginningWordPos(anchorPara,this.anchorMark.position - anchorParaStart)) { newAnchorIndex = this.anchorMark.position; } else { if(this.anchorMark.position <= this.activeMark.position) { newAnchorIndex = anchorPara.findPreviousWordBoundary(this.anchorMark.position - anchorParaStart) + anchorParaStart; } else { newAnchorIndex = anchorPara.findNextWordBoundary(this.anchorMark.position - anchorParaStart) + anchorParaStart; } if(newAnchorIndex == anchorParaStart + anchorPara.textLength) { newAnchorIndex--; } } } if(newAnchorIndex != this.anchorMark.position || newActiveIndex != this.activeMark.position) { this.internalSetSelection(this._textFlow,newAnchorIndex,newActiveIndex,null); this.selectionChanged(); this.clearSelectionShapes(); if(this.hasSelection()) { this.addSelectionShapes(); } } this.allowOperationMerge = false; } public function mouseOverHandler(event:MouseEvent) : void { var cell:TableCellElement = null; var leftEdge:int = 0; var topEdge:int = 0; var globalPoint:Point = null; var cellContainer:CellContainer = null; var point:Point = null; var cellContainerPoint:Point = null; this._mouseOverSelectionArea = true; var wmode:String = this.textFlow.computedFormat.blockProgression; if(wmode != BlockProgression.RL) { cell = this._textFlow.parentElement as TableCellElement; if(cell) { leftEdge = 5; topEdge = 5; globalPoint = new Point(event.stageX,event.stageY); cellContainer = event.currentTarget as CellContainer; if(cellContainer) { cellContainerPoint = cellContainer.localToGlobal(new Point()); point = globalPoint.subtract(cellContainerPoint); } if(tlf_internal::useTableSelectionCursors) { if(cell.colIndex == 0 && point.x < leftEdge && point.y > topEdge) { event.stopPropagation(); event.stopImmediatePropagation(); this.setMouseCursor(SelectTableRow); } else if(cell.rowIndex == 0 && cell.colIndex == 0 && point.x < leftEdge && point.y < topEdge) { event.stopPropagation(); event.stopImmediatePropagation(); this.setMouseCursor(SelectTable); } else if(cell.rowIndex == 0 && point.x > leftEdge && point.y < topEdge) { event.stopPropagation(); event.stopImmediatePropagation(); this.setMouseCursor(SelectTableColumn); } else { this.setMouseCursor(MouseCursor.IBEAM); } } else { this.setMouseCursor(MouseCursor.IBEAM); } } else { this.setMouseCursor(MouseCursor.IBEAM); } } else { this.setMouseCursor(MouseCursor.AUTO); } } public function mouseOutHandler(event:MouseEvent) : void { this._mouseOverSelectionArea = false; this.setMouseCursor(MouseCursor.AUTO); } public function focusInHandler(event:FocusEvent) : void { this._isActive = true; this.setSelectionFormatState(SelectionFormatState.FOCUSED); } public function focusOutHandler(event:FocusEvent) : void { if(this._isActive) { this.setSelectionFormatState(SelectionFormatState.UNFOCUSED); } } public function activateHandler(event:Event) : void { if(!this._isActive) { this._isActive = true; this.setSelectionFormatState(SelectionFormatState.UNFOCUSED); } } public function deactivateHandler(event:Event) : void { if(this._isActive) { this._isActive = false; this.setSelectionFormatState(SelectionFormatState.INACTIVE); } } public function doOperation(op:FlowOperation) : void { var opError:Error = null; var opEvent:FlowOperationEvent = new FlowOperationEvent(FlowOperationEvent.FLOW_OPERATION_BEGIN,false,true,op,0,null); this.textFlow.dispatchEvent(opEvent); if(!opEvent.isDefaultPrevented()) { var op:FlowOperation = opEvent.operation; if(!(op is CopyOperation)) { throw new IllegalOperationError(GlobalSettings.resourceStringFunction(""illegalOperation"",[getQualifiedClassName(op)])); } opError = null; try { op.doOperation(); } catch(e:Error) { opError = e; } opEvent = new FlowOperationEvent(FlowOperationEvent.FLOW_OPERATION_END,false,true,op,0,opError); this.textFlow.dispatchEvent(opEvent); opError = !!opEvent.isDefaultPrevented() ? null : opEvent.error; if(opError) { throw opError; } this.textFlow.dispatchEvent(new FlowOperationEvent(FlowOperationEvent.FLOW_OPERATION_COMPLETE,false,false,op,0,null)); } } public function editHandler(event:Event) : void { switch(event.type) { case Event.COPY: this.flushPendingOperations(); this.doOperation(new CopyOperation(this.getSelectionState())); break; case Event.SELECT_ALL: this.flushPendingOperations(); this.selectAll(); this.refreshSelection(); } } private function handleLeftArrow(event:KeyboardEvent) : SelectionState { var selState:SelectionState = this.getSelectionState(); if(this._textFlow.computedFormat.blockProgression != BlockProgression.RL) { if(this._textFlow.computedFormat.direction == Direction.LTR) { if(event.ctrlKey || event.altKey) { NavigationUtil.previousWord(selState,event.shiftKey); } else { NavigationUtil.previousCharacter(selState,event.shiftKey); } } else if(event.ctrlKey || event.altKey) { NavigationUtil.nextWord(selState,event.shiftKey); } else { NavigationUtil.nextCharacter(selState,event.shiftKey); } } else if(event.altKey) { NavigationUtil.endOfParagraph(selState,event.shiftKey); } else if(event.ctrlKey) { NavigationUtil.endOfDocument(selState,event.shiftKey); } else { NavigationUtil.nextLine(selState,event.shiftKey); } return selState; } private function handleUpArrow(event:KeyboardEvent) : SelectionState { var selState:SelectionState = this.getSelectionState(); if(this._textFlow.computedFormat.blockProgression != BlockProgression.RL) { if(event.altKey) { NavigationUtil.startOfParagraph(selState,event.shiftKey); } else if(event.ctrlKey) { NavigationUtil.startOfDocument(selState,event.shiftKey); } else { NavigationUtil.previousLine(selState,event.shiftKey); } } else if(this._textFlow.computedFormat.direction == Direction.LTR) { if(event.ctrlKey || event.altKey) { NavigationUtil.previousWord(selState,event.shiftKey); } else { NavigationUtil.previousCharacter(selState,event.shiftKey); } } else if(event.ctrlKey || event.altKey) { NavigationUtil.nextWord(selState,event.shiftKey); } else { NavigationUtil.nextCharacter(selState,event.shiftKey); } return selState; } private function handleRightArrow(event:KeyboardEvent) : SelectionState { var selState:SelectionState = this.getSelectionState(); if(this._textFlow.computedFormat.blockProgression != BlockProgression.RL) { if(this._textFlow.computedFormat.direction == Direction.LTR) { if(event.ctrlKey || event.altKey) { NavigationUtil.nextWord(selState,event.shiftKey); } else { NavigationUtil.nextCharacter(selState,event.shiftKey); } } else if(event.ctrlKey || event.altKey) { NavigationUtil.previousWord(selState,event.shiftKey); } else { NavigationUtil.previousCharacter(selState,event.shiftKey); } } else if(event.altKey) { NavigationUtil.startOfParagraph(selState,event.shiftKey); } else if(event.ctrlKey) { NavigationUtil.startOfDocument(selState,event.shiftKey); } else { NavigationUtil.previousLine(selState,event.shiftKey); } return selState; } private function handleDownArrow(event:KeyboardEvent) : SelectionState { var selState:SelectionState = this.getSelectionState(); if(this._textFlow.computedFormat.blockProgression != BlockProgression.RL) { if(event.altKey) { NavigationUtil.endOfParagraph(selState,event.shiftKey); } else if(event.ctrlKey) { NavigationUtil.endOfDocument(selState,event.shiftKey); } else { NavigationUtil.nextLine(selState,event.shiftKey); } } else if(this._textFlow.computedFormat.direction == Direction.LTR) { if(event.ctrlKey || event.altKey) { NavigationUtil.nextWord(selState,event.shiftKey); } else { NavigationUtil.nextCharacter(selState,event.shiftKey); } } else if(event.ctrlKey || event.altKey) { NavigationUtil.previousWord(selState,event.shiftKey); } else { NavigationUtil.previousCharacter(selState,event.shiftKey); } return selState; } private function handleHomeKey(event:KeyboardEvent) : SelectionState { var selState:SelectionState = this.getSelectionState(); if(event.ctrlKey && !event.altKey) { NavigationUtil.startOfDocument(selState,event.shiftKey); } else { NavigationUtil.startOfLine(selState,event.shiftKey); } return selState; } private function handleEndKey(event:KeyboardEvent) : SelectionState { var selState:SelectionState = this.getSelectionState(); if(event.ctrlKey && !event.altKey) { NavigationUtil.endOfDocument(selState,event.shiftKey); } else { NavigationUtil.endOfLine(selState,event.shiftKey); } return selState; } private function handlePageUpKey(event:KeyboardEvent) : SelectionState { var selState:SelectionState = this.getSelectionState(); NavigationUtil.previousPage(selState,event.shiftKey); return selState; } private function handlePageDownKey(event:KeyboardEvent) : SelectionState { var selState:SelectionState = this.getSelectionState(); NavigationUtil.nextPage(selState,event.shiftKey); return selState; } private function handleKeyEvent(event:KeyboardEvent) : void { var selState:SelectionState = null; this.flushPendingOperations(); switch(event.keyCode) { case Keyboard.LEFT: selState = this.handleLeftArrow(event); break; case Keyboard.UP: selState = this.handleUpArrow(event); break; case Keyboard.RIGHT: selState = this.handleRightArrow(event); break; case Keyboard.DOWN: selState = this.handleDownArrow(event); break; case Keyboard.HOME: selState = this.handleHomeKey(event); break; case Keyboard.END: selState = this.handleEndKey(event); break; case Keyboard.PAGE_DOWN: selState = this.handlePageDownKey(event); break; case Keyboard.PAGE_UP: selState = this.handlePageUpKey(event); } if(selState != null) { event.preventDefault(); this.updateSelectionAndShapes(this._textFlow,selState.anchorPosition,selState.activePosition); if(this._textFlow.flowComposer && this._textFlow.flowComposer.numControllers != 0) { this._textFlow.flowComposer.getControllerAt(this._textFlow.flowComposer.numControllers - 1).scrollToRange(selState.activePosition,selState.activePosition); } } this.allowOperationMerge = false; } public function keyDownHandler(event:KeyboardEvent) : void { if(!this.hasSelection() || event.isDefaultPrevented()) { return; } if(event.charCode == 0) { switch(event.keyCode) { case Keyboard.LEFT: case Keyboard.UP: case Keyboard.RIGHT: case Keyboard.DOWN: case Keyboard.HOME: case Keyboard.END: case Keyboard.PAGE_DOWN: case Keyboard.PAGE_UP: case Keyboard.ESCAPE: this.handleKeyEvent(event); } } else if(event.keyCode == Keyboard.ESCAPE) { this.handleKeyEvent(event); } if(this._textFlow.parentElement) { event.stopPropagation(); } } public function keyUpHandler(event:KeyboardEvent) : void { } public function keyFocusChangeHandler(event:FocusEvent) : void { } public function textInputHandler(event:TextEvent) : void { this.ignoreNextTextEvent = false; } public function imeStartCompositionHandler(event:IMEEvent) : void { } public function softKeyboardActivatingHandler(event:Event) : void { } protected function enterFrameHandler(event:Event) : void { this.flushPendingOperations(); } public function focusChangeHandler(event:FocusEvent) : void { } public function menuSelectHandler(event:ContextMenuEvent) : void { var menu:ContextMenu = event.target as ContextMenu; if(this.activePosition != this.anchorPosition) { menu.clipboardItems.copy = true; menu.clipboardItems.cut = this.editingMode == EditingMode.READ_WRITE; menu.clipboardItems.clear = this.editingMode == EditingMode.READ_WRITE; } else { menu.clipboardItems.copy = false; menu.clipboardItems.cut = false; menu.clipboardItems.clear = false; } var systemClipboard:Clipboard = Clipboard.generalClipboard; if(this.activePosition != -1 && this.editingMode == EditingMode.READ_WRITE && (systemClipboard.hasFormat(TextClipboard.TEXT_LAYOUT_MARKUP) || systemClipboard.hasFormat(ClipboardFormats.TEXT_FORMAT))) { menu.clipboardItems.paste = true; } else { menu.clipboardItems.paste = false; } menu.clipboardItems.selectAll = true; } public function mouseWheelHandler(event:MouseEvent) : void { } public function flushPendingOperations() : void { } public function getCommonCharacterFormat(range:TextRange = null) : TextLayoutFormat { if(!range && !this.hasSelection()) { return null; } var selRange:ElementRange = ElementRange.createElementRange(this._textFlow,!!range ? int(range.absoluteStart) : int(this.absoluteStart),!!range ? int(range.absoluteEnd) : int(this.absoluteEnd)); var rslt:TextLayoutFormat = selRange.getCommonCharacterFormat(); if(selRange.absoluteEnd == selRange.absoluteStart && this.pointFormat) { rslt.apply(this.pointFormat); } return rslt; } public function getCommonParagraphFormat(range:TextRange = null) : TextLayoutFormat { if(!range && !this.hasSelection()) { return null; } return ElementRange.createElementRange(this._textFlow,!!range ? int(range.absoluteStart) : int(this.absoluteStart),!!range ? int(range.absoluteEnd) : int(this.absoluteEnd)).getCommonParagraphFormat(); } public function getCommonContainerFormat(range:TextRange = null) : TextLayoutFormat { if(!range && !this.hasSelection()) { return null; } return ElementRange.createElementRange(this._textFlow,!!range ? int(range.absoluteStart) : int(this.absoluteStart),!!range ? int(range.absoluteEnd) : int(this.absoluteEnd)).getCommonContainerFormat(); } private function updateSelectionAndShapes(tf:TextFlow, begIdx:int, endIdx:int) : void { this.internalSetSelection(tf,begIdx,endIdx); if(this._textFlow.flowComposer && this._textFlow.flowComposer.numControllers != 0) { this._textFlow.flowComposer.getControllerAt(this._textFlow.flowComposer.numControllers - 1).scrollToRange(this.activeMark.position,this.anchorMark.position); } this.selectionChanged(); this.clearSelectionShapes(); this.addSelectionShapes(); } tlf_internal function createMark() : Mark { var mark:Mark = new Mark(-1); this.marks.push(mark); return mark; } tlf_internal function removeMark(mark:Mark) : void { var idx:int = this.marks.indexOf(mark); if(idx != -1) { this.marks.splice(idx,1); } } tlf_internal function createCellMark() : CellCoordinates { var mark:CellCoordinates = new CellCoordinates(-1,-1); this.cellMarks.push(mark); return mark; } tlf_internal function removeCellMark(mark:CellCoordinates) : void { var idx:int = this.cellMarks.indexOf(mark); if(idx != -1) { this.marks.splice(idx,1); } } public function notifyInsertOrDelete(absolutePosition:int, length:int) : void { var mark:Mark = null; if(length == 0) { return; } for(var i:int = 0; i < this.marks.length; i++) { mark = this.marks[i]; if(mark.position >= absolutePosition) { if(length < 0) { mark.position = mark.position + length < absolutePosition ? int(absolutePosition) : int(mark.position + length); } else { mark.position += length; } } } } public function get subManager() : ISelectionManager { return this._subManager; } public function set subManager(value:ISelectionManager) : void { if(value == this._subManager) { return; } if(this._subManager) { this._subManager.selectRange(-1,-1); } this._subManager = value; } public function get superManager() : ISelectionManager { return this._superManager; } public function set superManager(value:ISelectionManager) : void { this._superManager = value; } public function get anchorCellPosition() : CellCoordinates { return this._anchorCellPosition; } public function set anchorCellPosition(value:CellCoordinates) : void { this._anchorCellPosition = value; } public function get activeCellPosition() : CellCoordinates { return this._activeCellPosition; } public function set activeCellPosition(value:CellCoordinates) : void { this._activeCellPosition = value; } public function createSelectTableCursor() : MouseCursorData { var cursorData:Vector. = new Vector.(); var cursorShape:Shape = new Shape(); cursorShape.graphics.beginFill(0,1); cursorShape.graphics.lineStyle(0,16777215,1,true); cursorShape.graphics.drawPath(this.selectTableCursorDrawCommands,this.selectTableCursorPoints); cursorShape.graphics.endFill(); var transformer:Matrix = new Matrix(); var cursorFrame:BitmapData = new BitmapData(32,32,true,0); var angle:int = 8; var rotation:Number = 0.785398163; transformer.translate(-angle,-angle); transformer.rotate(rotation); transformer.translate(angle,angle); cursorFrame.draw(cursorShape,transformer); cursorData.push(cursorFrame); var mouseCursorData:MouseCursorData = new MouseCursorData(); mouseCursorData.data = cursorData; mouseCursorData.hotSpot = new Point(16,10); mouseCursorData.frameRate = 1; return mouseCursorData; } public function createSelectTableRowCursor() : MouseCursorData { var cursorData:Vector. = new Vector.(); var cursorShape:Shape = new Shape(); cursorShape.graphics.beginFill(0,1); cursorShape.graphics.lineStyle(0,16777215,1,true); cursorShape.graphics.drawPath(this.selectTableCursorDrawCommands,this.selectTableCursorPoints); cursorShape.graphics.endFill(); var transformer:Matrix = new Matrix(); var cursorFrame:BitmapData = new BitmapData(32,32,true,0); cursorFrame.draw(cursorShape,transformer); cursorData.push(cursorFrame); var mouseCursorData:MouseCursorData = new MouseCursorData(); mouseCursorData.data = cursorData; mouseCursorData.hotSpot = new Point(16,4); mouseCursorData.frameRate = 1; return mouseCursorData; } public function createSelectTableColumnCursor() : MouseCursorData { var cursorData:Vector. = new Vector.(); var cursorShape:Shape = new Shape(); cursorShape.graphics.beginFill(0,1); cursorShape.graphics.lineStyle(0,16777215,1,true); cursorShape.graphics.drawPath(this.selectTableCursorDrawCommands,this.selectTableCursorPoints); cursorShape.graphics.endFill(); var transformer:Matrix = new Matrix(); var cursorFrame:BitmapData = new BitmapData(32,32,true,0); var angle:int = 16; var rotation:Number = 0.785398163; transformer.translate(-angle,-angle); transformer.rotate(rotation * 2); transformer.translate(angle,angle); cursorFrame.draw(cursorShape,transformer); cursorData.push(cursorFrame); var mouseCursorData:MouseCursorData = new MouseCursorData(); mouseCursorData.data = cursorData; mouseCursorData.hotSpot = new Point(28,16); mouseCursorData.frameRate = 1; return mouseCursorData; } } } ",16132,True,2971.4969735178297,median "CLASS zcl_abapgit_gui_chunk_lib DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. TYPES: BEGIN OF ty_event_signature, method TYPE string, name TYPE string, END OF ty_event_signature . CLASS-METHODS class_constructor . CLASS-METHODS render_error IMPORTING !ix_error TYPE REF TO zcx_abapgit_exception OPTIONAL !iv_error TYPE string OPTIONAL !iv_extra_style TYPE string OPTIONAL RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . CLASS-METHODS render_repo_top IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo !iv_show_package TYPE abap_bool DEFAULT abap_true !iv_show_branch TYPE abap_bool DEFAULT abap_true !iv_show_commit TYPE abap_bool DEFAULT abap_true !iv_interactive_branch TYPE abap_bool DEFAULT abap_false !io_news TYPE REF TO zcl_abapgit_news OPTIONAL RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_item_state IMPORTING !iv_lstate TYPE char1 !iv_rstate TYPE char1 RETURNING VALUE(rv_html) TYPE string . CLASS-METHODS render_js_error_banner RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_news IMPORTING !io_news TYPE REF TO zcl_abapgit_news RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_commit_popup IMPORTING !iv_content TYPE csequence !iv_id TYPE csequence RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_error_message_box IMPORTING !ix_error TYPE REF TO zcx_abapgit_exception RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . CLASS-METHODS render_order_by_header_cells IMPORTING !it_col_spec TYPE zif_abapgit_definitions=>ty_col_spec_tt !iv_order_by TYPE string !iv_order_descending TYPE abap_bool RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . CLASS-METHODS render_warning_banner IMPORTING !iv_text TYPE string RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . CLASS-METHODS render_infopanel IMPORTING !iv_div_id TYPE string !iv_title TYPE string !iv_hide TYPE abap_bool DEFAULT abap_true !iv_hint TYPE string OPTIONAL !iv_scrollable TYPE abap_bool DEFAULT abap_true !io_content TYPE REF TO zif_abapgit_html RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_event_as_form IMPORTING !is_event TYPE ty_event_signature RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . CLASS-METHODS render_repo_palette IMPORTING !iv_action TYPE string RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS advanced_submenu RETURNING VALUE(ro_menu) TYPE REF TO zcl_abapgit_html_toolbar . CLASS-METHODS help_submenu RETURNING VALUE(ro_menu) TYPE REF TO zcl_abapgit_html_toolbar . CLASS-METHODS render_branch_name IMPORTING !iv_branch TYPE string OPTIONAL !iv_repo_key TYPE zif_abapgit_persistence=>ty_value OPTIONAL !io_repo TYPE REF TO zcl_abapgit_repo_online OPTIONAL !iv_interactive TYPE abap_bool DEFAULT abap_true RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_package_name IMPORTING !iv_package TYPE devclass !iv_interactive TYPE abap_bool DEFAULT abap_true RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_user_name IMPORTING !iv_username TYPE xubname !iv_interactive TYPE abap_bool DEFAULT abap_true !iv_icon_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_transport IMPORTING !iv_transport TYPE trkorr !iv_interactive TYPE abap_bool DEFAULT abap_true !iv_icon_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . PROTECTED SECTION. CLASS-METHODS render_repo_top_commit_hash IMPORTING !ii_html TYPE REF TO zif_abapgit_html !io_repo_online TYPE REF TO zcl_abapgit_repo_online RAISING zcx_abapgit_exception . PRIVATE SECTION. CLASS-DATA gv_time_zone TYPE timezone . CLASS-METHODS get_t100_text IMPORTING !iv_msgid TYPE scx_t100key-msgid !iv_msgno TYPE scx_t100key-msgno RETURNING VALUE(rv_text) TYPE string . CLASS-METHODS normalize_program_name IMPORTING !iv_program_name TYPE sy-repid RETURNING VALUE(rv_normalized_program_name) TYPE string . ENDCLASS. CLASS ZCL_ABAPGIT_GUI_CHUNK_LIB IMPLEMENTATION. METHOD advanced_submenu. DATA: li_gui_functions TYPE REF TO zif_abapgit_gui_functions, lv_supports_ie_devtools TYPE abap_bool. li_gui_functions = zcl_abapgit_ui_factory=>get_gui_functions( ). lv_supports_ie_devtools = li_gui_functions->is_sapgui_for_windows( ). CREATE OBJECT ro_menu. ro_menu->add( iv_txt = 'Database Utility' iv_act = zif_abapgit_definitions=>c_action-go_db )->add( iv_txt = 'Package to Zip' iv_act = zif_abapgit_definitions=>c_action-zip_package )->add( iv_txt = 'Transport to Zip' iv_act = zif_abapgit_definitions=>c_action-zip_transport )->add( iv_txt = 'Object to Files' iv_act = zif_abapgit_definitions=>c_action-zip_object )->add( iv_txt = 'Test Changed by' iv_act = zif_abapgit_definitions=>c_action-changed_by )->add( iv_txt = 'Debug Info' iv_act = zif_abapgit_definitions=>c_action-go_debuginfo ). IF lv_supports_ie_devtools = abap_true. ro_menu->add( iv_txt = 'Open IE DevTools' iv_act = zif_abapgit_definitions=>c_action-ie_devtools ). ENDIF. ro_menu->add( iv_txt = 'Performance Test' iv_act = zif_abapgit_definitions=>c_action-performance_test ). ENDMETHOD. METHOD class_constructor. CALL FUNCTION 'GET_SYSTEM_TIMEZONE' IMPORTING timezone = gv_time_zone EXCEPTIONS customizing_missing = 1 OTHERS = 2. ASSERT sy-subrc = 0. ENDMETHOD. METHOD get_t100_text. SELECT SINGLE text FROM t100 INTO rv_text WHERE arbgb = iv_msgid AND msgnr = iv_msgno AND sprsl = sy-langu. ENDMETHOD. METHOD help_submenu. CREATE OBJECT ro_menu. ro_menu->add( iv_txt = 'Tutorial' iv_act = zif_abapgit_definitions=>c_action-go_tutorial )->add( iv_txt = 'Documentation' iv_act = zif_abapgit_definitions=>c_action-documentation )->add( iv_txt = 'Explore' iv_act = zif_abapgit_definitions=>c_action-go_explore )->add( iv_txt = 'Changelog' iv_act = zif_abapgit_definitions=>c_action-changelog ). ENDMETHOD. METHOD normalize_program_name. rv_normalized_program_name = substring_before( val = iv_program_name regex = `(=+CP)?$` ). ENDMETHOD. METHOD render_branch_name. DATA: lv_key TYPE string, lv_branch TYPE string, lv_text TYPE string, lv_class TYPE string. IF iv_repo_key IS NOT INITIAL. lv_key = iv_repo_key. ELSEIF io_repo IS BOUND. lv_key = io_repo->get_key( ). ELSE. zcx_abapgit_exception=>raise( 'Either iv_repo_key or io_repo must be supplied' ). ENDIF. IF iv_branch IS NOT INITIAL. lv_branch = iv_branch. ELSEIF io_repo IS BOUND. lv_branch = io_repo->get_selected_branch( ). ELSE. zcx_abapgit_exception=>raise( 'Either iv_branch or io_repo must be supplied' ). ENDIF. lv_text = zcl_abapgit_git_branch_list=>get_display_name( lv_branch ). IF zcl_abapgit_git_branch_list=>get_type( lv_branch ) = zif_abapgit_definitions=>c_git_branch_type-branch. lv_class = 'branch branch_branch'. ELSE. lv_class = 'branch'. ENDIF. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( || ). ri_html->add_icon( iv_name = 'code-branch/grey70' iv_hint = 'Current branch' ). IF iv_interactive = abap_true. ri_html->add_a( iv_act = |{ zif_abapgit_definitions=>c_action-git_branch_switch }?key={ lv_key }| iv_txt = lv_text ). ELSE. ri_html->add( lv_text ). ENDIF. ri_html->add( '' ). ENDMETHOD. METHOD render_commit_popup. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( '
    ' ). ri_html->add( |
  • | && |{ iv_content }| && |
  • | ). ri_html->add( '
' ). ri_html = render_infopanel( iv_div_id = |{ iv_id }| iv_title = 'Commit details' iv_hide = abap_true iv_scrollable = abap_false io_content = ri_html ). ENDMETHOD. METHOD render_error. DATA lv_error TYPE string. DATA lv_class TYPE string VALUE 'panel error center'. IF iv_extra_style IS NOT INITIAL. lv_class = lv_class && ` ` && iv_extra_style. ENDIF. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF ix_error IS BOUND. lv_error = ix_error->get_text( ). ELSE. lv_error = iv_error. ENDIF. ri_html->add( |
| ). ri_html->add( |{ ri_html->icon( 'exclamation-circle/red' ) } { lv_error }| ). ri_html->add( '
' ). ENDMETHOD. METHOD render_error_message_box. DATA: lv_error_text TYPE string, lv_longtext TYPE string, lv_program_name TYPE sy-repid, lv_title TYPE string, lv_text TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. lv_error_text = ix_error->get_text( ). lv_longtext = ix_error->if_message~get_longtext( abap_true ). REPLACE FIRST OCCURRENCE OF REGEX |({ zcx_abapgit_exception=>gc_section_text-cause }{ cl_abap_char_utilities=>newline })| IN lv_longtext WITH |

$1

|. REPLACE FIRST OCCURRENCE OF REGEX |({ zcx_abapgit_exception=>gc_section_text-system_response }{ cl_abap_char_utilities=>newline })| IN lv_longtext WITH |

$1

|. REPLACE FIRST OCCURRENCE OF REGEX |({ zcx_abapgit_exception=>gc_section_text-what_to_do }{ cl_abap_char_utilities=>newline })| IN lv_longtext WITH |

$1

|. REPLACE FIRST OCCURRENCE OF REGEX |({ zcx_abapgit_exception=>gc_section_text-sys_admin }{ cl_abap_char_utilities=>newline })| IN lv_longtext WITH |

$1

|. ri_html->add( |
| ). ri_html->add( |{ ri_html->icon( 'exclamation-circle/red' ) } { lv_error_text }| ). ri_html->add( |
| ). ri_html->add_a( iv_txt = `❌` iv_act = `toggleDisplay('message')` iv_class = `close-btn` iv_typ = zif_abapgit_html=>c_action_type-onclick ). ri_html->add( |
| ). ri_html->add( |
| ). IF ix_error->if_t100_message~t100key-msgid IS NOT INITIAL. lv_title = get_t100_text( iv_msgid = ix_error->if_t100_message~t100key-msgid iv_msgno = ix_error->if_t100_message~t100key-msgno ). lv_text = |Message ({ ix_error->if_t100_message~t100key-msgid }/{ ix_error->if_t100_message~t100key-msgno })|. ri_html->add_a( iv_txt = lv_text iv_typ = zif_abapgit_html=>c_action_type-sapevent iv_act = zif_abapgit_definitions=>c_action-goto_message iv_title = lv_title iv_id = `a_goto_message` ). ENDIF. ix_error->get_source_position( IMPORTING program_name = lv_program_name ). lv_title = normalize_program_name( lv_program_name ). ri_html->add_a( iv_txt = `Goto source` iv_act = zif_abapgit_definitions=>c_action-goto_source iv_typ = zif_abapgit_html=>c_action_type-sapevent iv_title = lv_title iv_id = `a_goto_source` ). ri_html->add_a( iv_txt = `Callstack` iv_act = zif_abapgit_definitions=>c_action-show_callstack iv_typ = zif_abapgit_html=>c_action_type-sapevent iv_id = `a_callstack` ). ri_html->add( |
| ). ri_html->add( |
| ). ri_html->add( |{ lv_longtext }| ). ri_html->add( |
| ). ri_html->add( |
| ). ENDMETHOD. METHOD render_event_as_form. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( |
| ). ENDMETHOD. METHOD render_infopanel. DATA lv_display TYPE string. DATA lv_class TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF iv_hide = abap_true. "" Initially hide lv_display = 'display:none'. ENDIF. lv_class = 'info-panel'. IF iv_scrollable = abap_false. "" Initially hide lv_class = lv_class && ' info-panel-fixed'. ENDIF. ri_html->add( |
| ). ri_html->add( |
{ iv_title }| && '
' && ri_html->a( iv_txt = '❌' iv_typ = zif_abapgit_html=>c_action_type-onclick iv_act = |toggleDisplay('{ iv_div_id }')| iv_class = 'close-btn' ) && '
' ). IF iv_hint IS NOT INITIAL. ri_html->add( '
' && ri_html->icon( iv_name = 'exclamation-triangle' iv_class = 'pad-right' ) && iv_hint && '
' ). ENDIF. ri_html->add( |
| ). ri_html->add( io_content ). ri_html->add( '
' ). ri_html->add( '
' ). ENDMETHOD. METHOD render_item_state. DATA: lv_system TYPE string. FIELD-SYMBOLS TYPE char1. rv_html = ''. DO 2 TIMES. CASE sy-index. WHEN 1. ASSIGN iv_lstate TO . lv_system = 'Local:'. WHEN 2. ASSIGN iv_rstate TO . lv_system = 'Remote:'. ENDCASE. CASE . WHEN zif_abapgit_definitions=>c_state-unchanged. ""None or unchanged IF iv_lstate = zif_abapgit_definitions=>c_state-added OR iv_rstate = zif_abapgit_definitions=>c_state-added. rv_html = rv_html && |X|. ELSE. rv_html = rv_html && | |. ENDIF. WHEN zif_abapgit_definitions=>c_state-modified. ""Changed rv_html = rv_html && |M|. WHEN zif_abapgit_definitions=>c_state-added. ""Added new rv_html = rv_html && |A|. WHEN zif_abapgit_definitions=>c_state-mixed. ""Multiple changes (multifile) rv_html = rv_html && |■|. WHEN zif_abapgit_definitions=>c_state-deleted. ""Deleted rv_html = rv_html && |D|. ENDCASE. ENDDO. rv_html = rv_html && ''. ENDMETHOD. METHOD render_js_error_banner. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( '
' ). ri_html->add( |{ ri_html->icon( 'exclamation-triangle/red' ) }| && ' If this does not disappear soon,' && ' then there is a JS init error, please log an issue' ). ri_html->add( '
' ). ENDMETHOD. METHOD render_news. DATA: lv_text TYPE string, lv_hint TYPE string, lt_log TYPE zcl_abapgit_news=>ty_logs. FIELD-SYMBOLS: LIKE LINE OF lt_log. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF io_news IS NOT BOUND OR io_news->has_news( ) = abap_false. RETURN. ENDIF. lt_log = io_news->get_log( ). "" Render news LOOP AT lt_log ASSIGNING . IF -is_header = abap_true. IF -pos_to_cur > 0. lv_text = -text && 'update'. ELSEIF -pos_to_cur = 0. lv_text = -text && 'current'. ELSE. "" < 0 lv_text = -text. ENDIF. ri_html->add( |

{ lv_text }

| ). ELSE. -text = escape( val = -text format = cl_abap_format=>e_html_text ). ri_html->add( |
  • { -text }
  • | ). ENDIF. ENDLOOP. "" Wrap IF io_news->has_important( ) = abap_true. lv_hint = 'Please note changes marked with ""!""'. ENDIF. ri_html = render_infopanel( iv_div_id = 'news' iv_title = 'Announcement of the latest changes' iv_hint = lv_hint iv_hide = boolc( io_news->has_unseen( ) = abap_false ) io_content = ri_html ). ENDMETHOD. METHOD render_order_by_header_cells. DATA: lv_tmp TYPE string, lv_disp_name TYPE string. FIELD-SYMBOLS LIKE LINE OF it_col_spec. CREATE OBJECT ri_html TYPE zcl_abapgit_html. LOOP AT it_col_spec ASSIGNING . "" e.g. Created at [{ gv_time_zone }] lv_tmp = '-css_class IS NOT INITIAL. lv_tmp = lv_tmp && | class=""{ -css_class }""|. ENDIF. lv_tmp = lv_tmp && '>'. IF -display_name IS NOT INITIAL. lv_disp_name = -display_name. IF -add_tz = abap_true. lv_disp_name = lv_disp_name && | [{ gv_time_zone }]|. ENDIF. IF -tech_name = iv_order_by. IF iv_order_descending = abap_true. lv_tmp = lv_tmp && ri_html->a( iv_txt = lv_disp_name iv_act = |{ zif_abapgit_definitions=>c_action-direction }?direction=ASCENDING| iv_title = -title ). ELSE. lv_tmp = lv_tmp && ri_html->a( iv_txt = lv_disp_name iv_act = |{ zif_abapgit_definitions=>c_action-direction }?direction=DESCENDING| iv_title = -title ). ENDIF. ELSEIF -allow_order_by = abap_true. lv_tmp = lv_tmp && ri_html->a( iv_txt = lv_disp_name iv_act = |{ zif_abapgit_definitions=>c_action-change_order_by }?orderBy={ -tech_name }| iv_title = -title ). ELSE. lv_tmp = lv_tmp && ri_html->a( iv_txt = lv_disp_name iv_act = `` iv_title = -title ). ENDIF. ENDIF. IF -tech_name = iv_order_by AND iv_order_by IS NOT INITIAL. IF iv_order_descending = abap_true. lv_tmp = lv_tmp && | ▾|. "" arrow down ELSE. lv_tmp = lv_tmp && | ▴|. "" arrow up ENDIF. ENDIF. lv_tmp = lv_tmp && ''. ri_html->add( lv_tmp ). ENDLOOP. ENDMETHOD. METHOD render_package_name. DATA: lv_obj_name TYPE tadir-obj_name, lv_jump TYPE string, lv_title TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF iv_package IS INITIAL. RETURN. ENDIF. SELECT SINGLE ctext FROM tdevct INTO lv_title WHERE devclass = iv_package AND spras = sy-langu ##SUBRC_OK. lv_obj_name = iv_package. lv_jump = zcl_abapgit_html_action_utils=>jump_encode( iv_obj_type = 'DEVC' iv_obj_name = lv_obj_name ). ri_html->add( || ). ri_html->add_icon( iv_name = 'box/grey70' iv_hint = 'SAP package' ). IF iv_interactive = abap_true. ri_html->add_a( iv_act = |{ zif_abapgit_definitions=>c_action-jump }?{ lv_jump }| iv_title = lv_title iv_txt = to_lower( iv_package ) ). ELSE. ri_html->add( to_lower( iv_package ) ). ENDIF. ri_html->add( '' ). ENDMETHOD. METHOD render_repo_palette. DATA li_repo_srv TYPE REF TO zif_abapgit_repo_srv. DATA lt_repo_list TYPE zif_abapgit_persistence=>ty_repos. DATA lv_repo_json TYPE string. DATA lv_size TYPE i. FIELD-SYMBOLS LIKE LINE OF lt_repo_list. li_repo_srv = zcl_abapgit_repo_srv=>get_instance( ). lt_repo_list = zcl_abapgit_persist_factory=>get_repo( )->list( ). lv_size = lines( lt_repo_list ). CREATE OBJECT ri_html TYPE zcl_abapgit_html. "" Sort list by display name LOOP AT lt_repo_list ASSIGNING . -local_settings-display_name = li_repo_srv->get( -key )->get_name( ). ENDLOOP. SORT lt_repo_list BY local_settings-display_name AS TEXT. ri_html->add( 'var repoCatalog = [' ). "" Maybe separate this into another method if needed in more places LOOP AT lt_repo_list ASSIGNING . lv_repo_json = |\\{ key: ""{ -key }"", isOffline: ""{ -offline }"", displayName: ""{ -local_settings-display_name }"" \\}|. IF sy-tabix < lv_size. lv_repo_json = lv_repo_json && ','. ENDIF. ri_html->add( lv_repo_json ). ENDLOOP. ri_html->add( '];' ). ri_html->add( |var gGoRepoPalette = new CommandPalette(createRepoCatalogEnumerator(repoCatalog, ""{ iv_action }""), \\{| ). ri_html->add( ' toggleKey: ""F2"",' ). ri_html->add( ' hotkeyDescription: ""Go to repo ...""' ). ri_html->add( '});' ). ENDMETHOD. METHOD render_repo_top. DATA: lo_repo_online TYPE REF TO zcl_abapgit_repo_online, lo_pback TYPE REF TO zcl_abapgit_persist_background, lx_error TYPE REF TO zcx_abapgit_exception, lv_hint TYPE string, lv_icon TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. CREATE OBJECT lo_pback. IF io_repo->is_offline( ) = abap_true. lv_icon = 'plug/darkgrey'. lv_hint = 'Offline repository'. ELSE. lv_icon = 'cloud-upload-alt/blue'. lv_hint = 'On-line repository'. ENDIF. ri_html->add( '' ). ri_html->add( '' ). ri_html->add( '' ). ri_html->add( '
    ' ). "" Repo type and name ri_html->add_icon( iv_name = lv_icon iv_hint = lv_hint ). ri_html->add( |{ io_repo->get_name( ) }| ). IF io_repo->is_offline( ) = abap_false. lo_repo_online ?= io_repo. ri_html->add_a( iv_txt = lo_repo_online->get_url( ) iv_act = |{ zif_abapgit_definitions=>c_action-url }?url=| && |{ lo_repo_online->get_url( ) }| iv_class = |url| ). IF iv_show_commit = abap_true. TRY. render_repo_top_commit_hash( ii_html = ri_html io_repo_online = lo_repo_online ). CATCH zcx_abapgit_exception INTO lx_error. "" In case of missing or wrong credentials, show message in status bar lv_hint = lx_error->get_text( ). IF lv_hint CS 'credentials'. MESSAGE lv_hint TYPE 'S' DISPLAY LIKE 'E'. ENDIF. ENDTRY. ENDIF. ENDIF. "" News IF io_news IS BOUND AND io_news->has_news( ) = abap_true. IF io_news->has_updates( ) = abap_true. lv_icon = 'arrow-circle-up/warning'. ELSE. lv_icon = 'arrow-circle-up/grey80'. ENDIF. ri_html->add_a( iv_act = |toggleDisplay('news')| iv_typ = zif_abapgit_html=>c_action_type-onclick iv_txt = ri_html->icon( iv_name = lv_icon iv_class = 'pad-sides' iv_hint = 'Display changelog' ) ). ENDIF. ri_html->add( '' ). "" Fav IF abap_true = zcl_abapgit_persistence_user=>get_instance( )->is_favorite_repo( io_repo->get_key( ) ). lv_icon = 'star/blue'. ELSE. lv_icon = 'star/grey'. ENDIF. ri_html->add_a( iv_act = |{ zif_abapgit_definitions=>c_action-repo_toggle_fav }?key={ io_repo->get_key( ) }| iv_txt = ri_html->icon( iv_name = lv_icon iv_class = 'pad-sides' iv_hint = 'Click to toggle favorite' ) ). "" BG IF lo_pback->exists( io_repo->get_key( ) ) = abap_true. ri_html->add( 'BG' ). ENDIF. "" Write protect IF io_repo->get_local_settings( )-write_protected = abap_true. ri_html->add_icon( iv_name = 'lock/grey70' iv_hint = 'Locked from pulls' ). ENDIF. "" Branch IF io_repo->is_offline( ) = abap_false. lo_repo_online ?= io_repo. IF iv_show_branch = abap_true. ri_html->add( render_branch_name( io_repo = lo_repo_online iv_interactive = iv_interactive_branch ) ). ENDIF. ENDIF. "" Package IF iv_show_package = abap_true. ri_html->add( render_package_name( io_repo->get_package( ) ) ). ENDIF. ri_html->add( '
    ' ). ENDMETHOD. METHOD render_repo_top_commit_hash. DATA: lv_commit_hash TYPE zif_abapgit_definitions=>ty_sha1, lv_commit_short_hash TYPE zif_abapgit_definitions=>ty_sha1, lv_display_url TYPE zif_abapgit_persistence=>ty_repo-url, lo_url TYPE REF TO zcl_abapgit_git_url, lv_icon_commit TYPE string. lv_commit_hash = io_repo_online->get_current_remote( ). lv_commit_short_hash = lv_commit_hash(7). lv_icon_commit = ii_html->icon( iv_name = 'code-commit' iv_class = 'pad-sides' iv_hint = 'Commit' ). CREATE OBJECT lo_url. TRY. lv_display_url = lo_url->get_commit_display_url( io_repo_online ). ii_html->add_a( iv_txt = |{ lv_icon_commit }{ lv_commit_short_hash }| iv_act = |{ zif_abapgit_definitions=>c_action-url }?url={ lv_display_url }| iv_class = |url| ). CATCH zcx_abapgit_exception. ii_html->add( |{ lv_icon_commit }{ lv_commit_short_hash }| ). ENDTRY. ENDMETHOD. METHOD render_transport. DATA: lv_title TYPE string, lv_jump TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF iv_transport IS INITIAL. RETURN. ENDIF. SELECT SINGLE as4text FROM e07t INTO lv_title WHERE trkorr = iv_transport AND langu = sy-langu ##SUBRC_OK. lv_jump = |{ zif_abapgit_definitions=>c_action-jump_transport }?transport={ iv_transport }|. IF iv_icon_only = abap_true. ri_html->add_a( iv_act = lv_jump iv_title = |Transport { iv_transport }| iv_txt = zcl_abapgit_html=>icon( 'truck-solid/darkgrey' ) ). ELSE. ri_html->add( || ). ri_html->add_icon( iv_name = 'truck-solid/grey70' iv_hint = 'Transport' ). IF iv_interactive = abap_true. ri_html->add_a( iv_act = lv_jump iv_title = lv_title iv_txt = to_lower( iv_transport ) ). ELSE. ri_html->add( to_lower( iv_transport ) ). ENDIF. ri_html->add( '' ). ENDIF. ENDMETHOD. METHOD render_user_name. DATA: ls_user_address TYPE addr3_val, lv_title TYPE string, lv_jump TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF iv_username IS INITIAL. RETURN. ENDIF. IF iv_username <> zcl_abapgit_objects_super=>c_user_unknown. CALL FUNCTION 'SUSR_USER_ADDRESS_READ' EXPORTING user_name = iv_username IMPORTING user_address = ls_user_address EXCEPTIONS user_address_not_found = 1 OTHERS = 2. IF sy-subrc = 0. lv_title = ls_user_address-name_text. ENDIF. ENDIF. lv_jump = |{ zif_abapgit_definitions=>c_action-jump_user }?user={ iv_username }|. IF iv_icon_only = abap_true. ri_html->add_a( iv_act = lv_jump iv_title = lv_title iv_txt = zcl_abapgit_html=>icon( 'user-solid/darkgrey' ) ). ELSE. ri_html->add( || ). ri_html->add_icon( iv_name = 'user-solid/grey70' iv_hint = 'User name' ). IF iv_interactive = abap_true AND iv_username <> zcl_abapgit_objects_super=>c_user_unknown. ri_html->add_a( iv_act = lv_jump iv_title = lv_title iv_txt = to_lower( iv_username ) ). ELSE. ri_html->add( to_lower( iv_username ) ). ENDIF. ri_html->add( '' ). ENDIF. ENDMETHOD. METHOD render_warning_banner. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( '
    ' ). ri_html->add( |{ ri_html->icon( 'exclamation-triangle/yellow' ) } { iv_text }| ). ri_html->add( '
    ' ). ENDMETHOD. ENDCLASS. ",8242,False,1814.3600456238707,median "CLASS zcl_abapgit_object_tabl DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super FINAL. PUBLIC SECTION. INTERFACES zif_abapgit_object. ALIASES mo_files FOR zif_abapgit_object~mo_files. PROTECTED SECTION. TYPES: BEGIN OF ty_segment_definition, segmentheader TYPE edisegmhd, segmentdefinition TYPE edisegmdef, segmentstructures TYPE STANDARD TABLE OF edisegstru WITH DEFAULT KEY, END OF ty_segment_definition. TYPES: ty_segment_definitions TYPE STANDARD TABLE OF ty_segment_definition WITH DEFAULT KEY. TYPES: BEGIN OF ty_tabl_extras, tddat TYPE tddat, END OF ty_tabl_extras. ""! get additional data like table authorization group ""! @parameter iv_tabname | name of the table METHODS read_extras IMPORTING iv_tabname TYPE ddobjname RETURNING VALUE(rs_tabl_extras) TYPE ty_tabl_extras. ""! Update additional data ""! @parameter iv_tabname | name of the table ""! @parameter is_tabl_extras | additional table data METHODS update_extras IMPORTING iv_tabname TYPE ddobjname is_tabl_extras TYPE ty_tabl_extras. ""! Delete additional data ""! @parameter iv_tabname | name of the table METHODS delete_extras IMPORTING iv_tabname TYPE ddobjname. ""! Serialize IDoc Segment type/definition if exits ""! @parameter io_xml | XML writer ""! @raising zcx_abapgit_exception | Exceptions METHODS serialize_idoc_segment IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_output RAISING zcx_abapgit_exception. ""! Deserialize IDoc Segment type/definition if exits ""! @parameter io_xml | XML writer ""! @parameter iv_package | Target package ""! @parameter rv_deserialized | It's a segment and was desserialized ""! @raising zcx_abapgit_exception | Exceptions METHODS deserialize_idoc_segment IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_input iv_package TYPE devclass RETURNING VALUE(rv_deserialized) TYPE abap_bool RAISING zcx_abapgit_exception. ""! Delete the IDoc Segment type if exists ""! @parameter rv_deleted | It's a segment and was deleted ""! @raising zcx_abapgit_exception | Exceptions METHODS delete_idoc_segment RETURNING VALUE(rv_deleted) TYPE abap_bool RAISING zcx_abapgit_exception. PRIVATE SECTION. TYPES: ty_dd03p_tt TYPE STANDARD TABLE OF dd03p . TYPES: BEGIN OF ty_dd02_texts, ddlanguage TYPE dd02t-ddlanguage, ddtext TYPE dd02t-ddtext, END OF ty_dd02_texts, tt_dd02_texts TYPE STANDARD TABLE OF ty_dd02_texts. CONSTANTS c_longtext_id_tabl TYPE dokil-id VALUE 'TB' ##NO_TEXT. CONSTANTS: BEGIN OF c_s_dataname, segment_definition TYPE string VALUE 'SEGMENT_DEFINITION', tabl_extras TYPE string VALUE 'TABL_EXTRAS', END OF c_s_dataname. METHODS clear_dd03p_fields CHANGING !ct_dd03p TYPE ty_dd03p_tt . ""! Check if structure is an IDoc segment ""! @parameter rv_is_idoc_segment | It's an IDoc segment or not METHODS is_idoc_segment RETURNING VALUE(rv_is_idoc_segment) TYPE abap_bool. METHODS clear_dd03p_fields_common CHANGING !cs_dd03p TYPE dd03p . METHODS clear_dd03p_fields_dataelement CHANGING !cs_dd03p TYPE dd03p . METHODS: serialize_texts IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_output RAISING zcx_abapgit_exception, deserialize_texts IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_input is_dd02v TYPE dd02v RAISING zcx_abapgit_exception. ENDCLASS. CLASS ZCL_ABAPGIT_OBJECT_TABL IMPLEMENTATION. METHOD clear_dd03p_fields. CONSTANTS lc_comptype_dataelement TYPE comptype VALUE 'E' ##NO_TEXT. DATA: lv_masklen TYPE c LENGTH 4. FIELD-SYMBOLS: TYPE dd03p. * remove nested structures DELETE ct_dd03p WHERE depth <> '00'. * remove fields from .INCLUDEs DELETE ct_dd03p WHERE adminfield <> '0'. LOOP AT ct_dd03p ASSIGNING WHERE NOT rollname IS INITIAL. clear_dd03p_fields_common( CHANGING cs_dd03p = ). lv_masklen = -masklen. IF lv_masklen = '' OR NOT lv_masklen CO '0123456789'. * make sure the field contains valid data, or the XML will dump CLEAR -masklen. ENDIF. IF -comptype = lc_comptype_dataelement. clear_dd03p_fields_dataelement( CHANGING cs_dd03p = ). ENDIF. IF -shlporigin = 'D'. * search help from domain CLEAR: -shlpfield, -shlpname. ENDIF. * XML output assumes correct field content IF -routputlen = ' '. CLEAR -routputlen. ENDIF. ENDLOOP. ENDMETHOD. METHOD clear_dd03p_fields_common. CLEAR: cs_dd03p-ddlanguage, cs_dd03p-dtelmaster, cs_dd03p-logflag, cs_dd03p-ddtext, cs_dd03p-reservedte, cs_dd03p-reptext, cs_dd03p-scrtext_s, cs_dd03p-scrtext_m, cs_dd03p-scrtext_l. ENDMETHOD. METHOD clear_dd03p_fields_dataelement. * type specified via data element CLEAR: cs_dd03p-domname, cs_dd03p-inttype, cs_dd03p-intlen, cs_dd03p-mask, cs_dd03p-memoryid, cs_dd03p-headlen, cs_dd03p-scrlen1, cs_dd03p-scrlen2, cs_dd03p-scrlen3, cs_dd03p-datatype, cs_dd03p-leng, cs_dd03p-outputlen, cs_dd03p-deffdname, cs_dd03p-convexit, cs_dd03p-entitytab, cs_dd03p-dommaster, cs_dd03p-domname3l, cs_dd03p-decimals, cs_dd03p-lowercase, cs_dd03p-signflag. ENDMETHOD. METHOD delete_extras. DELETE FROM tddat WHERE tabname = iv_tabname. ENDMETHOD. METHOD delete_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. DATA lv_result LIKE sy-subrc. IF is_idoc_segment( ) = abap_false. rv_deleted = abap_false. RETURN. ""previous XML version or no IDoc segment ENDIF. rv_deleted = abap_true. lv_segment_type = ms_item-obj_name. CALL FUNCTION 'SEGMENT_DELETE' EXPORTING segmenttyp = lv_segment_type IMPORTING result = lv_result EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDMETHOD. METHOD deserialize_idoc_segment. DATA lv_result LIKE sy-subrc. DATA lt_segment_definitions TYPE ty_segment_definitions. DATA lv_package TYPE devclass. DATA lv_uname TYPE sy-uname. FIELD-SYMBOLS TYPE ty_segment_definition. rv_deserialized = abap_false. TRY. io_xml->read( EXPORTING iv_name = c_s_dataname-segment_definition CHANGING cg_data = lt_segment_definitions ). CATCH zcx_abapgit_exception. RETURN. ""previous XML version or no IDoc segment ENDTRY. IF lines( lt_segment_definitions ) = 0. RETURN. ""no IDoc segment ENDIF. rv_deserialized = abap_true. lv_package = iv_package. LOOP AT lt_segment_definitions ASSIGNING . -segmentheader-presp = -segmentheader-pwork = cl_abap_syst=>get_user_name( ). CALL FUNCTION 'SEGMENT_READ' EXPORTING segmenttyp = -segmentheader-segtyp IMPORTING result = lv_result EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. CALL FUNCTION 'SEGMENT_CREATE' IMPORTING segmentdefinition = -segmentdefinition TABLES segmentstructure = -segmentstructures CHANGING segmentheader = -segmentheader devclass = lv_package EXCEPTIONS OTHERS = 1. ELSE. CALL FUNCTION 'SEGMENT_MODIFY' CHANGING segmentheader = -segmentheader devclass = lv_package EXCEPTIONS OTHERS = 1. IF sy-subrc = 0. CALL FUNCTION 'SEGMENTDEFINITION_MODIFY' TABLES segmentstructure = -segmentstructures CHANGING segmentdefinition = -segmentdefinition EXCEPTIONS OTHERS = 1. ENDIF. ENDIF. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDLOOP. lv_uname = cl_abap_syst=>get_user_name( ). CALL FUNCTION 'TR_TADIR_INTERFACE' EXPORTING wi_test_modus = abap_false wi_tadir_pgmid = 'R3TR' wi_tadir_object = ms_item-obj_type wi_tadir_obj_name = ms_item-obj_name wi_tadir_author = lv_uname wi_tadir_devclass = iv_package wi_tadir_masterlang = mv_language iv_set_edtflag = abap_true iv_delflag = abap_false EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from TR_TADIR_INTERFACE' ). ENDIF. ENDMETHOD. METHOD deserialize_texts. DATA: lv_name TYPE ddobjname, ls_dd02v_tmp TYPE dd02v, lt_i18n_langs TYPE TABLE OF langu, lt_dd02_texts TYPE tt_dd02_texts. FIELD-SYMBOLS: LIKE LINE OF lt_i18n_langs, LIKE LINE OF lt_dd02_texts. lv_name = ms_item-obj_name. io_xml->read( EXPORTING iv_name = 'I18N_LANGS' CHANGING cg_data = lt_i18n_langs ). io_xml->read( EXPORTING iv_name = 'DD02_TEXTS' CHANGING cg_data = lt_dd02_texts ). SORT lt_i18n_langs. SORT lt_dd02_texts BY ddlanguage. "" Optimization LOOP AT lt_i18n_langs ASSIGNING . "" Table description ls_dd02v_tmp = is_dd02v. READ TABLE lt_dd02_texts ASSIGNING WITH KEY ddlanguage = . IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |DD02_TEXTS cannot find lang { } in XML| ). ENDIF. MOVE-CORRESPONDING TO ls_dd02v_tmp. CALL FUNCTION 'DDIF_TABL_PUT' EXPORTING name = lv_name dd02v_wa = ls_dd02v_tmp EXCEPTIONS tabl_not_found = 1 name_inconsistent = 2 tabl_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |error from DDIF_TABL_PUT @TEXTS, { sy-subrc }| ). ENDIF. ENDLOOP. ENDMETHOD. METHOD is_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. lv_segment_type = ms_item-obj_name. SELECT SINGLE segtyp FROM edisegment INTO lv_segment_type WHERE segtyp = lv_segment_type. rv_is_idoc_segment = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD read_extras. SELECT SINGLE * FROM tddat INTO rs_tabl_extras-tddat WHERE tabname = iv_tabname. ENDMETHOD. METHOD serialize_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. DATA lv_result LIKE sy-subrc. DATA lv_devclass TYPE devclass. DATA lt_segmentdefinitions TYPE STANDARD TABLE OF edisegmdef. DATA ls_segment_definition TYPE ty_segment_definition. DATA lt_segment_definitions TYPE ty_segment_definitions. FIELD-SYMBOLS: TYPE edisegmdef. IF is_idoc_segment( ) = abap_false. RETURN. ENDIF. lv_segment_type = ms_item-obj_name. CALL FUNCTION 'SEGMENT_READ' EXPORTING segmenttyp = lv_segment_type IMPORTING result = lv_result TABLES segmentdefinition = lt_segmentdefinitions EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. LOOP AT lt_segmentdefinitions ASSIGNING . CLEAR ls_segment_definition. CALL FUNCTION 'SEGMENTDEFINITION_READ' EXPORTING segmenttyp = -segtyp IMPORTING result = lv_result devclass = lv_devclass segmentheader = ls_segment_definition-segmentheader segmentdefinition = ls_segment_definition-segmentdefinition TABLES segmentstructure = ls_segment_definition-segmentstructures CHANGING version = -version EXCEPTIONS no_authority = 1 segment_not_existing = 2 OTHERS = 3. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. zcl_abapgit_object_idoc=>clear_idoc_segement_fields( CHANGING cg_structure = ls_segment_definition-segmentdefinition ). zcl_abapgit_object_idoc=>clear_idoc_segement_fields( CHANGING cg_structure = ls_segment_definition-segmentheader ). APPEND ls_segment_definition TO lt_segment_definitions. ENDLOOP. io_xml->add( iv_name = c_s_dataname-segment_definition ig_data = lt_segment_definitions ). ENDMETHOD. METHOD serialize_texts. DATA: lv_name TYPE ddobjname, lv_index TYPE i, ls_dd02v TYPE dd02v, lt_dd02_texts TYPE tt_dd02_texts, lt_i18n_langs TYPE TABLE OF langu. FIELD-SYMBOLS: LIKE LINE OF lt_i18n_langs, LIKE LINE OF lt_dd02_texts. IF io_xml->i18n_params( )-serialize_master_lang_only = abap_true. RETURN. ENDIF. lv_name = ms_item-obj_name. "" Collect additional languages, skip master lang - it was serialized already SELECT DISTINCT ddlanguage AS langu INTO TABLE lt_i18n_langs FROM dd02v WHERE tabname = lv_name AND ddlanguage <> mv_language. ""#EC CI_SUBRC LOOP AT lt_i18n_langs ASSIGNING . lv_index = sy-tabix. CALL FUNCTION 'DDIF_TABL_GET' EXPORTING name = lv_name langu = IMPORTING dd02v_wa = ls_dd02v EXCEPTIONS illegal_input = 1 OTHERS = 2. IF sy-subrc <> 0 OR ls_dd02v-ddlanguage IS INITIAL. DELETE lt_i18n_langs INDEX lv_index. "" Don't save this lang CONTINUE. ENDIF. APPEND INITIAL LINE TO lt_dd02_texts ASSIGNING . MOVE-CORRESPONDING ls_dd02v TO . ENDLOOP. SORT lt_i18n_langs ASCENDING. SORT lt_dd02_texts BY ddlanguage ASCENDING. IF lines( lt_i18n_langs ) > 0. io_xml->add( iv_name = 'I18N_LANGS' ig_data = lt_i18n_langs ). io_xml->add( iv_name = 'DD02_TEXTS' ig_data = lt_dd02_texts ). ENDIF. ENDMETHOD. METHOD update_extras. IF is_tabl_extras-tddat IS INITIAL. delete_extras( iv_tabname = iv_tabname ). ELSE. MODIFY tddat FROM is_tabl_extras-tddat. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~changed_by. TYPES: BEGIN OF ty_data, as4user TYPE as4user, as4date TYPE as4date, as4time TYPE as4time, END OF ty_data. DATA: lt_data TYPE STANDARD TABLE OF ty_data WITH DEFAULT KEY, ls_data LIKE LINE OF lt_data. SELECT as4user as4date as4time FROM dd02l INTO TABLE lt_data WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SELECT as4user as4date as4time APPENDING TABLE lt_data FROM dd09l WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SELECT as4user as4date as4time APPENDING TABLE lt_data FROM dd12l WHERE sqltab = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SORT lt_data BY as4date DESCENDING as4time DESCENDING. READ TABLE lt_data INDEX 1 INTO ls_data. IF sy-subrc = 0. rv_user = ls_data-as4user. ELSE. rv_user = c_user_unknown. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: lv_objname TYPE rsedd0-ddobjname, lv_tabclass TYPE dd02l-tabclass, lv_no_ask TYPE abap_bool, lv_subrc TYPE sy-subrc, lr_data TYPE REF TO data. FIELD-SYMBOLS: TYPE any. IF zif_abapgit_object~exists( ) = abap_false. "" Proxies e.g. delete on its own, nothing todo here then. RETURN. ENDIF. lv_objname = ms_item-obj_name. IF delete_idoc_segment( ) = abap_false. lv_no_ask = abap_true. SELECT SINGLE tabclass FROM dd02l INTO lv_tabclass WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. IF sy-subrc = 0 AND lv_tabclass = 'TRANSP'. "" Avoid dump in dynamic SELECT in case the table does not exist on database CALL FUNCTION 'DB_EXISTS_TABLE' EXPORTING tabname = lv_objname IMPORTING subrc = lv_subrc. IF lv_subrc = 0. "" it cannot delete table with data without asking CREATE DATA lr_data TYPE (lv_objname). ASSIGN lr_data->* TO . SELECT SINGLE * FROM (lv_objname) INTO . IF sy-subrc = 0. lv_no_ask = abap_false. ENDIF. ENDIF. ENDIF. delete_ddic( iv_objtype = 'T' iv_no_ask = lv_no_ask ). delete_longtexts( c_longtext_id_tabl ). delete_extras( iv_tabname = lv_objname ). ENDIF. ENDMETHOD. METHOD zif_abapgit_object~deserialize. DATA: lv_name TYPE ddobjname, lv_tname TYPE trobj_name, ls_dd02v TYPE dd02v, ls_dd09l TYPE dd09l, lt_dd03p TYPE TABLE OF dd03p, lt_dd05m TYPE TABLE OF dd05m, lt_dd08v TYPE TABLE OF dd08v, lt_dd12v TYPE dd12vtab, lt_dd17v TYPE dd17vtab, ls_dd17v LIKE LINE OF lt_dd17v, lt_secondary LIKE lt_dd17v, lt_dd35v TYPE TABLE OF dd35v, lt_dd36m TYPE dd36mttyp, ls_dd12v LIKE LINE OF lt_dd12v, lv_refs TYPE abap_bool, ls_extras TYPE ty_tabl_extras. FIELD-SYMBOLS: TYPE dd03p. IF deserialize_idoc_segment( io_xml = io_xml iv_package = iv_package ) = abap_false. io_xml->read( EXPORTING iv_name = 'DD02V' CHANGING cg_data = ls_dd02v ). io_xml->read( EXPORTING iv_name = 'DD09L' CHANGING cg_data = ls_dd09l ). io_xml->read( EXPORTING iv_name = 'DD03P_TABLE' CHANGING cg_data = lt_dd03p ). "" DDIC Step: Replace REF TO class/interface with generic reference to avoid cyclic dependency LOOP AT lt_dd03p ASSIGNING WHERE datatype = 'REF'. IF iv_step = zif_abapgit_object=>gc_step_id-ddic. -rollname = 'OBJECT'. ELSE. lv_refs = abap_true. ENDIF. ENDLOOP. io_xml->read( EXPORTING iv_name = 'DD05M_TABLE' CHANGING cg_data = lt_dd05m ). io_xml->read( EXPORTING iv_name = 'DD08V_TABLE' CHANGING cg_data = lt_dd08v ). io_xml->read( EXPORTING iv_name = 'DD12V' CHANGING cg_data = lt_dd12v ). io_xml->read( EXPORTING iv_name = 'DD17V' CHANGING cg_data = lt_dd17v ). io_xml->read( EXPORTING iv_name = 'DD35V_TALE' CHANGING cg_data = lt_dd35v ). io_xml->read( EXPORTING iv_name = 'DD36M' CHANGING cg_data = lt_dd36m ). "" DDIC Step: Remove referenced to search helps IF iv_step = zif_abapgit_object=>gc_step_id-ddic. CLEAR: lt_dd35v, lt_dd36m. ENDIF. IF iv_step = zif_abapgit_object=>gc_step_id-late AND lv_refs = abap_false AND lines( lt_dd35v ) = 0. RETURN. "" already active ENDIF. corr_insert( iv_package = iv_package ig_object_class = 'DICT' ). lv_name = ms_item-obj_name. "" type conversion CALL FUNCTION 'DDIF_TABL_PUT' EXPORTING name = lv_name dd02v_wa = ls_dd02v dd09l_wa = ls_dd09l TABLES dd03p_tab = lt_dd03p dd05m_tab = lt_dd05m dd08v_tab = lt_dd08v dd35v_tab = lt_dd35v dd36m_tab = lt_dd36m EXCEPTIONS tabl_not_found = 1 name_inconsistent = 2 tabl_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_TABL_PUT' ). ENDIF. zcl_abapgit_objects_activation=>add_item( ms_item ). * handle indexes LOOP AT lt_dd12v INTO ls_dd12v. * todo, call corr_insert? CLEAR lt_secondary. LOOP AT lt_dd17v INTO ls_dd17v WHERE sqltab = ls_dd12v-sqltab AND indexname = ls_dd12v-indexname. APPEND ls_dd17v TO lt_secondary. ENDLOOP. CALL FUNCTION 'DDIF_INDX_PUT' EXPORTING name = ls_dd12v-sqltab id = ls_dd12v-indexname dd12v_wa = ls_dd12v TABLES dd17v_tab = lt_secondary EXCEPTIONS indx_not_found = 1 name_inconsistent = 2 indx_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_INDX_PUT' ). ENDIF. CALL FUNCTION 'DD_DD_TO_E071' EXPORTING type = 'INDX' name = ls_dd12v-sqltab id = ls_dd12v-indexname IMPORTING obj_name = lv_tname. zcl_abapgit_objects_activation=>add( iv_type = 'INDX' iv_name = lv_tname ). ENDLOOP. deserialize_texts( io_xml = io_xml is_dd02v = ls_dd02v ). deserialize_longtexts( io_xml ). io_xml->read( EXPORTING iv_name = c_s_dataname-tabl_extras CHANGING cg_data = ls_extras ). update_extras( iv_tabname = lv_name is_tabl_extras = ls_extras ). ENDIF. ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: lv_tabname TYPE dd02l-tabname. SELECT SINGLE tabname FROM dd02l INTO lv_tabname WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. rv_bool = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. DATA: lo_local_version_output TYPE REF TO zcl_abapgit_xml_output, lo_local_version_input TYPE REF TO zcl_abapgit_xml_input. CREATE OBJECT lo_local_version_output. me->zif_abapgit_object~serialize( lo_local_version_output ). CREATE OBJECT lo_local_version_input EXPORTING iv_xml = lo_local_version_output->render( ). CREATE OBJECT ri_comparator TYPE zcl_abapgit_object_tabl_compar EXPORTING io_local = lo_local_version_input. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-ddic TO rt_steps. APPEND zif_abapgit_object=>gc_step_id-late TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). rs_metadata-ddic = abap_true. ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. rv_is_locked = exists_a_lock_entry_for( iv_lock_object = 'ESDICT' iv_argument = |{ ms_item-obj_type }{ ms_item-obj_name }| ). ENDMETHOD. METHOD zif_abapgit_object~jump. jump_se11( iv_radio = 'RSRD1-DDTYPE' iv_field = 'RSRD1-DDTYPE_VAL' ). ENDMETHOD. METHOD zif_abapgit_object~serialize. DATA: lv_name TYPE ddobjname, ls_dd02v TYPE dd02v, ls_dd09l TYPE dd09l, lt_dd03p TYPE ty_dd03p_tt, lt_dd05m TYPE TABLE OF dd05m, lt_dd08v TYPE TABLE OF dd08v, lt_dd12v TYPE dd12vtab, lt_dd17v TYPE dd17vtab, lt_dd35v TYPE TABLE OF dd35v, lv_index LIKE sy-index, lt_dd36m TYPE dd36mttyp, ls_extras TYPE ty_tabl_extras. FIELD-SYMBOLS: LIKE LINE OF lt_dd12v, LIKE LINE OF lt_dd05m, LIKE LINE OF lt_dd36m, TYPE any. lv_name = ms_item-obj_name. CALL FUNCTION 'DDIF_TABL_GET' EXPORTING name = lv_name langu = mv_language IMPORTING dd02v_wa = ls_dd02v dd09l_wa = ls_dd09l TABLES dd03p_tab = lt_dd03p dd05m_tab = lt_dd05m dd08v_tab = lt_dd08v dd12v_tab = lt_dd12v dd17v_tab = lt_dd17v dd35v_tab = lt_dd35v dd36m_tab = lt_dd36m EXCEPTIONS illegal_input = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_TABL_GET' ). ENDIF. IF ls_dd02v IS INITIAL. RETURN. "" object does not exits ENDIF. CLEAR: ls_dd02v-as4user, ls_dd02v-as4date, ls_dd02v-as4time. * reset numeric field, so XML does not crash IF ls_dd02v-prozpuff = ''. CLEAR ls_dd02v-prozpuff. ENDIF. IF ls_dd02v-datmin = ''. CLEAR ls_dd02v-datmin. ENDIF. IF ls_dd02v-datmax = ''. CLEAR ls_dd02v-datmax. ENDIF. IF ls_dd02v-datavg = ''. CLEAR ls_dd02v-datavg. ENDIF. CLEAR: ls_dd09l-as4user, ls_dd09l-as4date, ls_dd09l-as4time. ASSIGN COMPONENT 'ROWORCOLST' OF STRUCTURE ls_dd09l TO . IF sy-subrc = 0 AND = 'C'. CLEAR . ""To avoid diff errors. This field doesn't exists in all releases ENDIF. LOOP AT lt_dd12v ASSIGNING . CLEAR: -as4user, -as4date, -as4time. ENDLOOP. clear_dd03p_fields( CHANGING ct_dd03p = lt_dd03p ). * remove foreign keys inherited from .INCLUDEs DELETE lt_dd08v WHERE noinherit = 'N'. LOOP AT lt_dd05m ASSIGNING . lv_index = sy-tabix. READ TABLE lt_dd08v WITH KEY fieldname = -fieldname TRANSPORTING NO FIELDS. IF sy-subrc <> 0. DELETE lt_dd05m INDEX lv_index. ENDIF. ENDLOOP. * remove inherited search helps DELETE lt_dd35v WHERE shlpinher = abap_true. LOOP AT lt_dd36m ASSIGNING . lv_index = sy-tabix. READ TABLE lt_dd35v WITH KEY fieldname = -fieldname TRANSPORTING NO FIELDS. IF sy-subrc <> 0. DELETE lt_dd36m INDEX lv_index. ENDIF. ENDLOOP. io_xml->add( iv_name = 'DD02V' ig_data = ls_dd02v ). IF NOT ls_dd09l IS INITIAL. io_xml->add( iv_name = 'DD09L' ig_data = ls_dd09l ). ENDIF. io_xml->add( iv_name = 'DD03P_TABLE' ig_data = lt_dd03p ). io_xml->add( iv_name = 'DD05M_TABLE' ig_data = lt_dd05m ). io_xml->add( iv_name = 'DD08V_TABLE' ig_data = lt_dd08v ). io_xml->add( iv_name = 'DD12V' ig_data = lt_dd12v ). io_xml->add( iv_name = 'DD17V' ig_data = lt_dd17v ). io_xml->add( iv_name = 'DD35V_TALE' ig_data = lt_dd35v ). io_xml->add( iv_name = 'DD36M' ig_data = lt_dd36m ). serialize_texts( io_xml ). serialize_longtexts( io_xml = io_xml iv_longtext_id = c_longtext_id_tabl ). serialize_idoc_segment( io_xml ). ls_extras = read_extras( iv_tabname = lv_name ). io_xml->add( iv_name = c_s_dataname-tabl_extras ig_data = ls_extras ). ENDMETHOD. ENDCLASS. ",8137,False,1725.8351863852024,median "CLASS zcl_gtt_sts_bo_fb_reader DEFINITION PUBLIC INHERITING FROM zcl_gtt_sts_bo_tor_reader CREATE PUBLIC . PUBLIC SECTION. METHODS zif_gtt_sts_bo_reader~get_data REDEFINITION . METHODS zif_gtt_sts_bo_reader~get_track_id_data REDEFINITION . PROTECTED SECTION. METHODS get_docref_data REDEFINITION . PRIVATE SECTION. TYPES: BEGIN OF ts_freight_booking, shipment_type TYPE string, tor_id TYPE /scmtms/s_em_bo_tor_root-tor_id, mtr TYPE /scmtms/s_em_bo_tor_root-mtr, dgo_indicator TYPE /scmtms/s_em_bo_tor_root-dgo_indicator, tspid TYPE bu_id_number, total_distance_km TYPE /scmtms/total_distance_km, total_distance_km_uom TYPE meins, total_duration_net TYPE /scmtms/total_duration_net, pln_grs_duration TYPE /scmtms/total_duration_net, shipping_type TYPE /scmtms/s_em_bo_tor_root-shipping_type, traffic_direct TYPE /scmtms/s_em_bo_tor_root-traffic_direct, tracked_object_type TYPE tt_tracked_object_type, tracked_object_id TYPE tt_tracked_object_id, inc_class_code TYPE /scmtms/s_em_bo_tor_item-inc_class_code, inc_transf_loc_n TYPE /scmtms/s_em_bo_tor_item-inc_transf_loc_n, gro_vol_val TYPE /scmtms/s_em_bo_tor_root-gro_vol_val, gro_vol_uni TYPE /scmtms/s_em_bo_tor_root-gro_vol_uni, gro_wei_val TYPE /scmtms/s_em_bo_tor_root-gro_wei_val, gro_wei_uni TYPE /scmtms/s_em_bo_tor_root-gro_wei_uni, qua_pcs_val TYPE /scmtms/s_em_bo_tor_root-qua_pcs_val, qua_pcs_uni TYPE /scmtms/s_em_bo_tor_root-qua_pcs_uni, trmodcod TYPE /scmtms/s_em_bo_tor_root-trmodcod, carrier_ref_value TYPE tt_carrier_ref_value, carrier_ref_type TYPE tt_carrier_ref_type, shipper_ref_value TYPE tt_shipper_ref_value, shipper_ref_type TYPE tt_shipper_ref_type, pln_arr_loc_id TYPE /scmtms/s_em_bo_tor_stop-log_locid, pln_arr_loc_type TYPE /saptrx/loc_id_type, pln_arr_timest TYPE char16, pln_arr_timezone TYPE timezone, pln_dep_loc_id TYPE /scmtms/s_em_bo_tor_stop-log_locid, pln_dep_loc_type TYPE /saptrx/loc_id_type, pln_dep_timest TYPE char16, pln_dep_timezone TYPE timezone, stop_id TYPE tt_stop_id, ordinal_no TYPE tt_ordinal_no, loc_type TYPE tt_loc_type, loc_id TYPE tt_loc_id, req_doc_line_no TYPE tt_req_doc_line_number, req_doc_no TYPE tt_req_doc_number, req_doc_first_stop TYPE tt_stop, req_doc_last_stop TYPE tt_stop, END OF ts_freight_booking . CONSTANTS: BEGIN OF cs_mbl_doctype, ocean_fb TYPE string VALUE 'T52' ##NO_TEXT, air_fb TYPE string VALUE 'T55' ##NO_TEXT, END OF cs_mbl_doctype . METHODS get_data_from_maintab IMPORTING !ir_maintab TYPE REF TO data !iv_old_data TYPE abap_bool DEFAULT abap_false CHANGING !cs_freight_booking TYPE ts_freight_booking RAISING cx_udm_message . METHODS get_tracked_objects IMPORTING !ir_data TYPE REF TO data !iv_old_data TYPE abap_bool DEFAULT abap_false CHANGING !cs_freight_booking TYPE ts_freight_booking RAISING cx_udm_message . METHODS get_maintabref IMPORTING !is_app_object TYPE trxas_appobj_ctab_wa RETURNING VALUE(rr_maintabref) TYPE REF TO data . METHODS get_vessel_track IMPORTING !ir_data TYPE REF TO data !iv_old_data TYPE abap_bool CHANGING !ct_tracked_object_type TYPE tt_tracked_object_type !ct_tracked_object_id TYPE tt_tracked_object_id RAISING cx_udm_message . METHODS get_vessel_track_id ##RELAX IMPORTING !is_app_object TYPE trxas_appobj_ctab_wa CHANGING !ct_track_id_data TYPE zif_gtt_sts_ef_types=>tt_track_id_data RAISING cx_udm_message . METHODS get_data_from_item IMPORTING !ir_data TYPE REF TO data !iv_old_data TYPE abap_bool DEFAULT abap_false CHANGING !cs_freight_booking TYPE ts_freight_booking RAISING cx_udm_message . METHODS get_flight_number_track IMPORTING !ir_data TYPE REF TO data !iv_old_data TYPE abap_bool CHANGING !ct_tracked_object_type TYPE tt_tracked_object_type !ct_tracked_object_id TYPE tt_tracked_object_id . METHODS get_flight_number_track_id IMPORTING !is_app_object TYPE trxas_appobj_ctab_wa !iv_old_data TYPE abap_bool DEFAULT abap_false CHANGING !ct_track_id_data TYPE zif_gtt_sts_ef_types=>tt_enh_track_id_data . ENDCLASS. CLASS ZCL_GTT_STS_BO_FB_READER IMPLEMENTATION. METHOD get_data_from_item. FIELD-SYMBOLS: TYPE /scmtms/t_em_bo_tor_item, TYPE /scmtms/s_em_bo_tor_root. ASSIGN ir_data->* TO . IF sy-subrc <> 0. MESSAGE e010(zgtt_sts) INTO DATA(lv_dummy) ##needed. zcl_gtt_sts_tools=>throw_exception( ). ENDIF. DATA(lr_item) = mo_ef_parameters->get_appl_table( SWITCH #( iv_old_data WHEN abap_true THEN zif_gtt_sts_constants=>cs_tabledef-fo_item_old ELSE zif_gtt_sts_constants=>cs_tabledef-fo_item_new ) ). ASSIGN lr_item->* TO . IF sy-subrc <> 0. MESSAGE e010(zgtt_sts) INTO lv_dummy. zcl_gtt_sts_tools=>throw_exception( ). ENDIF. ASSIGN [ item_cat = /scmtms/if_tor_const=>sc_tor_item_category-booking parent_node_id = -node_id ] TO FIELD-SYMBOL(). IF sy-subrc <> 0. MESSAGE e010(zgtt_sts) INTO lv_dummy. zcl_gtt_sts_tools=>throw_exception( ). ENDIF. cs_freight_booking-inc_class_code = -inc_class_code. cs_freight_booking-inc_transf_loc_n = -inc_transf_loc_n. cs_freight_booking-gro_vol_val = -gro_vol_val. cs_freight_booking-gro_vol_uni = -gro_vol_uni. cs_freight_booking-gro_wei_val = -gro_wei_val. cs_freight_booking-gro_wei_uni = -gro_wei_uni. IF -trmodcod = zif_gtt_sts_constants=>cs_trmodcod-air. cs_freight_booking-qua_pcs_val = -incl_piece_count. cs_freight_booking-qua_pcs_uni = zif_gtt_sts_constants=>cs_uom-piece. ELSE. cs_freight_booking-qua_pcs_val = -qua_pcs_val. cs_freight_booking-qua_pcs_uni = -qua_pcs_uni. ENDIF. ENDMETHOD. METHOD get_data_from_maintab. FIELD-SYMBOLS: TYPE /scmtms/s_em_bo_tor_root, TYPE /scmtms/t_em_bo_tor_root. ASSIGN ir_maintab->* TO . IF sy-subrc <> 0. MESSAGE e010(zgtt_sts) INTO DATA(lv_dummy) ##needed. zcl_gtt_sts_tools=>throw_exception( ). ENDIF. IF iv_old_data = abap_true. DATA(lr_root_old) = mo_ef_parameters->get_appl_table( zif_gtt_sts_constants=>cs_tabledef-fo_header_old ). ASSIGN lr_root_old->* TO . IF sy-subrc = 0. ASSIGN [ tor_id = -tor_id ] TO . IF sy-subrc <> 0. "" Record was just created RETURN. ENDIF. ENDIF. DATA(lv_before_image) = abap_true. ENDIF. cs_freight_booking-shipment_type = zif_gtt_sts_constants=>cs_shipment_type-tor. cs_freight_booking-tor_id = -tor_id. cs_freight_booking-tspid = -tspid. SHIFT cs_freight_booking-tor_id LEFT DELETING LEADING '0'. cs_freight_booking-dgo_indicator = -dgo_indicator. cs_freight_booking-tspid = get_carrier_name( iv_tspid = cs_freight_booking-tspid ). SELECT SINGLE motscode FROM /sapapo/trtype INTO cs_freight_booking-mtr WHERE ttype = -mtr. SHIFT cs_freight_booking-mtr LEFT DELETING LEADING '0'. /scmtms/cl_tor_helper_root=>det_transient_root_fields( EXPORTING it_key = VALUE #( ( key = -node_id ) ) iv_get_stop_infos = abap_true iv_get_mainitem_info = abap_true iv_before_image = lv_before_image IMPORTING et_tor_add_info = DATA(lt_tor_add_info) ). ASSIGN lt_tor_add_info[ 1 ] TO FIELD-SYMBOL(). IF sy-subrc = 0. cs_freight_booking-pln_grs_duration = -tot_duration. ENDIF. cs_freight_booking-total_duration_net = -total_duration_net. cs_freight_booking-total_distance_km = -total_distance_km. IF cs_freight_booking-total_distance_km IS NOT INITIAL. cs_freight_booking-total_distance_km_uom = zif_gtt_sts_constants=>cs_uom-km. ENDIF. cs_freight_booking-traffic_direct = -traffic_direct. cs_freight_booking-shipping_type = -shipping_type. cs_freight_booking-trmodcod = zcl_gtt_sts_tools=>get_trmodcod( iv_trmodcod = -trmodcod ). ENDMETHOD. METHOD get_docref_data. DATA lv_master_bill_of_landing TYPE string. FIELD-SYMBOLS: TYPE /scmtms/s_em_bo_tor_root, TYPE /scmtms/t_em_bo_tor_root. super->get_docref_data( EXPORTING ir_root = ir_root iv_old_data = iv_old_data CHANGING ct_carrier_ref_value = ct_carrier_ref_value ct_carrier_ref_type = ct_carrier_ref_type ct_shipper_ref_value = ct_shipper_ref_value ct_shipper_ref_type = ct_shipper_ref_type ). ASSIGN ir_root->* TO . IF sy-subrc <> 0. MESSAGE e010(zgtt_sts) INTO DATA(lv_dummy) ##needed. zcl_gtt_sts_tools=>throw_exception( ). ENDIF. IF iv_old_data = abap_true. DATA(lr_root_old) = mo_ef_parameters->get_appl_table( zif_gtt_sts_constants=>cs_tabledef-fo_header_old ). ASSIGN lr_root_old->* TO . IF sy-subrc = 0. ASSIGN [ tor_id = -tor_id ] TO . IF sy-subrc <> 0. MESSAGE e010(zgtt_sts) INTO lv_dummy. zcl_gtt_sts_tools=>throw_exception( ). ENDIF. ENDIF. ENDIF. IF -trmodcod = zif_gtt_sts_constants=>cs_trmodcod-air. IF -tsp_airlcawb IS NOT INITIAL AND -partner_mbl_id IS INITIAL. lv_master_bill_of_landing = -tsp_airlcawb. ELSEIF -tsp_airlcawb IS INITIAL AND -partner_mbl_id IS NOT INITIAL. lv_master_bill_of_landing = -partner_mbl_id. ELSEIF -tsp_airlcawb IS NOT INITIAL AND -partner_mbl_id IS NOT INITIAL. lv_master_bill_of_landing = |{ -tsp_airlcawb }-{ -partner_mbl_id }|. ENDIF. IF lv_master_bill_of_landing IS NOT INITIAL. APPEND lv_master_bill_of_landing TO ct_carrier_ref_value. APPEND cs_mbl_doctype-air_fb TO ct_carrier_ref_type. ENDIF. ELSE. IF -partner_mbl_id IS NOT INITIAL. APPEND -partner_mbl_id TO ct_carrier_ref_value. APPEND cs_mbl_doctype-ocean_fb TO ct_carrier_ref_type. ENDIF. ENDIF. ENDMETHOD. METHOD get_maintabref. FIELD-SYMBOLS TYPE ANY TABLE. ASSIGN is_app_object-maintabref->* TO FIELD-SYMBOL(). IF IS ASSIGNED AND zcl_gtt_sts_tools=>is_table( iv_value = ) = abap_true. ASSIGN TO . LOOP AT ASSIGNING FIELD-SYMBOL(). ASSIGN COMPONENT /scmtms/if_tor_c=>sc_node_attribute-root-tor_cat OF STRUCTURE TO FIELD-SYMBOL(). IF sy-subrc = 0 AND = /scmtms/if_tor_const=>sc_tor_category-booking. GET REFERENCE OF INTO rr_maintabref. EXIT. ENDIF. ENDLOOP. ELSEIF IS ASSIGNED. GET REFERENCE OF INTO rr_maintabref. ENDIF. ENDMETHOD. METHOD get_tracked_objects. get_container_and_mobile_track( EXPORTING ir_data = ir_data iv_old_data = iv_old_data CHANGING ct_tracked_object_type = cs_freight_booking-tracked_object_type ct_tracked_object_id = cs_freight_booking-tracked_object_id ). get_vessel_track( EXPORTING ir_data = ir_data iv_old_data = iv_old_data CHANGING ct_tracked_object_type = cs_freight_booking-tracked_object_type ct_tracked_object_id = cs_freight_booking-tracked_object_id ). get_flight_number_track( EXPORTING ir_data = ir_data iv_old_data = iv_old_data CHANGING ct_tracked_object_type = cs_freight_booking-tracked_object_type ct_tracked_object_id = cs_freight_booking-tracked_object_id ). ENDMETHOD. METHOD get_vessel_track. FIELD-SYMBOLS: TYPE /scmtms/t_em_bo_tor_item, TYPE /scmtms/s_em_bo_tor_root. ASSIGN ir_data->* TO . IF sy-subrc = 0. DATA(lr_item) = mo_ef_parameters->get_appl_table( SWITCH #( iv_old_data WHEN abap_false THEN zif_gtt_sts_constants=>cs_tabledef-fo_item_new ELSE zif_gtt_sts_constants=>cs_tabledef-fo_item_old ) ). ASSIGN lr_item->* TO . IF sy-subrc = 0. ASSIGN [ item_cat = /scmtms/if_tor_const=>sc_tor_item_category-booking parent_node_id = -node_id ]-vessel_id TO FIELD-SYMBOL(). IF sy-subrc = 0. IF IS NOT INITIAL. APPEND cs_track_id-vessel TO ct_tracked_object_id. APPEND TO ct_tracked_object_type. ENDIF. ENDIF. ENDIF. ENDIF. ENDMETHOD. METHOD get_vessel_track_id. FIELD-SYMBOLS: TYPE /scmtms/t_em_bo_tor_item, TYPE /scmtms/s_em_bo_tor_root. ASSIGN is_app_object-maintabref->* TO . IF sy-subrc = 0. DATA(lr_item) = mo_ef_parameters->get_appl_table( iv_tabledef = zif_gtt_sts_constants=>cs_tabledef-fo_item_new ). ASSIGN lr_item->* TO . IF sy-subrc = 0. ASSIGN [ item_cat = /scmtms/if_tor_const=>sc_tor_item_category-booking parent_node_id = -node_id ]-vessel_id TO FIELD-SYMBOL(). IF sy-subrc = 0. add_track_id_data( EXPORTING is_app_object = is_app_object iv_trxcod = zif_gtt_sts_constants=>cs_trxcod-fo_resource iv_trxid = |{ -tor_id }{ }| CHANGING ct_track_id = ct_track_id_data ). ENDIF. ENDIF. ENDIF. ENDMETHOD. METHOD zif_gtt_sts_bo_reader~get_data. FIELD-SYMBOLS TYPE ts_freight_booking. rr_data = NEW ts_freight_booking( ). ASSIGN rr_data->* TO . IF sy-subrc <> 0. MESSAGE e010(zgtt_sts) INTO DATA(lv_dummy) ##needed. zcl_gtt_sts_tools=>throw_exception( ). ENDIF. DATA(lr_maintabref) = get_maintabref( is_app_object ). get_data_from_maintab( EXPORTING iv_old_data = iv_old_data ir_maintab = lr_maintabref CHANGING cs_freight_booking = ). IF IS INITIAL. RETURN. ENDIF. get_tracked_objects( EXPORTING iv_old_data = iv_old_data ir_data = lr_maintabref CHANGING cs_freight_booking = ). IF -tracked_object_id IS INITIAL. APPEND '' TO -tracked_object_id. ENDIF. get_data_from_item( EXPORTING iv_old_data = iv_old_data ir_data = lr_maintabref CHANGING cs_freight_booking = ). get_docref_data( EXPORTING iv_old_data = iv_old_data ir_root = lr_maintabref CHANGING ct_carrier_ref_value = -carrier_ref_value ct_carrier_ref_type = -carrier_ref_type ct_shipper_ref_value = -shipper_ref_value ct_shipper_ref_type = -shipper_ref_type ). IF -carrier_ref_value IS INITIAL. APPEND '' TO -carrier_ref_value. ENDIF. IF -shipper_ref_value IS INITIAL. APPEND '' TO -shipper_ref_value. ENDIF. get_data_from_stop( EXPORTING ir_data = lr_maintabref iv_old_data = iv_old_data CHANGING cv_pln_dep_loc_id = -pln_dep_loc_id cv_pln_dep_loc_type = -pln_dep_loc_type cv_pln_dep_timest = -pln_dep_timest cv_pln_dep_timezone = -pln_dep_timezone cv_pln_arr_loc_id = -pln_arr_loc_id cv_pln_arr_loc_type = -pln_arr_loc_type cv_pln_arr_timest = -pln_arr_timest cv_pln_arr_timezone = -pln_arr_timezone ct_stop_id = -stop_id ct_ordinal_no = -ordinal_no ct_loc_type = -loc_type ct_loc_id = -loc_id ). get_requirement_doc_list( EXPORTING ir_data = lr_maintabref iv_old_data = iv_old_data CHANGING ct_req_doc_line_no = -req_doc_line_no ct_req_doc_no = -req_doc_no ct_req_doc_first_stop = -req_doc_first_stop ct_req_doc_last_stop = -req_doc_last_stop ). IF -req_doc_no IS INITIAL. APPEND '' TO -req_doc_line_no. ENDIF. ENDMETHOD. METHOD zif_gtt_sts_bo_reader~get_track_id_data. ""FB DATA: lr_item_new TYPE REF TO data, lr_item_old TYPE REF TO data, lr_root_new TYPE REF TO data, lr_root_old TYPE REF TO data, lt_track_id_data_new TYPE zif_gtt_sts_ef_types=>tt_enh_track_id_data, lt_track_id_data_old TYPE zif_gtt_sts_ef_types=>tt_enh_track_id_data. FIELD-SYMBOLS: TYPE /scmtms/t_em_bo_tor_item, TYPE /scmtms/t_em_bo_tor_item, TYPE /scmtms/s_em_bo_tor_root, TYPE /scmtms/t_em_bo_tor_root, TYPE /scmtms/t_em_bo_tor_root, TYPE /scmtms/t_em_bo_tor_root, TYPE /scmtms/t_em_bo_tor_root. CLEAR et_track_id_data. ASSIGN is_app_object-maintabref->* TO . IF sy-subrc <> 0. RETURN. ENDIF. lr_root_new = mo_ef_parameters->get_appl_table( iv_tabledef = zif_gtt_sts_constants=>cs_tabledef-fo_header_new ). ASSIGN lr_root_new->* TO . IF sy-subrc <> 0. MESSAGE e010(zgtt_sts) INTO DATA(lv_dummy) ##needed. zcl_gtt_sts_tools=>throw_exception( ). ENDIF. lr_root_old = mo_ef_parameters->get_appl_table( iv_tabledef = zif_gtt_sts_constants=>cs_tabledef-fo_header_old ). ASSIGN lr_root_old->* TO . IF sy-subrc <> 0. MESSAGE e010(zgtt_sts) INTO lv_dummy. zcl_gtt_sts_tools=>throw_exception( ). ENDIF. add_track_id_data( EXPORTING is_app_object = is_app_object iv_trxcod = zif_gtt_sts_constants=>cs_trxcod-fo_number iv_trxid = |{ -tor_id }| CHANGING ct_track_id = et_track_id_data ). get_flight_number_track_id( EXPORTING is_app_object = is_app_object CHANGING ct_track_id_data = lt_track_id_data_new ). get_flight_number_track_id( EXPORTING is_app_object = is_app_object iv_old_data = abap_true CHANGING ct_track_id_data = lt_track_id_data_old ). get_container_mobile_track_id( EXPORTING is_app_object = is_app_object CHANGING ct_track_id_data = lt_track_id_data_new ). get_container_mobile_track_id( EXPORTING is_app_object = is_app_object iv_old_data = abap_true CHANGING ct_track_id_data = lt_track_id_data_old ). lr_item_new = mo_ef_parameters->get_appl_table( iv_tabledef = zif_gtt_sts_constants=>cs_tabledef-fo_item_new ). lr_item_old = mo_ef_parameters->get_appl_table( iv_tabledef = zif_gtt_sts_constants=>cs_tabledef-fo_item_old ). DATA(lr_tor_req_root_new) = mo_ef_parameters->get_appl_table( /scmtms/cl_scem_int_c=>sc_table_definition-bo_tor-req_root ). DATA(lr_tor_req_root_old) = mo_ef_parameters->get_appl_table( /scmtms/cl_scem_int_c=>sc_table_definition-bo_tor-req_root_before ). ASSIGN [ node_id = -node_id ] TO FIELD-SYMBOL(). IF sy-subrc = 0. DATA(lv_deleted) = zcl_gtt_sts_tools=>check_is_fo_deleted( is_root_new = is_root_old = ). IF lv_deleted = zif_gtt_sts_ef_constants=>cs_condition-true. CLEAR: lt_track_id_data_old, lr_item_old, lr_tor_req_root_old. ENDIF. ENDIF. ASSIGN lr_tor_req_root_new->* TO . IF IS ASSIGNED. LOOP AT ASSIGNING FIELD-SYMBOL(). IF -tor_root_node IS ASSIGNED AND -tor_cat = /scmtms/if_tor_const=>sc_tor_category-freight_unit AND -tor_root_node = -node_id. APPEND VALUE #( key = -tor_id appsys = mo_ef_parameters->get_appsys( ) appobjtype = is_app_object-appobjtype appobjid = is_app_object-appobjid trxcod = zif_gtt_sts_constants=>cs_trxcod-fu_number trxid = -tor_id ) TO lt_track_id_data_new. ENDIF. ENDLOOP. ENDIF. ASSIGN lr_item_new->* TO . IF IS ASSIGNED. LOOP AT ASSIGNING FIELD-SYMBOL(). IF -vessel_id IS ASSIGNED AND -item_id IS ASSIGNED AND -item_cat IS ASSIGNED AND -item_cat = /scmtms/if_tor_const=>sc_tor_item_category-booking. IF -tor_id IS NOT INITIAL AND -vessel_id IS NOT INITIAL. APPEND VALUE #( key = -item_id appsys = mo_ef_parameters->get_appsys( ) appobjtype = is_app_object-appobjtype appobjid = is_app_object-appobjid trxcod = zif_gtt_sts_constants=>cs_trxcod-fo_resource trxid = |{ -tor_id }{ -vessel_id }| ) TO lt_track_id_data_new. ENDIF. ENDIF. ENDLOOP. ENDIF. ASSIGN lr_tor_req_root_old->* TO . IF sy-subrc = 0 AND lv_deleted = zif_gtt_sts_ef_constants=>cs_condition-false. LOOP AT ASSIGNING FIELD-SYMBOL(). IF -tor_root_node IS ASSIGNED AND -tor_cat = /scmtms/if_tor_const=>sc_tor_category-freight_unit AND -tor_root_node = -node_id. APPEND VALUE #( key = -tor_id appsys = mo_ef_parameters->get_appsys( ) appobjtype = is_app_object-appobjtype appobjid = is_app_object-appobjid trxcod = zif_gtt_sts_constants=>cs_trxcod-fu_number trxid = -tor_id ) TO lt_track_id_data_old. ENDIF. ENDLOOP. ENDIF. ASSIGN lr_item_old->* TO . IF sy-subrc = 0 AND lv_deleted = zif_gtt_sts_ef_constants=>cs_condition-false. LOOP AT ASSIGNING FIELD-SYMBOL(). IF -vessel_id IS ASSIGNED AND -item_id IS ASSIGNED AND -item_cat IS ASSIGNED AND -item_cat = /scmtms/if_tor_const=>sc_tor_item_category-booking. IF -tor_id IS NOT INITIAL AND -vessel_id IS NOT INITIAL. APPEND VALUE #( key = -item_id appsys = mo_ef_parameters->get_appsys( ) appobjtype = is_app_object-appobjtype appobjid = is_app_object-appobjid trxcod = zif_gtt_sts_constants=>cs_trxcod-fo_resource trxid = |{ -tor_id }{ -vessel_id }| ) TO lt_track_id_data_old. ENDIF. ENDIF. ENDLOOP. ENDIF. zcl_gtt_sts_tools=>get_track_obj_changes( EXPORTING is_app_object = is_app_object iv_appsys = mo_ef_parameters->get_appsys( ) it_track_id_data_new = lt_track_id_data_new it_track_id_data_old = lt_track_id_data_old CHANGING ct_track_id_data = et_track_id_data ). ENDMETHOD. METHOD get_flight_number_track. FIELD-SYMBOLS: TYPE /scmtms/t_em_bo_tor_item, TYPE /scmtms/s_em_bo_tor_root. ASSIGN ir_data->* TO . IF sy-subrc = 0. DATA(lr_item) = mo_ef_parameters->get_appl_table( SWITCH #( iv_old_data WHEN abap_false THEN zif_gtt_sts_constants=>cs_tabledef-fo_item_new ELSE zif_gtt_sts_constants=>cs_tabledef-fo_item_old ) ). ASSIGN lr_item->* TO . IF sy-subrc = 0. ASSIGN [ item_cat = /scmtms/if_tor_const=>sc_tor_item_category-booking parent_node_id = -node_id ] TO FIELD-SYMBOL(). IF sy-subrc = 0 AND -mtr = zif_gtt_sts_constants=>cs_mtr-air AND -flight_code IS NOT INITIAL AND -flight_number IS NOT INITIAL. APPEND cs_track_id-flight_number TO ct_tracked_object_id. APPEND -flight_code TO ct_tracked_object_type. ENDIF. ENDIF. ENDIF. ENDMETHOD. METHOD get_flight_number_track_id. FIELD-SYMBOLS: TYPE /scmtms/t_em_bo_tor_item, TYPE /scmtms/s_em_bo_tor_root. ASSIGN is_app_object-maintabref->* TO . IF sy-subrc = 0. DATA(lv_tabledef_tor_item) = SWITCH #( iv_old_data WHEN abap_false THEN zif_gtt_sts_constants=>cs_tabledef-fo_item_new ELSE zif_gtt_sts_constants=>cs_tabledef-fo_item_old ). DATA(lr_item) = mo_ef_parameters->get_appl_table( iv_tabledef = lv_tabledef_tor_item ). ASSIGN lr_item->* TO . IF sy-subrc = 0. ASSIGN [ item_cat = /scmtms/if_tor_const=>sc_tor_item_category-booking parent_node_id = -node_id ] TO FIELD-SYMBOL(). IF sy-subrc = 0 AND -mtr = zif_gtt_sts_constants=>cs_mtr-air AND -flight_code IS NOT INITIAL AND -flight_number IS NOT INITIAL. APPEND VALUE #( appsys = mo_ef_parameters->get_appsys( ) appobjtype = is_app_object-appobjtype appobjid = is_app_object-appobjid trxcod = zif_gtt_sts_constants=>cs_trxcod-fo_resource trxid = |{ -tor_id }{ -flight_code }| ) TO ct_track_id_data. ENDIF. ENDIF. ENDIF. ENDMETHOD. ENDCLASS. ",8135,False,1915.078736196423,median "package com.smbc.characters { import com.explodingRabbit.cross.gameplay.statusEffects.StatFxFlash; import com.explodingRabbit.cross.gameplay.statusEffects.StatusProperty; import com.explodingRabbit.display.CustomMovieClip; import com.explodingRabbit.utils.CustomDictionary; import com.explodingRabbit.utils.CustomTimer; import com.smbc.data.AnimationTimers; import com.smbc.data.CharacterInfo; import com.smbc.data.DamageValue; import com.smbc.data.GameSettings; import com.smbc.data.MovieClipInfo; import com.smbc.data.MusicType; import com.smbc.data.PaletteTypes; import com.smbc.data.PickupInfo; import com.smbc.data.SoundNames; import com.smbc.enemies.Enemy; import com.smbc.enums.RyuSimonThrowType; import com.smbc.enums.RyuSpecialWeapon; import com.smbc.graphics.BmdSkinCont; import com.smbc.graphics.HudAlwaysOnTop; import com.smbc.graphics.fontChars.FontCharRyu; import com.smbc.ground.Brick; import com.smbc.ground.Ground; import com.smbc.ground.Platform; import com.smbc.ground.SimpleGround; import com.smbc.ground.SpringRed; import com.smbc.interfaces.IAttackable; import com.smbc.interfaces.ICustomTimer; import com.smbc.level.CharacterSelect; import com.smbc.level.TitleLevel; import com.smbc.main.LevObj; import com.smbc.managers.TutorialManager; import com.smbc.pickups.Pickup; import com.smbc.pickups.Vine; import com.smbc.projectiles.Projectile; import com.smbc.projectiles.RyuProjectile; import com.smbc.sound.MusicInfo; import com.smbc.text.TextFieldContainer; import com.smbc.utils.CharacterSequencer; import flash.display.DisplayObject; import flash.display.MovieClip; import flash.events.TimerEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.utils.Dictionary; public class Ryu extends Character { public static const CHAR_NAME:String = CharacterInfo.Ryu[ CharacterInfo.IND_CHAR_NAME ]; public static const CHAR_NAME_CAPS:String = CharacterInfo.Ryu[ CharacterInfo.IND_CHAR_NAME_CAPS ]; public static const CHAR_NAME_TEXT:String = CharacterInfo.Ryu[ CharacterInfo.IND_CHAR_NAME_MENUS ]; public static const CHAR_NUM:int = CharacterInfo.Ryu[ CharacterInfo.IND_CHAR_NUM ]; public static const PAL_ORDER_ARR:Array = [ PaletteTypes.FLASH_POWERING_UP ]; public static const IND_CI_Ryu:int = 1; protected static const RYU_ART_OF_FIRE_WHEEL:String = PickupInfo.RYU_ART_OF_FIRE_WHEEL; protected static const RYU_SHURIKEN:String = PickupInfo.RYU_SHURIKEN; protected static const RYU_WINDMILL_SHURIKEN:String = PickupInfo.RYU_WINDMILL_SHURIKEN; protected static const RYU_FIRE_DRAGON_BALL:String = PickupInfo.RYU_FIRE_DRAGON_BALL; protected static const RYU_JUMP_SLASH:String = PickupInfo.RYU_JUMP_SLASH; protected static const RYU_INFINITE_JUMP_SLASH:String = PickupInfo.RYU_INFINITE_JUMP_SLASH; protected static const RYU_SCROLL:String = PickupInfo.RYU_SCROLL; protected static const RYU_SWORD_EXTENSION:String = PickupInfo.RYU_SWORD_EXTENSION; public static const RYU_NINJITSU_AMMO_BIG:String = PickupInfo.RYU_NINJITSU_AMMO_BIG; public static const RYU_NINJITSU_AMMO_SMALL:String = PickupInfo.RYU_NINJITSU_AMMO_SMALL; public static const OBTAINABLE_UPGRADES_ARR:Array = [ [ RYU_SWORD_EXTENSION ], [ RYU_SHURIKEN, RYU_ART_OF_FIRE_WHEEL, RYU_WINDMILL_SHURIKEN, RYU_FIRE_DRAGON_BALL, RYU_JUMP_SLASH, RYU_SCROLL ] ]; override public function get classicGetMushroomUpgrades():Vector. { return Vector.([ RYU_SWORD_EXTENSION ]); } override public function get classicGetFireFlowerUpgrades():Vector. { return Vector.([ RYU_SCROLL ]); } override public function get classicLoseFireFlowerUpgrades():Vector. { return Vector.([ ]); } public static const MUSHROOM_UPGRADES:Array = [ ]; public static const NEVER_LOSE_UPGRADES:Array = [ RYU_SHURIKEN, RYU_ART_OF_FIRE_WHEEL, RYU_WINDMILL_SHURIKEN, RYU_FIRE_DRAGON_BALL, RYU_JUMP_SLASH, RYU_SCROLL ]; public static const RESTORABLE_UPGRADES:Array = [ ]; public static const START_WITH_UPGRADES:Array = [ RYU_SHURIKEN ]; public static const SINGLE_UPGRADES_ARR:Array = [ RYU_SHURIKEN, RYU_ART_OF_FIRE_WHEEL, RYU_WINDMILL_SHURIKEN, RYU_FIRE_DRAGON_BALL, RYU_JUMP_SLASH ]; public static const REPLACEABLE_UPGRADES_ARR:Array = [ ]; public static const TITLE_SCREEN_UPGRADES:Array = [ MUSHROOM, RYU_SHURIKEN ]; private static const CLASSIC_DEFAULT_AMMO:int = 25; private static const NINJITSU_AMMO_MAX_DEFAULT:int = 99; private static const NINJITSU_AMMO_MAX_SCROLL:int = 200; public static const ICON_ORDER_ARR:Array = [ RYU_SHURIKEN, RYU_ART_OF_FIRE_WHEEL, RYU_WINDMILL_SHURIKEN, RYU_FIRE_DRAGON_BALL, RYU_JUMP_SLASH, RYU_SWORD_EXTENSION, RYU_SCROLL ]; private static const AMMO_TYPE_NINJITSU:String = ""ninjitsuAmmoName""; public static const AMMO_ARR:Array = [ [ AMMO_TYPE_NINJITSU, 50, NINJITSU_AMMO_MAX_DEFAULT, 1 ] ]; public static const AMMO_DEPLETION_ARR:Array = [ [ RYU_SHURIKEN, 3], [ RYU_ART_OF_FIRE_WHEEL, 5], [ RYU_WINDMILL_SHURIKEN, 5], [ RYU_FIRE_DRAGON_BALL, 5], [ RYU_JUMP_SLASH, 5 ] ]; public static const AMMO_DCT:CustomDictionary = new CustomDictionary(); public static const AMMO_DEPLETION_DCT:CustomDictionary = new CustomDictionary(); public static const DROP_ARR:Array = [ [ 0, RYU_NINJITSU_AMMO_SMALL ], [ .8, RYU_NINJITSU_AMMO_BIG ] ]; public static const WIN_SONG_DUR:int = 4000; private var SUBWEAPON_OVERRIDE:String = RYU_JUMP_SLASH; public static const CHAR_SEL_END_DUR:int = 1900; private const DIE_TMR_DEL_NORMAL:int = 3800; private const DIE_TMR_DEL_NORMAL_MAX:int = 6000; private const DIE_TMR_DEL_PIT:int = 3800; private const SECONDS_LEFT_SND:String = SoundNames.BGM_RYU_SECONDS_LEFT; private const SND_MUSIC_WIN:String = SoundNames.MFX_RYU_WIN; private static const CLR_GRAY:uint = 0xff8989a3; private static const CLR_SKIN:uint = 0xffffc4ea; private static const CLR_BROWN_OUTLINE:uint = 0xff561d00; private static const CLR_BLUE:uint = 0xff9290ff; private static const CLR_BLOOD_RED:uint = 0xffae1212; private static const CLR_BLACK_RED_OUTLINE:uint = 0xff2d0f00; private const REPL_COLOR_1_1:uint = CLR_BROWN_OUTLINE; private const REPL_COLOR_2_1:uint = CLR_GRAY; private const REPL_COLOR_3_1:uint = CLR_SKIN; private const REPL_COLOR_1_2:uint = CLR_BROWN_OUTLINE; private const REPL_COLOR_2_2:uint = CLR_BLUE; private const REPL_COLOR_3_2:uint = CLR_SKIN; private const REPL_COLOR_1_3:uint = CLR_BLACK_RED_OUTLINE; private const REPL_COLOR_2_3:uint = CLR_BLOOD_RED; private const REPL_COLOR_3_3:uint = CLR_SKIN; private static const FL_AMMO_ICON:String = ""ninjitsuAmmo""; private static const FL_CHECK_ATK_RECT_STAND:String = ""attack-2""; private static const FL_CHECK_ATK_RECT_FALL:String = ""fallAttackStart""; private static const FL_CHECK_ATK_RECT_CROUCH:String = ""crouchAttack-2""; private static const FL_ATTACK_START:String = ""attackStart""; private static const FL_ATTACK_END:String = ""attackEnd""; private static const FL_STAND_START:String = ""standStart""; private static const FL_STAND_END:String = ""standEnd""; public static const FL_WALK_START:String = ""walkStart""; public static const FL_WALK_END:String = ""walkEnd""; private static const FL_THROW_START:String = ""throwStart""; private static const FL_THROW_END:String = ""throwEnd""; private static const FL_CROUCH:String = ""crouch""; private static const FL_CROUCH_ATTACK_START:String = ""crouchAttackStart""; private static const FL_CROUCH_ATTACK_END:String = ""crouchAttackEnd""; private static const FL_CROUCH_THROW_START:String = ""crouchThrowStart""; private static const FL_CROUCH_THROW_END:String = ""crouchThrowEnd""; private static const FL_FALL:String = ""fall""; private static const FL_FALL_ATTACK_START:String = ""fallAttackStart""; private static const FL_FALL_ATTACK_END:String = ""fallAttackEnd""; private static const FL_FALL_THROW_START:String = ""fallThrowStart""; private static const FL_FALL_THROW_END:String = ""fallThrowEnd""; public static const FL_CLIMB_START:String = ""climbStart""; public static const FL_CLIMB_END:String = ""climbEnd""; private static const FL_CLIMB_STOP:String = ""climbStop""; private static const FL_CLIMB_THROW_START:String = ""climbThrowStart""; private static const FL_CLIMB_THROW_END:String = ""climbThrowEnd""; private static const FL_CLIMB_THROW_BACKWARDS_START:String = ""climbThrowBackwardsStart""; private static const FL_CLIMB_THROW_BACKWARDS_END:String = ""climbThrowBackwardsEnd""; public static const FL_CLIMB_THROW_BACKWARDS_PROJECTILE:String = ""climbThrowBackwards-2""; private static const FL_CLIMB_POLE_START:String = ""climbPoleStart""; private static const FL_CLIMB_POLE_END:String = ""climbPoleEnd""; public static const FL_FLIP_START:String = ""flipStart""; public static const FL_FLIP_END:String = ""flipEnd""; public static const FL_JUMP_SLASH_START:String = ""jumpSlashStart""; public static const FL_JUMP_SLASH_END:String = ""jumpSlashEnd""; private static const FL_TAKE_DAMAGE:String = ""takeDamage""; private static const FL_DIE:String = ""die""; private static const SWORD_NAME:String = ""swordStg""; private static const SWORD_WAVE_NAME:String = ""swordWaveStg""; private const CHOOSE_CHAR_SEQ:Array = [ [ 1, pressRhtBtn ], [ 100, pressJmpBtn ], [ 1, pressUpBtn ] ]; private static const A_RECT_NORMAL:Rectangle = new Rectangle(16,-50,48,13); private static const A_RECT_WAVE_NORMAL:Rectangle = new Rectangle(16,-50,75,32); private static const A_RECT_CROUCH:Rectangle = new Rectangle(16,-38,48,15); private static const A_RECT_WAVE_CROUCH:Rectangle = new Rectangle(16,-38,79,32); public static const SN_RYU_ATTACK:String = SoundNames.SFX_RYU_ATTACK; private static const SN_GET_PICKUP:String = SoundNames.SFX_RYU_GET_PICKUP; private static const SN_JUMP_SLASH:String = SoundNames.SFX_RYU_JUMP_SLASH; public static const SN_RYU_DAMAGE_ENEMY:String = SoundNames.SFX_RYU_DAMAGE_ENEMY; public static const SN_RYU_JUMP:String = SoundNames.SFX_RYU_JUMP; public static const ST_CLIMB:String = ""climb""; public static const WALK_START_LAB:String = FL_WALK_START; public static const WALK_END_LAB_PLAIN:String = ""walk-4""; private static const WALK_END_LAB_HAGGLE:String = ""walkEnd""; // public static var walkEndLab:String = FL_WALK_END; public static const WALK_SPEED:int = 185; public static const JUMP_PWR:int = 565; public static const JUMP_PWR_WATER:int = 400; private static const CLIMB_JUMP_PWR:int = 300; private static const CLIMB_TOP_JUMP_PWR:int = 430; public static const GRAVITY:int = 1400; private static const GRAVITY_WATER:int = 500; private static const DEF_SPRING_PWR:int = 500; private static const BOOST_SPRING_PWR:int = 1000; private static const VY_MAX_PSV:int = 700; public static const CLIMB_SPEED:int = 120; private static const FLIP_MAX_VY:int = -200; private static const BOUNCE_POWER:int = 550; private static const CLIMB_GROUND_CHECK_DIST:int = 50; private static const CLIMB_TOP_JUMP_OFS:int = -10; private static const CLIMB_TOP_OFS:int = 20; private static const CLIMB_BOT_OFS:int = 25; private static const CLIMB_BOT_MAX_GRAPPLE_INCREASE:int = 10; private static const CLIMB_BOT_GRAPPLE_TEST_INC:int = 2; private const DIE_VERT_BOOST:int = 385; private const DIE_HORZ_BOOST:int = 150; public static const CLIMB_ANIM_TMR:CustomTimer = AnimationTimers.ANIM_VERY_SLOW_TMR; public static const FLIP_ANIM_TMR:CustomTimer = AnimationTimers.ANIM_FAST_TMR; private static const WALK_ANIM_TMR:CustomTimer = AnimationTimers.ANIM_MODERATE_TMR; private static const STAND_ANIM_TMR:CustomTimer = AnimationTimers.ANIM_SLOWEST_TMR; private static const ATTACK_ANIM_TMR:CustomTimer = new CustomTimer(45); public const CANCEL_GRAPPLE_TMR:CustomTimer = new CustomTimer(250,1); private static const FLIP_TMR:CustomTimer = new CustomTimer(400,1); private var haggleMan:Boolean; private static const ATTACK_FRAMES_DCT:CustomDictionary = new CustomDictionary(); private static const SWORD_FRAMES_1_ARR:Array = [ FL_ATTACK_START,""attack-2"",""attack-3"",FL_FALL_ATTACK_START,""fallAttack-2"",""fallAttack-3"",FL_CROUCH_ATTACK_START,""crouchAttack-2"",""crouchAttack-3"" ]; private static const SWORD_FRAMES_2_ARR:Array = [ ""attack-4"",""attack-5"",""fallAttack-4"",""fallAttack-5"",""crouchAttack-4"",""crouchAttack-5"" ]; private static const SWORD_WAVE_FRAMES_ARR:Array = [ FL_ATTACK_START,""attack-2"",""attack-3"", FL_FALL_ATTACK_START,""fallAttack-2"",""fallAttack-3"",FL_CROUCH_ATTACK_START,""crouchAttack-2"",""crouchAttack-3"" ]; private static const THROW_PROJECTILE_FRAMES_DCT:CustomDictionary = new CustomDictionary(); private const HIT_DIST_OVER_OFFSET:int = 30; private static const MAX_PROJECTILES_ON_SCREEN:int = 1; private static const PT_STAR_BIG:String = RyuProjectile.TYPE_WINDMILL_SHURIKEN; private static const PT_STAR_SMALL:String = RyuProjectile.TYPE_SHURIKEN; private static const NINJITSU_AMMO_BIG_VALUE:int = 10; private static const NINJITSU_AMMO_SMALL_VALUE:int = 5; private var startedDeathMusic:Boolean; public var climbPlat:Platform; private const MAX_PLAT_DIST:int = 30; private const NSF_STR_DIE:String = MusicInfo.CHAR_STR_RYU + MusicInfo.TYPE_DIE; public var swordStg:MovieClip; public var swordWaveStg:MovieClip; private var sword:MovieClip; private var swordWave:MovieClip; private static var attackFramesArr:Array = [ ""attack-2"",""attack-3"", ""fallAttack-2"",""fallAttack-3"", ""crouchAttack-2"",""crouchAttack-3"" ]; private static var attackFramesHaggleManArr:Array = [ ""attackStart"",""attack-2"", ""fallAttackStart"",""fallAttack-2"", ""crouchAttackStart"",""crouchAttack-2"" ]; private var throwProjectileFramesArr:Array = [ ""throw-2"",""crouchThrow-2"",""fallThrow-2"",""climbThrow-2"",""climbThrowBackwards-2"" ]; public var cancelGrappleGroundPos:Number; private var justCrouched:Boolean; private var attackedInAir:Boolean; private var flipping:Boolean; private var climbThrowing:Boolean; private var topJumpPos:Boolean; private var topClimbPos:Boolean; private var botClimbPos:Boolean; public var forceAttachToWall:Boolean; public var bigStar:RyuProjectile; private var curSubWeapon:String; private var jumpSlash:Boolean; public static const DEFAULT_PROPS_DCT:CustomDictionary = new CustomDictionary(); public static const SKIN_PREVIEW_SIZE:Point = new Point(30,36); public static const SKIN_ORDER:Array = [ SKIN_RYU_NES, SKIN_RYU_SNES, SKIN_RYU_GB, SKIN_RYU_SMS, SKIN_RYU_X1, SKIN_RYU_ATARI, SKIN_RYU_CLONE, SKIN_HAYATE, SKIN_KAEDE, SKIN_SHADOW_SNES, SKIN_HAGGLE_MAN_NES, SKIN_HAGGLE_MAN_SNES ]; public static const SKIN_RYU_NES:int = 0; public static const SKIN_RYU_SNES:int = 1; public static const SKIN_RYU_GB:int = 2; public static const SKIN_HAGGLE_MAN_NES:int = 3; public static const SKIN_HAGGLE_MAN_SNES:int = 4; public static const SKIN_SHADOW_SNES:int = 5; public static const SKIN_RYU_X1:int = 6; public static const SKIN_RYU_ATARI:int = 7; public static const SKIN_RYU_SMS:int = 8; public static const SKIN_RYU_CLONE:int = 9; public static const SKIN_HAYATE:int = 10; public static const SKIN_KAEDE:int = 11; public static const SPECIAL_SKIN_NUMBER:int = SKIN_RYU_X1; public static const ATARI_SKIN_NUMBER:int = SKIN_RYU_ATARI; private var lastThrowType:RyuSimonThrowType; public function Ryu() { charNum = CHAR_NUM; super(); poorBowserFighter = true; if (!DEFAULT_PROPS_DCT.length) { DEFAULT_PROPS_DCT.addItem( new StatusProperty(PR_FLASH_AGG,0, new StatFxFlash(null,AnimationTimers.DEL_FAST,400) ) ); } for each (var prop:StatusProperty in DEFAULT_PROPS_DCT) { addProperty(prop); } _canGetAmmoFromCoinBlocks = true; _canGetAmmoFromBricks = true; _charName = CHAR_NAME; _charNameTxt = CHAR_NAME_TEXT; _charNameCaps = CHAR_NAME_CAPS; winSongDur = WIN_SONG_DUR; _secondsLeftSnd = SECONDS_LEFT_SND; _sndWinMusic = SND_MUSIC_WIN; _secondsLeftSndIsBgm = true; _dieTmrDel = DIE_TMR_DEL_NORMAL; _usesHorzObjs = true; _usesVertObjs = true; boostSpringPwr = BOOST_SPRING_PWR; defSpringPwr = DEF_SPRING_PWR; walkStartLab = WALK_START_LAB; walkEndLab = walkEndLab; } override protected function setObjsToRemoveFromFrames():void { super.setObjsToRemoveFromFrames(); removeObjsFromFrames(SWORD_NAME,SWORD_FRAMES_1_ARR.concat(SWORD_FRAMES_2_ARR),true ); removeObjsFromFrames(SWORD_WAVE_NAME,SWORD_WAVE_FRAMES_ARR,true ); } override public function setCurrentBmdSkin(bmc:BmdSkinCont, characterInitiating:Boolean = false):void { super.setCurrentBmdSkin(bmc); var attackArr:Array = attackFramesArr; if (skinNum == 3 || skinNum == 4) { haggleMan = true; attackArr = attackFramesHaggleManArr; walkEndLab = WALK_END_LAB_HAGGLE; } else { haggleMan = false; walkEndLab = WALK_END_LAB_PLAIN; } if (cState == ST_WALK) setPlayFrame(FL_WALK_START); setSwordVisibility(); ATTACK_FRAMES_DCT.clear(); var n:int = attackArr.length; for (var i:int = 0; i < n; i++) { ATTACK_FRAMES_DCT.addItem(attackArr[i]); } } private function setSwordVisibility():void { var bool:Boolean = true; if ( upgradeIsActive(RYU_SWORD_EXTENSION) ) bool = false; removeObjsFromFrames(SWORD_NAME,SWORD_FRAMES_2_ARR,true, int(bool) ); removeObjsFromFrames(SWORD_WAVE_NAME,SWORD_WAVE_FRAMES_ARR,false, int(!bool) ); } override public function initiate():void { super.initiate(); var n:int = throwProjectileFramesArr.length; for (var i:int = 0; i < n; i++) { THROW_PROJECTILE_FRAMES_DCT.addItem(throwProjectileFramesArr[i]); } throwProjectileFramesArr = null; } override protected function mcReplacePrep(thisMc:MovieClip):void { sword = thisMc.getChildByName(SWORD_NAME) as MovieClip; swordWave = thisMc.getChildByName(SWORD_WAVE_NAME) as MovieClip; } override public function setStats():void { inColor1_1 = REPL_COLOR_1_1; inColor2_1 = REPL_COLOR_2_1; inColor3_1 = REPL_COLOR_3_1; inColor1_2 = REPL_COLOR_1_2; inColor2_2 = REPL_COLOR_2_2; inColor3_2 = REPL_COLOR_3_2; inColor1_3 = REPL_COLOR_1_3; inColor2_3 = REPL_COLOR_2_3; inColor3_3 = REPL_COLOR_3_3; jumpPwr = JUMP_PWR; gravity = GRAVITY; if (level.waterLevel) { defGravity = gravity; gravity = GRAVITY_WATER; defGravityWater = gravity; jumpPwr = JUMP_PWR_WATER; } defSpringPwr = DEF_SPRING_PWR; boostSpringPwr = BOOST_SPRING_PWR; vyMaxPsv = VY_MAX_PSV; //vyMaxNgv = jumpPwr; xSpeed = WALK_SPEED; vxMax = xSpeed; pState2 = true; super.setStats(); beginIdleStance(); /*if (SUBWEAPON_OVERRIDE) { STAT_MNGR.addCharUpgrade(charNum,MUSHROOM); STAT_MNGR.addCharUpgrade(charNum,SUBWEAPON_OVERRIDE); }*/ tsTxt.UpdAmmoIcon(true, FL_AMMO_ICON); setAmmo(AMMO_TYPE_NINJITSU, getAmmo(AMMO_TYPE_NINJITSU) ); sword.visible = false; swordWave.visible = false; ATTACK_ANIM_TMR.addEventListener(TimerEvent.TIMER,attackAnimTmrHandler,false,0,true); addTmr(ATTACK_ANIM_TMR); CANCEL_GRAPPLE_TMR.addEventListener(TimerEvent.TIMER_COMPLETE,cancelGrappleTmrHandler,false,0,true); addTmr(CANCEL_GRAPPLE_TMR); FLIP_TMR.addEventListener(TimerEvent.TIMER_COMPLETE,flipTmrHandler,false,0,true); addTmr(FLIP_TMR); } override protected function startAndDamageFcts(start:Boolean = false):void { super.startAndDamageFcts(start); if (GameSettings.classicMode && start && !upgradeIsActive(classicStartWeapon) && !(level is TitleLevel) ) STAT_MNGR.addCharUpgrade(charNum, classicStartWeapon); setSwordVisibility(); setCurSubWeapon(); updMaxAmmo(); } private function getClassicWeapon(weapon:RyuSpecialWeapon):String { switch(weapon) { case RyuSpecialWeapon.ArtOfFireWheel: return RYU_ART_OF_FIRE_WHEEL; case RyuSpecialWeapon.FireDragonBall: return RYU_FIRE_DRAGON_BALL; case RyuSpecialWeapon.JumpSlash: return RYU_JUMP_SLASH; case RyuSpecialWeapon.Shuriken: return RYU_SHURIKEN; case RyuSpecialWeapon.WindmillShuriken: return RYU_WINDMILL_SHURIKEN; default: return RYU_WINDMILL_SHURIKEN; } } private function get classicStartWeapon():String { return getClassicWeapon(GameSettings.ryuStartWeapon); } private function get classicExtraWeapon():String { return getClassicWeapon(GameSettings.ryuExtraWeapon); } private function updMaxAmmo():void { if (upgradeIsActive(RYU_SCROLL)) setMaxAmmo(AMMO_TYPE_NINJITSU,NINJITSU_AMMO_MAX_SCROLL); else setMaxAmmo(AMMO_TYPE_NINJITSU,NINJITSU_AMMO_MAX_DEFAULT); } private function setCurSubWeapon():void { if ( upgradeIsActive(RYU_ART_OF_FIRE_WHEEL) ) curSubWeapon = RYU_ART_OF_FIRE_WHEEL; else if ( upgradeIsActive(RYU_FIRE_DRAGON_BALL) ) curSubWeapon = RYU_FIRE_DRAGON_BALL; else if ( upgradeIsActive(RYU_JUMP_SLASH) ) curSubWeapon = RYU_JUMP_SLASH; else if ( upgradeIsActive(RYU_SHURIKEN) ) curSubWeapon = RYU_SHURIKEN; else if ( upgradeIsActive(RYU_WINDMILL_SHURIKEN) ) curSubWeapon = RYU_WINDMILL_SHURIKEN; else curSubWeapon = null; } override public function forceWaterStats():void { defGravity = gravity; gravity = GRAVITY_WATER; defGravityWater = gravity; jumpPwr = JUMP_PWR_WATER; super.forceWaterStats(); } override public function forceNonwaterStats():void { gravity = GRAVITY; jumpPwr = JUMP_PWR; super.forceNonwaterStats(); } override protected function checkPlatform():void { if (climbPlat) { if (scaleX > 0) { if (checkPlatDist(nx - climbPlat.hLft)) { detachFromWall(); return; } nx = climbPlat.hLft - hWidth/2; } else { if (checkPlatDist(nx - climbPlat.hRht)) { detachFromWall(); return; } nx = climbPlat.hRht + hWidth/2; } if (checkPlatDist( (ny - hHeight/2) - climbPlat.hMidY) ) { detachFromWall(); return; } ny = climbPlat.hMidY + hHeight/2; setHitPoints(); function checkPlatDist(num:Number):Boolean { if (num < 0) num = -num; if (num > MAX_PLAT_DIST) return true; else return false; } } else super.checkPlatform(); } override protected function movePlayer():void { if (cState == ST_TAKE_DAMAGE) return; if (onGround) { if (dwnBtn || cState == ST_ATTACK) { vx = 0; return; } } if (cState == ST_CLIMB) { if (climbThrowing) return; checkClimbPosition(); if (!topClimbPos && upBtn) vy = -CLIMB_SPEED; else if (!botClimbPos && dwnBtn) vy = CLIMB_SPEED; else vy = 0; return; } else if (rhtBtn && !lftBtn && !wallOnRight) { if (stuckInWall) return; if (cState == ST_VINE) { if (exitVine) getOffVine(); else return; } vx = xSpeed; this.scaleX = 1; } else if (lftBtn && !rhtBtn && !wallOnLeft) { if (stuckInWall) return; if (cState == ST_VINE) { if (exitVine) getOffVine(); else return; } vx = -xSpeed; this.scaleX = -1; } else if ( ( (lftBtn && rhtBtn) || (!lftBtn && !rhtBtn) ) && cState != ST_DIE) vx = 0; } override protected function checkState():void { checkAtkRect = false; hitDistOver = 0; if (cState == ST_VINE) { checkVineBtns(); checkVinePosition(); return; } else if (cState == ST_CLIMB) { if (climbThrowing) return; if (stopAnim && (upBtn || dwnBtn) ) setPlayFrame(FL_CLIMB_START); else if ( (!upBtn && !dwnBtn) || (upBtn && dwnBtn) ) setStopFrame(FL_CLIMB_STOP); return; } else if (cState == ST_TAKE_DAMAGE) return; else if (onGround) { jumped = false; climbPlat = null; cancelGrappleGroundPos = NaN; if (cState != ST_ATTACK && cState != ST_DIE) { if (dwnBtn) { setState(ST_CROUCH); setStopFrame(FL_CROUCH); justCrouched = true; } else if (vx == 0) { if (cState != ST_STAND) beginIdleStance(); } else { if (cState != ST_WALK) { mainAnimTmr = WALK_ANIM_TMR; setPlayFrame(FL_WALK_START); } setState(ST_WALK); } } else if (cState == ST_DIE && !startedDeathMusic) { SND_MNGR.changeMusic( MusicType.DIE ); //SND_MNGR.playSound(SoundNames.MFX_RYU_DIE); EVENT_MNGR.startDieTmr(DIE_TMR_DEL_NORMAL); vx = 0; startedDeathMusic = true; } } else if (cState != ST_ATTACK) // not onGround { setState(ST_JUMP); if (!FLIP_TMR.running && !jumpSlash) setStopFrame(FL_FALL); } if (cState == ST_ATTACK) { var cl:String = currentFrameLabel; for each (var str:String in ATTACK_FRAMES_DCT) { if (cl === convLab(str)) { checkAtkRect = true; var rect:Rectangle; var crouch:Boolean = false; if (cl.indexOf(""crouch"") != -1) crouch = true; if ( !upgradeIsActive(RYU_SWORD_EXTENSION) ) { if (!crouch) rect = A_RECT_NORMAL; else rect = A_RECT_CROUCH; } else { if (!crouch) rect = A_RECT_WAVE_NORMAL; else rect = A_RECT_WAVE_CROUCH; hitDistOver = rect.width*2; } ahRect.x = rect.x; ahRect.y = rect.y; ahRect.width = rect.width; ahRect.height = rect.height; break; } } } } override protected function getMushroomEnd():void { super.getMushroomEnd(); if (GameSettings.tutorials) TutorialManager.TUT_MNGR.gotPowerUp(this); } override public function hitEnemy(enemy:Enemy,side:String):void { if (!starPwr && jumpSlash) landAttack(enemy); else super.hitEnemy(enemy,side); } override public function hitGround(mc:Ground,hType:String):void { if (jumpSlash && mc is IAttackable) landAttack(mc as IAttackable); if (!mc.destroyed) super.hitGround(mc,hType); } private function checkClimbPosition():void { topClimbPos = true; botClimbPos = true; topJumpPos = true; var topPos:Number; var botPos:Number; var tjPos:Number; if (climbPlat) { /*topPos = hTop + CLIMB_TOP_OFS; botPos = hBot - CLIMB_BOT_OFS; tjPos = hTop + CLIMB_TOP_JUMP_OFS; if (topPos >= climbPlat.hTop && topPos <= climbPlat.hBot) topClimbPos = false; if (botPos >= climbPlat.hTop && botPos <= climbPlat.hBot) botClimbPos = false; if (tjPos >= climbPlat.hTop && tjPos <= climbPlat.hBot) topJumpPos = false;*/ return; } // if (!climbPlat) for each (var ground:Ground in level.GROUND_STG_DCT) { if (!ground.onScreen || !ground.visible) continue; if ( (scaleX > 0 && ground.hLft == hRht) || (scaleX < 0 && ground.hRht == hLft) ) { topPos = hTop + CLIMB_TOP_OFS; botPos = hBot - CLIMB_BOT_OFS; tjPos = hTop + CLIMB_TOP_JUMP_OFS; if (topPos >= ground.hTop && topPos <= ground.hBot) topClimbPos = false; if (botPos >= ground.hTop && botPos <= ground.hBot) botClimbPos = false; if (tjPos >= ground.hTop && tjPos <= ground.hBot) topJumpPos = false; /* if (hTop - SLIDE_TOP_OFS <= ground.hBot && hBot - SLIDE_BOT_OFS > ground.hTop && hLft < ground.hRht && hRht >= ground.hLft) { ceilingAboveSlide = true; break; } */ } } } override public function hitPickup(pickup:Pickup,showAnimation:Boolean = true):void { var hadFireFlower:Boolean = upgradeIsActive(FIRE_FLOWER); super.hitPickup(pickup,showAnimation); if (pickup.mainType == PickupInfo.MAIN_TYPE_UPGRADE) { setCurSubWeapon(); switch(pickup.type) { case RYU_SWORD_EXTENSION: { setSwordVisibility(); break; } case RYU_SCROLL: { updMaxAmmo(); break; } case MUSHROOM: { setSwordVisibility(); break; } case FIRE_FLOWER: { setSwordVisibility(); if (hadFireFlower) increaseAmmoByValue(AMMO_TYPE_NINJITSU, NINJITSU_AMMO_SMALL_VALUE * 3); else updMaxAmmo(); break; } } } else { switch(pickup.type) { case RYU_NINJITSU_AMMO_BIG: { increaseAmmoByValue(AMMO_TYPE_NINJITSU,NINJITSU_AMMO_BIG_VALUE); break; } case RYU_NINJITSU_AMMO_SMALL: { increaseAmmoByValue(AMMO_TYPE_NINJITSU,NINJITSU_AMMO_SMALL_VALUE); break; } } } if (!pickup.playsRegularSound && pickup.mainType != PickupInfo.MAIN_TYPE_FAKE && showAnimation) { if (pickup.type == RYU_SCROLL) SND_MNGR.playSound(SoundNames.SFX_RYU_GET_SCROLL); else SND_MNGR.playSound(SN_GET_PICKUP); } } override public function pressJmpBtn():void { if (cState == ST_VINE) return; var lastClimbPlat:Platform = climbPlat; if (cState == ST_CLIMB && !climbThrowing) { if (dwnBtn) detachFromWall(); else if ( (scaleX < 0 && rhtBtn) || (scaleX > 0 && lftBtn) || topJumpPos) { detachFromWall(); vy = -CLIMB_JUMP_PWR; setState(ST_JUMP); startFlip(); SND_MNGR.playSound(SN_RYU_JUMP); if (topJumpPos && ( lastClimbPlat || (scaleX < 0 && !rhtBtn) || (scaleX > 0 && !lftBtn) ) ) { vy = -CLIMB_TOP_JUMP_PWR; if (CANCEL_GRAPPLE_TMR.running) CANCEL_GRAPPLE_TMR.reset(); CANCEL_GRAPPLE_TMR.start(); } } } else if (onGround) { onGround = false; vy = -jumpPwr; setState(ST_JUMP); lState = ST_STAND; jumped = true; startFlip(); SND_MNGR.playSound(SN_RYU_JUMP); } // else if (!onGround && cState == ST_JUMP && upgradeIsActive(RYU_INFINITE_JUMP_SLASH) && !jumpSlash) // jumpSlashStart(); super.pressJmpBtn(); } public function detachFromWall():void { onGround = false; vy = 0; setState(ST_JUMP); setStopFrame(FL_FALL); lState = ST_CLIMB; jumped = true; defyGrav = false; if (climbPlat) { climbPlat.charOnPlat = false; climbPlat = null; } brickState = BRICK_BOUNCER; } override public function pressAtkBtn():void { if (upBtn && GameSettings.classicSpecialInput) { pressedSpecialButton(); return; } if (cState == ST_VINE || cState == ST_CLIMB) { if (cState == ST_CLIMB && canThrowCurWeapon(RyuSimonThrowType.Default)) throwStar(RyuSimonThrowType.Default); return; } super.pressAtkBtn(); if (cState != ST_ATTACK && !jumpSlash) { if (onGround) { if (dwnBtn) setPlayFrame(FL_CROUCH_ATTACK_START); else setPlayFrame(FL_ATTACK_START); } else { setPlayFrame(FL_FALL_ATTACK_START); attackedInAir = true; flipping = false; } setState(ST_ATTACK); mainAnimTmr = ATTACK_ANIM_TMR; SND_MNGR.playSound(SN_RYU_ATTACK); ATTACK_ANIM_TMR.start(); checkState(); } } override protected function getOnVine(_vine:Vine):void { if (cState == ST_TAKE_DAMAGE) takeDamageEnd(); super.getOnVine(_vine); setStopFrame(FL_CLIMB_POLE_START); mainAnimTmr = CLIMB_ANIM_TMR; } override public function slideDownFlagPole():void { super.slideDownFlagPole(); setPlayFrame(FL_CLIMB_POLE_START); nx = level.flagPole.hMidX; mainAnimTmr = CLIMB_ANIM_TMR; } override public function pressSpcBtn():void { super.pressSpcBtn(); pressedSpecialButton(); } private function pressedSpecialButton():void { if (cState == ST_VINE || cState == ST_ATTACK) return; if (cState == ST_JUMP && curSubWeapon == RYU_JUMP_SLASH && !jumpSlash && hasEnoughAmmo(AMMO_TYPE_NINJITSU,RYU_JUMP_SLASH) ) jumpSlashStart(); else if (canThrowCurWeapon(RyuSimonThrowType.Default) ) throwStar(RyuSimonThrowType.Default); } override public function pressSelBtn():void { super.pressSelBtn(); if (cState == ST_VINE || cState == ST_ATTACK || !GameSettings.classicMode || !upgradeIsActive(FIRE_FLOWER) ) return; // trace(""extra: "" + classicExtraWeapon); if (cState == ST_JUMP && classicExtraWeapon == RYU_JUMP_SLASH && !jumpSlash && hasEnoughAmmo(AMMO_TYPE_NINJITSU,RYU_JUMP_SLASH) ) jumpSlashStart(); else if (canThrowCurWeapon(RyuSimonThrowType.Extra) ) throwStar(RyuSimonThrowType.Extra); } override protected function getDefaultAmmo(ammoType:String):int { if (GameSettings.classicMode) return CLASSIC_DEFAULT_AMMO; else return super.getDefaultAmmo(ammoType); } private function jumpSlashStart():void { if (!FLIP_TMR.running) startFlip(); if ( !upgradeIsActive(RYU_INFINITE_JUMP_SLASH) ) decAmmo(AMMO_TYPE_NINJITSU,RYU_JUMP_SLASH); var num1:int = convFrameToInt(FL_FLIP_START); var num2:int = convFrameToInt(FL_JUMP_SLASH_START); var ofs:int = num2 - num1; gotoAndStop(currentFrame + ofs); jumpSlash = true; SND_MNGR.playSound(SN_JUMP_SLASH); } override public function relAtkBtn():void { super.relAtkBtn(); if (GS_MNGR.gameState != GS_PLAY || cState == ST_ATTACK || cState == ST_VINE || pState < 1) return; } override public function pressLftBtn():void { super.pressLftBtn(); if (forceAttachToWall) forceAttachToWall = false; } override public function pressRhtBtn():void { super.pressRhtBtn(); if (forceAttachToWall) forceAttachToWall = false; } private function throwStar(throwType:RyuSimonThrowType):void { if (cState != ST_CLIMB) { lastThrowType = throwType; if (onGround) { if (dwnBtn) setPlayFrame(FL_CROUCH_THROW_START); else setPlayFrame(FL_THROW_START); } else setPlayFrame(FL_FALL_THROW_START); setState(ST_ATTACK); mainAnimTmr = ATTACK_ANIM_TMR; ATTACK_ANIM_TMR.start(); } else if (!climbThrowing) // && cState == ST_CLIMB) { lastThrowType = throwType; if ( (scaleX < 0 && rhtBtn) || (scaleX > 0 && lftBtn) ) setPlayFrame(FL_CLIMB_THROW_BACKWARDS_START); else setPlayFrame(FL_CLIMB_THROW_START); climbThrowing = true; vy = 0; mainAnimTmr = ATTACK_ANIM_TMR; ATTACK_ANIM_TMR.start(); } } private function canThrowCurWeapon(throwType:RyuSimonThrowType):String { var weaponToThrow:String = curSubWeapon; if (throwType == RyuSimonThrowType.Extra && GameSettings.classicMode) weaponToThrow = classicExtraWeapon; var projectileType:String = getRyuProjectileTypeFromPickupType(weaponToThrow); if (projectileType == null || getProjectileCountForType(projectileType) >= MAX_PROJECTILES_ON_SCREEN) return null; else return projectileType; } private function getProjectileCountForType(projectileType:String):int { var count:int = 0; for each(var projectile:Projectile in level.PLAYER_PROJ_DCT) { if (projectile is RyuProjectile && RyuProjectile(projectile).isType(projectileType) ) count++; } return count; } private function getRyuProjectileTypeFromPickupType(pickupType:String):String { switch(pickupType) { case RYU_ART_OF_FIRE_WHEEL: return RyuProjectile.TYPE_ART_OF_FIRE_WHEEL; case RYU_FIRE_DRAGON_BALL: return RyuProjectile.TYPE_FIRE_DRAGON_BALL; case RYU_SHURIKEN: return RyuProjectile.TYPE_SHURIKEN; case RYU_WINDMILL_SHURIKEN: return RyuProjectile.TYPE_WINDMILL_SHURIKEN; default: return null; } } private function getPickupTypeFromProjectileType(projectileType:String):String { switch(projectileType) { case RyuProjectile.TYPE_ART_OF_FIRE_WHEEL: return RYU_ART_OF_FIRE_WHEEL; case RyuProjectile.TYPE_FIRE_DRAGON_BALL: return RYU_FIRE_DRAGON_BALL; case RyuProjectile.TYPE_SHURIKEN: return RYU_SHURIKEN; case RyuProjectile.TYPE_WINDMILL_SHURIKEN: return RYU_WINDMILL_SHURIKEN; default: return null; } } override protected function bounce(enemy:Enemy):void { if (cState == ST_CLIMB) return; super.bounce(enemy); if (cState != ST_ATTACK) startFlip(); } // this function is also called from Spring when Ryu lands on it public function startFlip():void { if (FLIP_TMR.running) FLIP_TMR.reset(); setPlayFrame(FL_FLIP_START); mainAnimTmr = FLIP_ANIM_TMR; FLIP_TMR.start(); } override protected function attackObjPiercing(obj:IAttackable):void { if (jumpSlash) damageAmt = DamageValue.RYU_JUMP_SLASH; else damageAmt = DamageValue.RYU_SWORD; super.attackObjPiercing(obj); if (obj is Enemy && obj.health > 0) SND_MNGR.playSound(SN_RYU_DAMAGE_ENEMY); } override protected function attackObjNonPiercing(obj:IAttackable):void { super.attackObjNonPiercing(obj); if (obj is Enemy) SND_MNGR.playSound(SoundNames.SFX_RYU_ATTACK_ARMOR); } override protected function addAllPowerups():void { for (var i:int = 0; i < 5; i++) { hitRandomUpgrade(charNum,false); } } private function finishAttack():void { ATTACK_ANIM_TMR.reset(); if (ATK_DCT.length != 0) ATK_DCT.clear(); //if (FLIP_TMR.running) // FLIP_TMR.reset(); } override public function groundAbove(g:Ground):void { if ( (cState == ST_CLIMB && g is Platform) || (cState == ST_CLIMB && climbPlat) ) detachFromWall(); super.groundAbove(g); if (cState == ST_CLIMB ) SND_MNGR.removeStoredSound(SND_GAME_HIT_CEILING); } override public function groundOnSide(g:Ground, side:String):void { if (cState == ST_CLIMB) { if (climbPlat) climbPlat.setCharOnPlat(); return; } super.groundOnSide(g,side); if (dead || stuckInWall || lastStuckInWall || (GS_MNGR.gameState != GS_PLAY && !(level is CharacterSelect) ) ) return; var topPos:Number = hTop + CLIMB_TOP_OFS; var botPos:Number = hBot - CLIMB_BOT_OFS; var botMaxGrapple:Number = botPos - CLIMB_BOT_MAX_GRAPPLE_INCREASE; var plat:Boolean = false; var touchingSingleGround:Boolean = true; if (g != null && cState != ST_CLIMB && !onGround && !lastOnGround && ( (side == ""left"" && lftBtn) || (side == ""right"" && rhtBtn) || forceAttachToWall ) ) { if (g is Platform) { if (!CANCEL_GRAPPLE_TMR.running) { attachToWall(g,side); climbPlat = g as Platform; climbPlat.setCharOnPlat(); ny = g.hMidY + hHeight/2; } } else if ( (!CANCEL_GRAPPLE_TMR.running || (CANCEL_GRAPPLE_TMR.running && (side == ""left"" && g.hRht != cancelGrappleGroundPos) || (side == ""right"" && g.hLft != cancelGrappleGroundPos) ) ) && ( (topPos >= g.hTop && topPos <= g.hBot) || (botPos >= g.hTop && botMaxGrapple <= g.hBot) ) ) { for each (var ground:Ground in level.GROUND_STG_DCT) { //if (!ground.onScreen || !ground.visible) // continue; if (hTop <= ground.hBot && hBot >= ground.hTop && hLft <= ground.hRht && hRht >= ground.hLft) { if (ground != g) { touchingSingleGround = false; break; } } } if (touchingSingleGround) { while (botPos > g.hBot) { ny -= CLIMB_BOT_GRAPPLE_TEST_INC; botPos = ny - CLIMB_BOT_OFS; } } attachToWall(g,side); } } } private function beginIdleStance():void { setState(ST_STAND); mainAnimTmr = STAND_ANIM_TMR; setPlayFrame(FL_STAND_START); } override public function groundBelow(g:Ground):void { if (cState == ST_CLIMB) detachFromWall(); super.groundBelow(g); } private function attachToWall(g:Ground,side:String):void { if (side == ""left"") { cancelGrappleGroundPos = g.hRht; scaleX = -1; } else if (side == ""right"") { cancelGrappleGroundPos = g.hLft; scaleX = 1; } jumpSlash = false; forceAttachToWall = false; setState(ST_CLIMB); setStopFrame(FL_CLIMB_STOP); defyGrav = true; vx = 0; vy = 0; jumped = false; climbThrowing = false; if (cState == ST_ATTACK) finishAttack(); checkState(); mainAnimTmr = CLIMB_ANIM_TMR; SND_MNGR.playSound(SN_RYU_JUMP); brickState = BRICK_NONE; } override protected function landOnGround():void { super.landOnGround(); if (cState == ST_CLIMB) defyGrav = false; else if (cState == ST_TAKE_DAMAGE) takeDamageEnd(); forceAttachToWall = false; beginIdleStance(); SND_MNGR.playSound(SN_RYU_JUMP); finishAttack(); jumpSlash = false; checkState(); } override protected function takeDamageStart(source:LevObj):void { super.takeDamageStart(source); damageBoost(source); takeNoDamage = true; disableInput = true; nonInteractive = true; setState(ST_TAKE_DAMAGE); BTN_MNGR.relPlyrBtns(); } override protected function takeDamageEnd():void { disableInput = false; nonInteractive = false; setState(ST_STAND); alpha = TD_ALPHA; noDamageTmr.start(); BTN_MNGR.sendPlayerBtns(); } override public function springLaunch(spring:SpringRed):void { super.springLaunch(spring); if (cState == ST_TAKE_DAMAGE) takeDamageEnd(); if (cState != Character.ST_ATTACK) startFlip(); } override protected function bouncePit():void { if (cState == ST_TAKE_DAMAGE) takeDamageEnd(); return super.bouncePit(); } override protected function setAmmo(ammoType:String, value:int):void { super.setAmmo(ammoType, value); tsTxt.UpdAmmoText(true, getAmmo(ammoType) ); } override public function revivalBoost():void { super.revivalBoost(); hitPickup( new Pickup(RYU_NINJITSU_AMMO_BIG), false ); hitPickup( new Pickup(RYU_NINJITSU_AMMO_BIG), false ); } override protected function initiateNormalDeath(source:LevObj = null):void { super.initiateNormalDeath(source); damageBoost(source); EVENT_MNGR.startDieTmr(DIE_TMR_DEL_NORMAL_MAX); lockFrame = true; } private function damageBoost(source:LevObj = null):void { if (cState == ST_CLIMB || defyGrav) detachFromWall(); var dir:int = 1; if (source) { if (source.nx > nx) dir = -1; } else { if (scaleX > 0) dir = -1; } vy = -DIE_VERT_BOOST; vx = dir*DIE_HORZ_BOOST; scaleX = -dir; onGround = false; setStopFrame(FL_TAKE_DAMAGE); SND_MNGR.playSound(SoundNames.SFX_RYU_TAKE_DAMAGE); } override protected function enterPipeHorz():void { super.enterPipeHorz(); mainAnimTmr = WALK_ANIM_TMR; } override protected function initiatePitDeath():void { _dieTmrDel = DIE_TMR_DEL_PIT; // SND_MNGR.changeMusic(MusicType.DIE); super.initiatePitDeath(); SND_MNGR.changeMusic( MusicType.DIE ); } private function attackAnimTmrHandler(event:TimerEvent):void { animate(ATTACK_ANIM_TMR); } private function cancelGrappleTmrHandler(event:TimerEvent):void { CANCEL_GRAPPLE_TMR.reset(); } private function flipTmrHandler(event:TimerEvent):void { FLIP_TMR.reset(); } override public function chooseCharacter():void { super.chooseCharacter(); var seq:CharacterSequencer = new CharacterSequencer(); seq.startNewSequence(CHOOSE_CHAR_SEQ); var curY:int = GLOB_STG_TOP - TILE_SIZE; var endY:int = GLOB_STG_BOT - TILE_SIZE*2; var groundX:Number = level.getNearestGrid( player.nx + TILE_SIZE*3,-1); var groundDct:CustomDictionary = new CustomDictionary(true); while (curY != endY) { var brick:SimpleGround = new SimpleGround(SimpleGround.BN_BLOCK); brick.x = groundX; brick.y = curY; level.addToLevel(brick); curY += TILE_SIZE; groundDct.addItem(brick); } level.addObj(); for each (brick in groundDct) { brick.checkNearbyGround(); } } override public function fallenCharSelScrn():void { super.fallenCharSelScrn(); cancelCheckState = true; setStopFrame(FL_TAKE_DAMAGE); } override public function animate(ct:ICustomTimer):Boolean { var bool:Boolean = super.animate(ct); if (ct == ATTACK_ANIM_TMR && mainAnimTmr == ATTACK_ANIM_TMR) checkFrame(); return bool; } private function addProjectile(type:String):void { var weapon:String = getPickupTypeFromProjectileType(type); if (weapon == null) return; if ( hasEnoughAmmo(AMMO_TYPE_NINJITSU, weapon) ) { level.addToLevel( new RyuProjectile(this,type) ); decAmmo(AMMO_TYPE_NINJITSU, weapon); } } override public function checkFrame():void { var cl:String = currentLabel; var cf:int = currentFrame; var projType:String; if ( cState == ST_STAND && cl == convLab(FL_STAND_END) ) setPlayFrame(FL_STAND_START); if ((cState == ST_WALK || cState == ST_PIPE) && cl == convLab(walkEndLab) ) setPlayFrame(FL_WALK_START); else if (cState == ST_JUMP) { if (cl == convLab(FL_FLIP_END)) setPlayFrame(FL_FLIP_START); else if (cl == convLab(FL_JUMP_SLASH_END)) gotoAndStop(FL_JUMP_SLASH_START); } else if (cState == ST_ATTACK) { projType = canThrowCurWeapon(lastThrowType); if (projType && GS_MNGR.gameState == GS_PLAY) { for each (var str:String in THROW_PROJECTILE_FRAMES_DCT) { if (cl == convLab(str)) { addProjectile(projType); return; } } } if (cl == convLab(FL_ATTACK_END) || cl == convLab(FL_THROW_END)) { if (onGround) { beginIdleStance(); finishAttack(); } else { setState(ST_JUMP); finishAttack(); setStopFrame(FL_FALL ); } } else if (cl == convLab(FL_CROUCH_ATTACK_END) || cl == convLab(FL_CROUCH_THROW_END)) { setState(ST_CROUCH); setStopFrame(FL_CROUCH); finishAttack(); } else if (cl == convLab(FL_FALL_ATTACK_END) || cl == convLab(FL_FALL_THROW_END)) { setState(ST_JUMP); setStopFrame(FL_FALL); finishAttack(); } } else if (cState == ST_CLIMB) { projType = canThrowCurWeapon(lastThrowType); if (climbThrowing && projType && GS_MNGR.gameState == GS_PLAY) { for each (str in THROW_PROJECTILE_FRAMES_DCT) { if (cl == convLab(str)) { addProjectile(projType); return; } } } if (cl == convLab(FL_CLIMB_END)) setPlayFrame(FL_CLIMB_START); else if (cl == convLab(FL_CLIMB_THROW_END) || cl == convLab(FL_CLIMB_THROW_BACKWARDS_END)) { setState(ST_CLIMB); setStopFrame(FL_CLIMB_STOP); climbThrowing = false; mainAnimTmr = CLIMB_ANIM_TMR; finishAttack(); } } else if (cState == ST_VINE || cState == ST_FLAG_SLIDE) { if (cl == convLab(FL_CLIMB_POLE_END)) setPlayFrame(FL_CLIMB_POLE_START); } super.checkFrame(); } override protected function removeListeners():void { super.removeListeners(); ATTACK_ANIM_TMR.removeEventListener(TimerEvent.TIMER,attackAnimTmrHandler); CANCEL_GRAPPLE_TMR.removeEventListener(TimerEvent.TIMER_COMPLETE,cancelGrappleTmrHandler); FLIP_TMR.removeEventListener(TimerEvent.TIMER_COMPLETE,flipTmrHandler); } override protected function reattachLsrs():void { super.reattachLsrs(); ATTACK_ANIM_TMR.addEventListener(TimerEvent.TIMER,attackAnimTmrHandler,false,0,true); CANCEL_GRAPPLE_TMR.addEventListener(TimerEvent.TIMER_COMPLETE,cancelGrappleTmrHandler,false,0,true); FLIP_TMR.addEventListener(TimerEvent.TIMER_COMPLETE,flipTmrHandler,false,0,true); } override public function cleanUp():void { super.cleanUp(); tsTxt.UpdAmmoIcon(false); tsTxt.UpdAmmoText(false); } override protected function playDefaultPickupSoundEffect():void { SND_MNGR.playSound(SoundNames.SFX_RYU_GET_PICKUP); } } }",16195,True,2931.45451400212,median "CLASS zcl_abapgit_object_wdyn DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super FINAL CREATE PUBLIC . PUBLIC SECTION. INTERFACES zif_abapgit_object . PROTECTED SECTION. PRIVATE SECTION. CONSTANTS c_longtext_id_wc TYPE dokil-id VALUE 'WC' ##NO_TEXT. CONSTANTS c_longtext_id_wd TYPE dokil-id VALUE 'WD' ##NO_TEXT. CONSTANTS c_longtext_name_wc TYPE string VALUE 'LONGTEXTS_WC' ##NO_TEXT. DATA: mt_components TYPE TABLE OF wdy_ctlr_compo_vrs, mt_sources TYPE TABLE OF wdy_ctlr_compo_source_vrs. METHODS: get_limu_objects RETURNING VALUE(rt_objects) TYPE wdy_md_transport_keys, read RETURNING VALUE(rs_component) TYPE wdy_component_metadata RAISING zcx_abapgit_exception, read_controller IMPORTING is_key TYPE wdy_md_controller_key RETURNING VALUE(rs_controller) TYPE wdy_md_controller_meta_data RAISING zcx_abapgit_exception, read_definition IMPORTING is_key TYPE wdy_md_component_key RETURNING VALUE(rs_definition) TYPE wdy_md_component_meta_data RAISING zcx_abapgit_exception, read_view IMPORTING is_key TYPE wdy_md_view_key RETURNING VALUE(rs_view) TYPE wdy_md_view_meta_data RAISING zcx_abapgit_exception, recover_controller IMPORTING is_controller TYPE wdy_md_controller_meta_data RAISING zcx_abapgit_exception, recover_definition IMPORTING is_definition TYPE wdy_md_component_meta_data iv_package TYPE devclass RAISING zcx_abapgit_exception, recover_view IMPORTING is_view TYPE wdy_md_view_meta_data RAISING zcx_abapgit_exception, delta_controller IMPORTING is_controller TYPE wdy_md_controller_meta_data RETURNING VALUE(rs_delta) TYPE svrs2_xversionable_object RAISING zcx_abapgit_exception, delta_definition IMPORTING is_definition TYPE wdy_md_component_meta_data VALUE(iv_package) TYPE devclass RETURNING VALUE(rs_delta) TYPE svrs2_xversionable_object RAISING zcx_abapgit_exception, delta_view IMPORTING is_view TYPE wdy_md_view_meta_data RETURNING VALUE(rs_delta) TYPE svrs2_xversionable_object RAISING zcx_abapgit_exception, add_fm_param_exporting IMPORTING iv_name TYPE string ig_value TYPE any CHANGING ct_param TYPE abap_func_parmbind_tab, add_fm_param_tables IMPORTING iv_name TYPE string CHANGING ct_value TYPE ANY TABLE ct_param TYPE abap_func_parmbind_tab, add_fm_exception IMPORTING iv_name TYPE string iv_value TYPE i CHANGING ct_exception TYPE abap_func_excpbind_tab, add_with_inactive_parts RAISING zcx_abapgit_exception. ENDCLASS. CLASS zcl_abapgit_object_wdyn IMPLEMENTATION. METHOD add_fm_exception. DATA: ls_exception LIKE LINE OF ct_exception. ls_exception-name = iv_name. ls_exception-value = iv_value. INSERT ls_exception INTO TABLE ct_exception. ENDMETHOD. METHOD add_fm_param_exporting. DATA: ls_param LIKE LINE OF ct_param. ls_param-kind = abap_func_exporting. ls_param-name = iv_name. GET REFERENCE OF ig_value INTO ls_param-value. INSERT ls_param INTO TABLE ct_param. ENDMETHOD. METHOD add_fm_param_tables. DATA: ls_param LIKE LINE OF ct_param. ls_param-kind = abap_func_tables. ls_param-name = iv_name. GET REFERENCE OF ct_value INTO ls_param-value. INSERT ls_param INTO TABLE ct_param. ENDMETHOD. METHOD add_with_inactive_parts. DATA: lv_obj_name TYPE trobj_name, lv_object TYPE trobjtype, lt_objects TYPE dwinactiv_tab. FIELD-SYMBOLS: LIKE LINE OF lt_objects. lv_obj_name = ms_item-obj_name. lv_object = ms_item-obj_type. CALL FUNCTION 'RS_INACTIVE_OBJECTS_IN_OBJECT' EXPORTING obj_name = lv_obj_name object = lv_object TABLES inactive_objects = lt_objects EXCEPTIONS object_not_found = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. LOOP AT lt_objects ASSIGNING . zcl_abapgit_objects_activation=>add( iv_type = -object iv_name = -obj_name ). ENDLOOP. ENDMETHOD. METHOD delta_controller. DATA: li_controller TYPE REF TO if_wdy_md_controller, lx_error TYPE REF TO cx_wdy_md_exception, lv_found TYPE abap_bool, ls_key TYPE wdy_md_controller_key, ls_obj_new TYPE svrs2_versionable_object, ls_obj_old TYPE svrs2_versionable_object. FIELD-SYMBOLS: LIKE LINE OF mt_components, LIKE LINE OF mt_sources, TYPE ANY TABLE, TYPE ANY TABLE, TYPE ANY TABLE, TYPE ANY TABLE. ls_key-component_name = is_controller-definition-component_name. ls_key-controller_name = is_controller-definition-controller_name. lv_found = cl_wdy_md_controller=>check_existency( component_name = ls_key-component_name controller_name = ls_key-controller_name ). IF lv_found = abap_false. TRY. li_controller ?= cl_wdy_md_controller=>create_complete( component_name = ls_key-component_name controller_name = ls_key-controller_name controller_type = is_controller-definition-controller_type ). li_controller->save_to_database( ). li_controller->unlock( ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error creating dummy controller: { lx_error->get_text( ) }| ). ENDTRY. ENDIF. ls_obj_new-objtype = wdyn_limu_component_controller. ls_obj_new-objname = ls_key. ls_obj_old-objtype = wdyn_limu_component_controller. ls_obj_old-objname = ls_key. APPEND is_controller-definition TO ls_obj_old-wdyc-defin. LOOP AT mt_components ASSIGNING WHERE component_name = ls_key-component_name AND controller_name = ls_key-controller_name. APPEND TO ls_obj_old-wdyc-ccomp. ENDLOOP. LOOP AT mt_sources ASSIGNING WHERE component_name = ls_key-component_name AND controller_name = ls_key-controller_name. APPEND TO ls_obj_old-wdyc-ccoms. ENDLOOP. ls_obj_old-wdyc-descr = is_controller-descriptions. ls_obj_old-wdyc-cusag = is_controller-controller_usages. ls_obj_old-wdyc-ccomt = is_controller-controller_component_texts. ls_obj_old-wdyc-cpara = is_controller-controller_parameters. ls_obj_old-wdyc-cpart = is_controller-controller_parameter_texts. ls_obj_old-wdyc-cnode = is_controller-context_nodes. ls_obj_old-wdyc-cattr = is_controller-context_attributes. ls_obj_old-wdyc-cmapp = is_controller-context_mappings. * Version 702 doesn't have these two attributes so we * use them dynamically for downward compatibility ASSIGN COMPONENT 'CONTROLLER_EXCEPTIONS' OF STRUCTURE is_controller TO . IF sy-subrc = 0. ASSIGN COMPONENT 'EXCP' OF STRUCTURE ls_obj_old-wdyc TO . IF sy-subrc = 0. = . ENDIF. ENDIF. ASSIGN COMPONENT 'CONTROLLER_EXCEPTIONS_TEXTS' OF STRUCTURE is_controller TO . IF sy-subrc = 0. ASSIGN COMPONENT 'EXCPT' OF STRUCTURE ls_obj_old-wdyc TO . IF sy-subrc = 0. = . ENDIF. ENDIF. ls_obj_old-wdyc-fgrps = is_controller-fieldgroups. CALL FUNCTION 'SVRS_MAKE_OBJECT_DELTA' EXPORTING obj_old = ls_obj_new obj_new = ls_obj_old CHANGING delta = rs_delta EXCEPTIONS inconsistent_objects = 1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from SVRS_MAKE_OBJECT_DELTA' ). ENDIF. ENDMETHOD. METHOD delta_definition. DATA: ls_key TYPE wdy_md_component_key, lv_found TYPE abap_bool, ls_obj_new TYPE svrs2_versionable_object, li_component TYPE REF TO if_wdy_md_component, lx_error TYPE REF TO cx_wdy_md_exception, ls_obj_old TYPE svrs2_versionable_object. ls_key-component_name = is_definition-definition-component_name. lv_found = cl_wdy_md_component=>check_existency( ls_key-component_name ). IF lv_found = abap_false. TRY. cl_wdy_md_component=>create_complete( EXPORTING name = ls_key-component_name IMPORTING component = li_component CHANGING devclass = iv_package ). li_component->save_to_database( ). li_component->unlock( ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error creating dummy component: { lx_error->get_text( ) }| ). ENDTRY. ENDIF. ls_obj_new-objtype = wdyn_limu_component_definition. ls_obj_new-objname = ls_key-component_name. ls_obj_old-objtype = wdyn_limu_component_definition. ls_obj_old-objname = ls_key-component_name. APPEND is_definition-definition TO ls_obj_old-wdyd-defin. ls_obj_old-wdyd-descr = is_definition-descriptions. ls_obj_old-wdyd-cusag = is_definition-component_usages. ls_obj_old-wdyd-intrf = is_definition-interface_implementings. ls_obj_old-wdyd-libra = is_definition-library_usages. ls_obj_old-wdyd-ctuse = is_definition-ext_ctlr_usages. ls_obj_old-wdyd-ctmap = is_definition-ext_ctx_mappings. CALL FUNCTION 'SVRS_MAKE_OBJECT_DELTA' EXPORTING obj_old = ls_obj_new obj_new = ls_obj_old CHANGING delta = rs_delta EXCEPTIONS inconsistent_objects = 1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from SVRS_MAKE_OBJECT_DELTA' ). ENDIF. ENDMETHOD. METHOD delta_view. DATA: ls_key TYPE wdy_md_view_key, ls_obj_new TYPE svrs2_versionable_object, ls_obj_old TYPE svrs2_versionable_object, lv_found TYPE abap_bool, lx_error TYPE REF TO cx_wdy_md_exception, li_view TYPE REF TO if_wdy_md_abstract_view. FIELD-SYMBOLS: LIKE LINE OF ls_obj_old-wdyv-defin. ls_key-component_name = is_view-definition-component_name. ls_key-view_name = is_view-definition-view_name. lv_found = cl_wdy_md_abstract_view=>check_existency( component_name = ls_key-component_name name = ls_key-view_name ). IF lv_found = abap_false. TRY. li_view = cl_wdy_md_abstract_view=>create( component_name = is_view-definition-component_name view_name = is_view-definition-view_name type = is_view-definition-type ). li_view->save_to_database( ). li_view->unlock( ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error creating dummy view: { lx_error->get_text( ) }| ). ENDTRY. ENDIF. ls_obj_new-objtype = wdyn_limu_component_view. ls_obj_new-objname = ls_key. ls_obj_old-objtype = wdyn_limu_component_view. ls_obj_old-objname = ls_key. APPEND INITIAL LINE TO ls_obj_old-wdyv-defin ASSIGNING . MOVE-CORRESPONDING is_view-definition TO . ls_obj_old-wdyv-descr = is_view-descriptions. ls_obj_old-wdyv-vcont = is_view-view_containers. ls_obj_old-wdyv-vcntt = is_view-view_container_texts. ls_obj_old-wdyv-ibplg = is_view-iobound_plugs. ls_obj_old-wdyv-ibplt = is_view-iobound_plug_texts. ls_obj_old-wdyv-plpar = is_view-plug_parameters. ls_obj_old-wdyv-plprt = is_view-plug_parameter_texts. ls_obj_old-wdyv-uiele = is_view-ui_elements. ls_obj_old-wdyv-uicon = is_view-ui_context_bindings. ls_obj_old-wdyv-uievt = is_view-ui_event_bindings. ls_obj_old-wdyv-uiddc = is_view-ui_ddic_bindings. ls_obj_old-wdyv-uiprp = is_view-ui_properties. ls_obj_old-wdyv-navil = is_view-navigation_links. ls_obj_old-wdyv-navit = is_view-navigation_target_refs. ls_obj_old-wdyv-vshno = is_view-vsh_nodes. ls_obj_old-wdyv-vshpl = is_view-vsh_placeholders. ls_obj_old-wdyv-views = is_view-viewset_properties. CALL FUNCTION 'SVRS_MAKE_OBJECT_DELTA' EXPORTING obj_old = ls_obj_new obj_new = ls_obj_old CHANGING delta = rs_delta EXCEPTIONS inconsistent_objects = 1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from SVRS_MAKE_OBJECT_DELTA' ). ENDIF. ENDMETHOD. METHOD get_limu_objects. DATA: lv_name TYPE wdy_component_name. lv_name = ms_item-obj_name. CALL FUNCTION 'WDYN_GET_LIMU_OBJECTS' EXPORTING component_name = lv_name IMPORTING limu_objects = rt_objects. ENDMETHOD. METHOD read. DATA: lt_objects TYPE wdy_md_transport_keys, ls_controller_key TYPE wdy_md_controller_key, ls_component_key TYPE wdy_md_component_key, ls_view_key TYPE wdy_md_view_key. FIELD-SYMBOLS: LIKE LINE OF lt_objects, LIKE LINE OF rs_component-ctlr_metadata, LIKE LINE OF rs_component-view_metadata, TYPE ANY TABLE, TYPE ANY TABLE. CLEAR mt_components. CLEAR mt_sources. lt_objects = get_limu_objects( ). LOOP AT lt_objects ASSIGNING . CASE -sub_type. WHEN wdyn_limu_component_controller. ls_controller_key = -sub_name. APPEND read_controller( ls_controller_key ) TO rs_component-ctlr_metadata. WHEN wdyn_limu_component_definition. ls_component_key = -sub_name. rs_component-comp_metadata = read_definition( ls_component_key ). WHEN wdyn_limu_component_view. ls_view_key = -sub_name. APPEND read_view( ls_view_key ) TO rs_component-view_metadata. WHEN OTHERS. ASSERT 0 = 1. ENDCASE. ENDLOOP. SORT rs_component-ctlr_metadata BY definition-component_name ASCENDING definition-controller_name ASCENDING. LOOP AT rs_component-ctlr_metadata ASSIGNING . SORT -descriptions. SORT -controller_usages. SORT -controller_components. SORT -controller_component_texts. SORT -controller_parameters. SORT -controller_parameter_texts. SORT -context_nodes. SORT -context_attributes. SORT -context_mappings. SORT -fieldgroups. * Version 702 doesn't have these two attributes so we * use them dynamically for downward compatibility ASSIGN COMPONENT 'CONTROLLER_EXCEPTIONS' OF STRUCTURE TO . IF sy-subrc = 0. SORT . ENDIF. ASSIGN COMPONENT 'CONTROLLER_EXCEPTION_TEXTS' OF STRUCTURE TO . IF sy-subrc = 0. SORT . ENDIF. ENDLOOP. SORT rs_component-view_metadata BY definition-component_name ASCENDING definition-view_name ASCENDING. LOOP AT rs_component-view_metadata ASSIGNING . SORT -descriptions. SORT -view_containers. SORT -view_container_texts. SORT -iobound_plugs. SORT -iobound_plug_texts. SORT -plug_parameters. SORT -plug_parameter_texts. SORT -ui_elements. SORT -ui_context_bindings. SORT -ui_event_bindings. SORT -ui_ddic_bindings. SORT -ui_properties. SORT -navigation_links. SORT -navigation_target_refs. SORT -vsh_nodes. SORT -vsh_placeholders. SORT -viewset_properties. ENDLOOP. SORT mt_components BY component_name ASCENDING controller_name ASCENDING cmpname ASCENDING. SORT mt_sources BY component_name ASCENDING controller_name ASCENDING cmpname ASCENDING line_number ASCENDING. ENDMETHOD. METHOD read_controller. DATA: lt_components TYPE TABLE OF wdy_ctlr_compo_vrs, lt_sources TYPE TABLE OF wdy_ctlr_compo_source_vrs, lt_definition TYPE TABLE OF wdy_controller, lt_psmodilog TYPE TABLE OF smodilog, lt_psmodisrc TYPE TABLE OF smodisrc, lt_fm_param TYPE abap_func_parmbind_tab, lt_fm_exception TYPE abap_func_excpbind_tab. FIELD-SYMBOLS: TYPE ANY TABLE, TYPE ANY TABLE. * Calling FM dynamically because version 702 has less parameters * FM parameters add_fm_param_exporting( EXPORTING iv_name = 'CONTROLLER_KEY' ig_value = is_key CHANGING ct_param = lt_fm_param ). add_fm_param_exporting( EXPORTING iv_name = 'GET_ALL_TRANSLATIONS' ig_value = abap_false CHANGING ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'DEFINITION' CHANGING ct_value = lt_definition ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'DESCRIPTIONS' CHANGING ct_value = rs_controller-descriptions ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_USAGES' CHANGING ct_value = rs_controller-controller_usages ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_COMPONENTS' CHANGING ct_value = lt_components ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_COMPONENT_SOURCES' CHANGING ct_value = lt_sources ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_COMPONENT_TEXTS' CHANGING ct_value = rs_controller-controller_component_texts ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_PARAMETERS' CHANGING ct_value = rs_controller-controller_parameters ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_PARAMETER_TEXTS' CHANGING ct_value = rs_controller-controller_parameter_texts ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTEXT_NODES' CHANGING ct_value = rs_controller-context_nodes ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTEXT_ATTRIBUTES' CHANGING ct_value = rs_controller-context_attributes ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTEXT_MAPPINGS' CHANGING ct_value = rs_controller-context_mappings ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'FIELDGROUPS' CHANGING ct_value = rs_controller-fieldgroups ct_param = lt_fm_param ). * Version 702 doesn't have these two attributes so we * use them dynamically for downward compatibility ASSIGN COMPONENT 'CONTROLLER_EXCEPTIONS' OF STRUCTURE rs_controller TO . IF sy-subrc = 0. add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_EXCEPTIONS' CHANGING ct_value = ct_param = lt_fm_param ). ENDIF. ASSIGN COMPONENT 'CONTROLLER_EXCEPTION_TEXTS' OF STRUCTURE rs_controller TO . IF sy-subrc = 0. add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_EXCEPTION_TEXTS' CHANGING ct_value = ct_param = lt_fm_param ). ENDIF. add_fm_param_tables( EXPORTING iv_name = 'PSMODILOG' CHANGING ct_value = lt_psmodilog ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'PSMODISRC' CHANGING ct_value = lt_psmodisrc ct_param = lt_fm_param ). * FM exceptions add_fm_exception( EXPORTING iv_name = 'NOT_EXISTING' iv_value = 1 CHANGING ct_exception = lt_fm_exception ). add_fm_exception( EXPORTING iv_name = 'OTHERS' iv_value = 2 CHANGING ct_exception = lt_fm_exception ). CALL FUNCTION 'WDYC_GET_OBJECT' PARAMETER-TABLE lt_fm_param EXCEPTION-TABLE lt_fm_exception. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from WDYC_GET_OBJECT' ). ENDIF. APPEND LINES OF lt_components TO mt_components. APPEND LINES OF lt_sources TO mt_sources. READ TABLE lt_definition INDEX 1 INTO rs_controller-definition. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'WDYC, definition not found' ). ENDIF. CLEAR: rs_controller-definition-author, rs_controller-definition-createdon, rs_controller-definition-changedby, rs_controller-definition-changedon. ENDMETHOD. METHOD read_definition. DATA: lt_definition TYPE TABLE OF wdy_component, lt_psmodilog TYPE TABLE OF smodilog, lt_psmodisrc TYPE TABLE OF smodisrc. CALL FUNCTION 'WDYD_GET_OBJECT' EXPORTING component_key = is_key get_all_translations = abap_false TABLES definition = lt_definition descriptions = rs_definition-descriptions component_usages = rs_definition-component_usages interface_implementings = rs_definition-interface_implementings library_usages = rs_definition-library_usages ext_ctlr_usages = rs_definition-ext_ctlr_usages ext_ctx_mappings = rs_definition-ext_ctx_mappings psmodilog = lt_psmodilog "" not optional in all versions psmodisrc = lt_psmodisrc "" not optional in all versions EXCEPTIONS not_existing = 1 OTHERS = 2. IF sy-subrc = 1. RETURN. ELSEIF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from WDYD_GET_OBJECT' ). ENDIF. READ TABLE lt_definition INDEX 1 INTO rs_definition-definition. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'WDYD, definition not found' ). ENDIF. CLEAR: rs_definition-definition-author, rs_definition-definition-createdon, rs_definition-definition-changedby, rs_definition-definition-changedon, rs_definition-definition-gendate, rs_definition-definition-gentime. ENDMETHOD. METHOD read_view. DATA: lt_definition TYPE TABLE OF wdy_view_vrs, lt_psmodilog TYPE TABLE OF smodilog, lt_psmodisrc TYPE TABLE OF smodisrc. FIELD-SYMBOLS: LIKE LINE OF lt_definition. CALL FUNCTION 'WDYV_GET_OBJECT' EXPORTING view_key = is_key get_all_translations = abap_false TABLES definition = lt_definition descriptions = rs_view-descriptions view_containers = rs_view-view_containers view_container_texts = rs_view-view_container_texts iobound_plugs = rs_view-iobound_plugs iobound_plug_texts = rs_view-iobound_plug_texts plug_parameters = rs_view-plug_parameters plug_parameter_texts = rs_view-plug_parameter_texts ui_elements = rs_view-ui_elements ui_context_bindings = rs_view-ui_context_bindings ui_event_bindings = rs_view-ui_event_bindings ui_ddic_bindings = rs_view-ui_ddic_bindings ui_properties = rs_view-ui_properties navigation_links = rs_view-navigation_links navigation_target_refs = rs_view-navigation_target_refs vsh_nodes = rs_view-vsh_nodes vsh_placeholders = rs_view-vsh_placeholders viewset_properties = rs_view-viewset_properties psmodilog = lt_psmodilog psmodisrc = lt_psmodisrc EXCEPTIONS not_existing = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from WDYV_GET_OBJECT' ). ENDIF. READ TABLE lt_definition INDEX 1 ASSIGNING . ASSERT sy-subrc = 0. MOVE-CORRESPONDING TO rs_view-definition. CLEAR: rs_view-definition-author, rs_view-definition-createdon, rs_view-definition-changedby, rs_view-definition-changedon. ENDMETHOD. METHOD recover_controller. DATA: ls_key TYPE wdy_controller_key, lv_corrnr TYPE trkorr, lx_error TYPE REF TO cx_wdy_md_exception, ls_delta TYPE svrs2_xversionable_object. ls_delta = delta_controller( is_controller ). ls_key-component_name = is_controller-definition-component_name. ls_key-controller_name = is_controller-definition-controller_name. TRY. cl_wdy_md_controller=>recover_version( EXPORTING controller_key = ls_key delta = ls_delta-wdyc CHANGING corrnr = lv_corrnr ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error recovering version of controller: { lx_error->get_text( ) }| ). ENDTRY. ENDMETHOD. METHOD recover_definition. DATA: ls_key TYPE wdy_md_component_key, lv_corrnr TYPE trkorr, lx_error TYPE REF TO cx_wdy_md_exception, ls_delta TYPE svrs2_xversionable_object. ls_delta = delta_definition( is_definition = is_definition iv_package = iv_package ). ls_key-component_name = is_definition-definition-component_name. TRY. cl_wdy_md_component=>recover_version( EXPORTING component_key = ls_key delta = ls_delta-wdyd CHANGING corrnr = lv_corrnr ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error recovering version of component: { lx_error->get_text( ) }| ). ENDTRY. ENDMETHOD. METHOD recover_view. DATA: ls_key TYPE wdy_md_view_key, lv_corrnr TYPE trkorr, lx_error TYPE REF TO cx_wdy_md_exception, ls_delta TYPE svrs2_xversionable_object. ls_delta = delta_view( is_view ). ls_key-component_name = is_view-definition-component_name. ls_key-view_name = is_view-definition-view_name. TRY. cl_wdy_md_abstract_view=>recover_version( EXPORTING view_key = ls_key delta = ls_delta-wdyv CHANGING corrnr = lv_corrnr ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error recovering version of abstract view: { lx_error->get_text( ) }| ). ENDTRY. ENDMETHOD. METHOD zif_abapgit_object~changed_by. SELECT SINGLE changedby FROM wdy_component INTO rv_user WHERE component_name = ms_item-obj_name AND version = 'A'. IF sy-subrc <> 0. rv_user = c_user_unknown. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: lo_component TYPE REF TO cl_wdy_wb_component, lo_request TYPE REF TO cl_wb_request, li_state TYPE REF TO if_wb_program_state, lv_object_name TYPE seu_objkey. CREATE OBJECT lo_component. lv_object_name = ms_item-obj_name. CREATE OBJECT lo_request EXPORTING p_object_type = 'YC' p_object_name = lv_object_name p_operation = swbm_c_op_delete_no_dialog. lo_component->if_wb_program~process_wb_request( p_wb_request = lo_request p_wb_program_state = li_state ). ENDMETHOD. METHOD zif_abapgit_object~deserialize. DATA: ls_component TYPE wdy_component_metadata, ls_description TYPE wdy_ext_ctx_map. FIELD-SYMBOLS: LIKE LINE OF ls_component-view_metadata, LIKE LINE OF ls_component-ctlr_metadata. io_xml->read( EXPORTING iv_name = 'COMPONENT' CHANGING cg_data = ls_component ). io_xml->read( EXPORTING iv_name = 'COMPONENTS' CHANGING cg_data = mt_components ). io_xml->read( EXPORTING iv_name = 'SOURCES' CHANGING cg_data = mt_sources ). ls_component-comp_metadata-definition-author = sy-uname. ls_component-comp_metadata-definition-createdon = sy-datum. recover_definition( is_definition = ls_component-comp_metadata iv_package = iv_package ). LOOP AT ls_component-ctlr_metadata ASSIGNING . -definition-author = sy-uname. -definition-createdon = sy-datum. recover_controller( ). ENDLOOP. LOOP AT ls_component-view_metadata ASSIGNING . -definition-author = sy-uname. -definition-createdon = sy-datum. recover_view( ). ENDLOOP. READ TABLE ls_component-comp_metadata-descriptions INTO ls_description INDEX 1. IF sy-subrc = 0. zcl_abapgit_sotr_handler=>create_sotr( iv_package = iv_package io_xml = io_xml ). ENDIF. add_with_inactive_parts( ). deserialize_longtexts( io_xml ). deserialize_longtexts( ii_xml = io_xml iv_longtext_name = c_longtext_name_wc ). ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: lv_component_name TYPE wdy_component-component_name. SELECT SINGLE component_name FROM wdy_component INTO lv_component_name WHERE component_name = ms_item-obj_name. ""#EC CI_GENBUFF rv_bool = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. RETURN. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-abap TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. rv_is_locked = abap_false. ENDMETHOD. METHOD zif_abapgit_object~jump. "" Covered by ZCL_ABAPGIT_OBJECTS=>JUMP ENDMETHOD. METHOD zif_abapgit_object~serialize. DATA: ls_component TYPE wdy_component_metadata, ls_comp TYPE wdy_ctlr_compo_vrs, lv_object TYPE dokil-object, lt_object TYPE STANDARD TABLE OF dokil-object WITH DEFAULT KEY, lt_dokil TYPE STANDARD TABLE OF dokil WITH DEFAULT KEY, ls_description TYPE wdy_ext_ctx_map. ls_component = read( ). io_xml->add( iv_name = 'COMPONENT' ig_data = ls_component ). io_xml->add( ig_data = mt_components iv_name = 'COMPONENTS' ). io_xml->add( ig_data = mt_sources iv_name = 'SOURCES' ). READ TABLE ls_component-comp_metadata-descriptions INTO ls_description INDEX 1. IF sy-subrc = 0. zcl_abapgit_sotr_handler=>read_sotr( iv_pgmid = 'LIMU' iv_object = 'WDYV' iv_obj_name = ms_item-obj_name io_xml = io_xml ). ENDIF. serialize_longtexts( ii_xml = io_xml iv_longtext_id = c_longtext_id_wd ). LOOP AT mt_components INTO ls_comp. lv_object = ls_comp-component_name. lv_object+30 = ls_comp-controller_name. COLLECT lv_object INTO lt_object. ENDLOOP. IF io_xml->i18n_params( )-main_language_only = abap_true. SELECT * FROM dokil INTO TABLE lt_dokil FOR ALL ENTRIES IN lt_object WHERE id = c_longtext_id_wc AND object = lt_object-table_line AND masterlang = abap_true ORDER BY PRIMARY KEY. ELSE. SELECT * FROM dokil INTO TABLE lt_dokil FOR ALL ENTRIES IN lt_object WHERE id = c_longtext_id_wc AND object = lt_object-table_line ORDER BY PRIMARY KEY. ENDIF. serialize_longtexts( ii_xml = io_xml it_dokil = lt_dokil iv_longtext_id = c_longtext_id_wc iv_longtext_name = c_longtext_name_wc ). ENDMETHOD. ENDCLASS. ",8025,False,1895.215111977063,median "CLASS zcl_abapgit_object_tabl DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super FINAL. PUBLIC SECTION. INTERFACES zif_abapgit_object. ALIASES mo_files FOR zif_abapgit_object~mo_files. PROTECTED SECTION. TYPES: BEGIN OF ty_segment_definition, segmentheader TYPE edisegmhd, segmentdefinition TYPE edisegmdef, segmentstructures TYPE STANDARD TABLE OF edisegstru WITH DEFAULT KEY, END OF ty_segment_definition. TYPES: ty_segment_definitions TYPE STANDARD TABLE OF ty_segment_definition WITH DEFAULT KEY. TYPES: BEGIN OF ty_tabl_extras, tddat TYPE tddat, END OF ty_tabl_extras. ""! get additional data like table authorization group ""! @parameter iv_tabname | name of the table METHODS read_extras IMPORTING iv_tabname TYPE ddobjname RETURNING VALUE(rs_tabl_extras) TYPE ty_tabl_extras. ""! Update additional data ""! @parameter iv_tabname | name of the table ""! @parameter is_tabl_extras | additional table data METHODS update_extras IMPORTING iv_tabname TYPE ddobjname is_tabl_extras TYPE ty_tabl_extras. ""! Delete additional data ""! @parameter iv_tabname | name of the table METHODS delete_extras IMPORTING iv_tabname TYPE ddobjname. ""! Serialize IDoc Segment type/definition if exits ""! @parameter io_xml | XML writer ""! @raising zcx_abapgit_exception | Exceptions METHODS serialize_idoc_segment IMPORTING io_xml TYPE REF TO zif_abapgit_xml_output RAISING zcx_abapgit_exception. ""! Deserialize IDoc Segment type/definition if exits ""! @parameter io_xml | XML writer ""! @parameter iv_package | Target package ""! @parameter rv_deserialized | It's a segment and was desserialized ""! @raising zcx_abapgit_exception | Exceptions METHODS deserialize_idoc_segment IMPORTING io_xml TYPE REF TO zif_abapgit_xml_input iv_package TYPE devclass RETURNING VALUE(rv_deserialized) TYPE abap_bool RAISING zcx_abapgit_exception. ""! Delete the IDoc Segment type if exists ""! @parameter rv_deleted | It's a segment and was deleted ""! @raising zcx_abapgit_exception | Exceptions METHODS delete_idoc_segment RETURNING VALUE(rv_deleted) TYPE abap_bool RAISING zcx_abapgit_exception. PRIVATE SECTION. TYPES: ty_dd03p_tt TYPE STANDARD TABLE OF dd03p . TYPES: BEGIN OF ty_dd02_texts, ddlanguage TYPE dd02t-ddlanguage, ddtext TYPE dd02t-ddtext, END OF ty_dd02_texts, tt_dd02_texts TYPE STANDARD TABLE OF ty_dd02_texts. CONSTANTS c_longtext_id_tabl TYPE dokil-id VALUE 'TB' ##NO_TEXT. CONSTANTS: BEGIN OF c_s_dataname, segment_definition TYPE string VALUE 'SEGMENT_DEFINITION', tabl_extras TYPE string VALUE 'TABL_EXTRAS', END OF c_s_dataname. METHODS clear_dd03p_fields CHANGING !ct_dd03p TYPE ty_dd03p_tt . ""! Check if structure is an IDoc segment ""! @parameter rv_is_idoc_segment | It's an IDoc segment or not METHODS is_idoc_segment RETURNING VALUE(rv_is_idoc_segment) TYPE abap_bool. METHODS clear_dd03p_fields_common CHANGING !cs_dd03p TYPE dd03p . METHODS clear_dd03p_fields_dataelement CHANGING !cs_dd03p TYPE dd03p . METHODS: serialize_texts IMPORTING io_xml TYPE REF TO zif_abapgit_xml_output RAISING zcx_abapgit_exception, deserialize_texts IMPORTING io_xml TYPE REF TO zif_abapgit_xml_input is_dd02v TYPE dd02v RAISING zcx_abapgit_exception. ENDCLASS. CLASS ZCL_ABAPGIT_OBJECT_TABL IMPLEMENTATION. METHOD clear_dd03p_fields. CONSTANTS lc_comptype_dataelement TYPE comptype VALUE 'E' ##NO_TEXT. DATA: lv_masklen TYPE c LENGTH 4. FIELD-SYMBOLS: TYPE dd03p. * remove nested structures DELETE ct_dd03p WHERE depth <> '00'. * remove fields from .INCLUDEs DELETE ct_dd03p WHERE adminfield <> '0'. LOOP AT ct_dd03p ASSIGNING WHERE NOT rollname IS INITIAL. clear_dd03p_fields_common( CHANGING cs_dd03p = ). lv_masklen = -masklen. IF lv_masklen = '' OR NOT lv_masklen CO '0123456789'. * make sure the field contains valid data, or the XML will dump CLEAR -masklen. ENDIF. IF -comptype = lc_comptype_dataelement. clear_dd03p_fields_dataelement( CHANGING cs_dd03p = ). ENDIF. IF -shlporigin = 'D'. * search help from domain CLEAR: -shlpfield, -shlpname. ENDIF. * XML output assumes correct field content IF -routputlen = ' '. CLEAR -routputlen. ENDIF. ENDLOOP. ENDMETHOD. METHOD clear_dd03p_fields_common. CLEAR: cs_dd03p-ddlanguage, cs_dd03p-dtelmaster, cs_dd03p-logflag, cs_dd03p-ddtext, cs_dd03p-reservedte, cs_dd03p-reptext, cs_dd03p-scrtext_s, cs_dd03p-scrtext_m, cs_dd03p-scrtext_l. ENDMETHOD. METHOD clear_dd03p_fields_dataelement. * type specified via data element CLEAR: cs_dd03p-domname, cs_dd03p-inttype, cs_dd03p-intlen, cs_dd03p-mask, cs_dd03p-memoryid, cs_dd03p-headlen, cs_dd03p-scrlen1, cs_dd03p-scrlen2, cs_dd03p-scrlen3, cs_dd03p-datatype, cs_dd03p-leng, cs_dd03p-outputlen, cs_dd03p-deffdname, cs_dd03p-convexit, cs_dd03p-entitytab, cs_dd03p-dommaster, cs_dd03p-domname3l, cs_dd03p-decimals, cs_dd03p-lowercase, cs_dd03p-signflag. ENDMETHOD. METHOD delete_extras. DELETE FROM tddat WHERE tabname = iv_tabname. ENDMETHOD. METHOD delete_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. DATA lv_result LIKE sy-subrc. IF is_idoc_segment( ) = abap_false. rv_deleted = abap_false. RETURN. ""previous XML version or no IDoc segment ENDIF. rv_deleted = abap_true. lv_segment_type = ms_item-obj_name. CALL FUNCTION 'SEGMENT_DELETE' EXPORTING segmenttyp = lv_segment_type IMPORTING result = lv_result EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDMETHOD. METHOD deserialize_idoc_segment. DATA lv_result LIKE sy-subrc. DATA lt_segment_definitions TYPE ty_segment_definitions. DATA lv_package TYPE devclass. DATA lv_uname TYPE sy-uname. FIELD-SYMBOLS TYPE ty_segment_definition. rv_deserialized = abap_false. TRY. io_xml->read( EXPORTING iv_name = c_s_dataname-segment_definition CHANGING cg_data = lt_segment_definitions ). CATCH zcx_abapgit_exception. RETURN. ""previous XML version or no IDoc segment ENDTRY. IF lines( lt_segment_definitions ) = 0. RETURN. ""no IDoc segment ENDIF. rv_deserialized = abap_true. lv_package = iv_package. LOOP AT lt_segment_definitions ASSIGNING . -segmentheader-presp = -segmentheader-pwork = cl_abap_syst=>get_user_name( ). CALL FUNCTION 'SEGMENT_READ' EXPORTING segmenttyp = -segmentheader-segtyp IMPORTING result = lv_result EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. CALL FUNCTION 'SEGMENT_CREATE' IMPORTING segmentdefinition = -segmentdefinition TABLES segmentstructure = -segmentstructures CHANGING segmentheader = -segmentheader devclass = lv_package EXCEPTIONS OTHERS = 1. ELSE. CALL FUNCTION 'SEGMENT_MODIFY' CHANGING segmentheader = -segmentheader devclass = lv_package EXCEPTIONS OTHERS = 1. IF sy-subrc = 0. CALL FUNCTION 'SEGMENTDEFINITION_MODIFY' TABLES segmentstructure = -segmentstructures CHANGING segmentdefinition = -segmentdefinition EXCEPTIONS OTHERS = 1. ENDIF. ENDIF. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDLOOP. lv_uname = cl_abap_syst=>get_user_name( ). CALL FUNCTION 'TR_TADIR_INTERFACE' EXPORTING wi_test_modus = abap_false wi_tadir_pgmid = 'R3TR' wi_tadir_object = ms_item-obj_type wi_tadir_obj_name = ms_item-obj_name wi_tadir_author = lv_uname wi_tadir_devclass = iv_package wi_tadir_masterlang = mv_language iv_set_edtflag = abap_true iv_delflag = abap_false EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from TR_TADIR_INTERFACE' ). ENDIF. ENDMETHOD. METHOD deserialize_texts. DATA: lv_name TYPE ddobjname, ls_dd02v_tmp TYPE dd02v, lt_i18n_langs TYPE TABLE OF langu, lt_dd02_texts TYPE tt_dd02_texts. FIELD-SYMBOLS: LIKE LINE OF lt_i18n_langs, LIKE LINE OF lt_dd02_texts. lv_name = ms_item-obj_name. io_xml->read( EXPORTING iv_name = 'I18N_LANGS' CHANGING cg_data = lt_i18n_langs ). io_xml->read( EXPORTING iv_name = 'DD02_TEXTS' CHANGING cg_data = lt_dd02_texts ). SORT lt_i18n_langs. SORT lt_dd02_texts BY ddlanguage. "" Optimization LOOP AT lt_i18n_langs ASSIGNING . "" Table description ls_dd02v_tmp = is_dd02v. READ TABLE lt_dd02_texts ASSIGNING WITH KEY ddlanguage = . IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |DD02_TEXTS cannot find lang { } in XML| ). ENDIF. MOVE-CORRESPONDING TO ls_dd02v_tmp. CALL FUNCTION 'DDIF_TABL_PUT' EXPORTING name = lv_name dd02v_wa = ls_dd02v_tmp EXCEPTIONS tabl_not_found = 1 name_inconsistent = 2 tabl_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |error from DDIF_TABL_PUT @TEXTS, { sy-subrc }| ). ENDIF. ENDLOOP. ENDMETHOD. METHOD is_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. lv_segment_type = ms_item-obj_name. SELECT SINGLE segtyp FROM edisegment INTO lv_segment_type WHERE segtyp = lv_segment_type. rv_is_idoc_segment = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD read_extras. SELECT SINGLE * FROM tddat INTO rs_tabl_extras-tddat WHERE tabname = iv_tabname. ENDMETHOD. METHOD serialize_idoc_segment. DATA lv_segment_type TYPE edilsegtyp. DATA lv_result LIKE sy-subrc. DATA lv_devclass TYPE devclass. DATA lt_segmentdefinitions TYPE STANDARD TABLE OF edisegmdef. DATA ls_segment_definition TYPE ty_segment_definition. DATA lt_segment_definitions TYPE ty_segment_definitions. FIELD-SYMBOLS: TYPE edisegmdef. IF is_idoc_segment( ) = abap_false. RETURN. ENDIF. lv_segment_type = ms_item-obj_name. CALL FUNCTION 'SEGMENT_READ' EXPORTING segmenttyp = lv_segment_type IMPORTING result = lv_result TABLES segmentdefinition = lt_segmentdefinitions EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. LOOP AT lt_segmentdefinitions ASSIGNING . CLEAR ls_segment_definition. CALL FUNCTION 'SEGMENTDEFINITION_READ' EXPORTING segmenttyp = -segtyp IMPORTING result = lv_result devclass = lv_devclass segmentheader = ls_segment_definition-segmentheader segmentdefinition = ls_segment_definition-segmentdefinition TABLES segmentstructure = ls_segment_definition-segmentstructures CHANGING version = -version EXCEPTIONS no_authority = 1 segment_not_existing = 2 OTHERS = 3. IF sy-subrc <> 0 OR lv_result <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. zcl_abapgit_object_idoc=>clear_idoc_segement_fields( CHANGING cg_structure = ls_segment_definition-segmentdefinition ). zcl_abapgit_object_idoc=>clear_idoc_segement_fields( CHANGING cg_structure = ls_segment_definition-segmentheader ). APPEND ls_segment_definition TO lt_segment_definitions. ENDLOOP. io_xml->add( iv_name = c_s_dataname-segment_definition ig_data = lt_segment_definitions ). ENDMETHOD. METHOD serialize_texts. DATA: lv_name TYPE ddobjname, lv_index TYPE i, ls_dd02v TYPE dd02v, lt_dd02_texts TYPE tt_dd02_texts, lt_i18n_langs TYPE TABLE OF langu. FIELD-SYMBOLS: LIKE LINE OF lt_i18n_langs, LIKE LINE OF lt_dd02_texts. IF io_xml->i18n_params( )-serialize_master_lang_only = abap_true. RETURN. ENDIF. lv_name = ms_item-obj_name. "" Collect additional languages, skip master lang - it was serialized already SELECT DISTINCT ddlanguage AS langu INTO TABLE lt_i18n_langs FROM dd02v WHERE tabname = lv_name AND ddlanguage <> mv_language. ""#EC CI_SUBRC LOOP AT lt_i18n_langs ASSIGNING . lv_index = sy-tabix. CALL FUNCTION 'DDIF_TABL_GET' EXPORTING name = lv_name langu = IMPORTING dd02v_wa = ls_dd02v EXCEPTIONS illegal_input = 1 OTHERS = 2. IF sy-subrc <> 0 OR ls_dd02v-ddlanguage IS INITIAL. DELETE lt_i18n_langs INDEX lv_index. "" Don't save this lang CONTINUE. ENDIF. APPEND INITIAL LINE TO lt_dd02_texts ASSIGNING . MOVE-CORRESPONDING ls_dd02v TO . ENDLOOP. SORT lt_i18n_langs ASCENDING. SORT lt_dd02_texts BY ddlanguage ASCENDING. IF lines( lt_i18n_langs ) > 0. io_xml->add( iv_name = 'I18N_LANGS' ig_data = lt_i18n_langs ). io_xml->add( iv_name = 'DD02_TEXTS' ig_data = lt_dd02_texts ). ENDIF. ENDMETHOD. METHOD update_extras. IF is_tabl_extras-tddat IS INITIAL. delete_extras( iv_tabname = iv_tabname ). ELSE. MODIFY tddat FROM is_tabl_extras-tddat. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~changed_by. TYPES: BEGIN OF ty_data, as4user TYPE as4user, as4date TYPE as4date, as4time TYPE as4time, END OF ty_data. DATA: lt_data TYPE STANDARD TABLE OF ty_data WITH DEFAULT KEY, ls_data LIKE LINE OF lt_data. SELECT as4user as4date as4time FROM dd02l INTO TABLE lt_data WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SELECT as4user as4date as4time APPENDING TABLE lt_data FROM dd09l WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SELECT as4user as4date as4time APPENDING TABLE lt_data FROM dd12l WHERE sqltab = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. SORT lt_data BY as4date DESCENDING as4time DESCENDING. READ TABLE lt_data INDEX 1 INTO ls_data. IF sy-subrc = 0. rv_user = ls_data-as4user. ELSE. rv_user = c_user_unknown. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: lv_objname TYPE rsedd0-ddobjname, lv_tabclass TYPE dd02l-tabclass, lv_no_ask TYPE abap_bool, lv_subrc TYPE sy-subrc, lr_data TYPE REF TO data. FIELD-SYMBOLS: TYPE any. IF zif_abapgit_object~exists( ) = abap_false. "" Proxies e.g. delete on its own, nothing todo here then. RETURN. ENDIF. lv_objname = ms_item-obj_name. IF delete_idoc_segment( ) = abap_false. lv_no_ask = abap_true. SELECT SINGLE tabclass FROM dd02l INTO lv_tabclass WHERE tabname = ms_item-obj_name AND as4local = 'A' AND as4vers = '0000'. IF sy-subrc = 0 AND lv_tabclass = 'TRANSP'. "" Avoid dump in dynamic SELECT in case the table does not exist on database CALL FUNCTION 'DB_EXISTS_TABLE' EXPORTING tabname = lv_objname IMPORTING subrc = lv_subrc. IF lv_subrc = 0. "" it cannot delete table with data without asking CREATE DATA lr_data TYPE (lv_objname). ASSIGN lr_data->* TO . SELECT SINGLE * FROM (lv_objname) INTO . IF sy-subrc = 0. lv_no_ask = abap_false. ENDIF. ENDIF. ENDIF. delete_ddic( iv_objtype = 'T' iv_no_ask = lv_no_ask ). delete_longtexts( c_longtext_id_tabl ). delete_extras( iv_tabname = lv_objname ). ENDIF. ENDMETHOD. METHOD zif_abapgit_object~deserialize. DATA: lv_name TYPE ddobjname, lv_tname TYPE trobj_name, ls_dd02v TYPE dd02v, ls_dd09l TYPE dd09l, lt_dd03p TYPE TABLE OF dd03p, lt_dd05m TYPE TABLE OF dd05m, lt_dd08v TYPE TABLE OF dd08v, lt_dd12v TYPE dd12vtab, lt_dd17v TYPE dd17vtab, ls_dd17v LIKE LINE OF lt_dd17v, lt_secondary LIKE lt_dd17v, lt_dd35v TYPE TABLE OF dd35v, lt_dd36m TYPE dd36mttyp, ls_dd12v LIKE LINE OF lt_dd12v, lv_refs TYPE abap_bool, ls_extras TYPE ty_tabl_extras. FIELD-SYMBOLS: TYPE dd03p. IF deserialize_idoc_segment( io_xml = io_xml iv_package = iv_package ) = abap_false. io_xml->read( EXPORTING iv_name = 'DD02V' CHANGING cg_data = ls_dd02v ). io_xml->read( EXPORTING iv_name = 'DD09L' CHANGING cg_data = ls_dd09l ). io_xml->read( EXPORTING iv_name = 'DD03P_TABLE' CHANGING cg_data = lt_dd03p ). "" DDIC Step: Replace REF TO class/interface with generic reference to avoid cyclic dependency LOOP AT lt_dd03p ASSIGNING WHERE datatype = 'REF'. IF iv_step = zif_abapgit_object=>gc_step_id-ddic. -rollname = 'OBJECT'. ELSE. lv_refs = abap_true. ENDIF. ENDLOOP. io_xml->read( EXPORTING iv_name = 'DD05M_TABLE' CHANGING cg_data = lt_dd05m ). io_xml->read( EXPORTING iv_name = 'DD08V_TABLE' CHANGING cg_data = lt_dd08v ). io_xml->read( EXPORTING iv_name = 'DD12V' CHANGING cg_data = lt_dd12v ). io_xml->read( EXPORTING iv_name = 'DD17V' CHANGING cg_data = lt_dd17v ). io_xml->read( EXPORTING iv_name = 'DD35V_TALE' CHANGING cg_data = lt_dd35v ). io_xml->read( EXPORTING iv_name = 'DD36M' CHANGING cg_data = lt_dd36m ). "" DDIC Step: Remove referenced to search helps IF iv_step = zif_abapgit_object=>gc_step_id-ddic. CLEAR: lt_dd35v, lt_dd36m. ENDIF. IF iv_step = zif_abapgit_object=>gc_step_id-late AND lv_refs = abap_false AND lines( lt_dd35v ) = 0. RETURN. "" already active ENDIF. corr_insert( iv_package = iv_package ig_object_class = 'DICT' ). lv_name = ms_item-obj_name. "" type conversion CALL FUNCTION 'DDIF_TABL_PUT' EXPORTING name = lv_name dd02v_wa = ls_dd02v dd09l_wa = ls_dd09l TABLES dd03p_tab = lt_dd03p dd05m_tab = lt_dd05m dd08v_tab = lt_dd08v dd35v_tab = lt_dd35v dd36m_tab = lt_dd36m EXCEPTIONS tabl_not_found = 1 name_inconsistent = 2 tabl_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_TABL_PUT' ). ENDIF. zcl_abapgit_objects_activation=>add_item( ms_item ). * handle indexes LOOP AT lt_dd12v INTO ls_dd12v. * todo, call corr_insert? CLEAR lt_secondary. LOOP AT lt_dd17v INTO ls_dd17v WHERE sqltab = ls_dd12v-sqltab AND indexname = ls_dd12v-indexname. APPEND ls_dd17v TO lt_secondary. ENDLOOP. CALL FUNCTION 'DDIF_INDX_PUT' EXPORTING name = ls_dd12v-sqltab id = ls_dd12v-indexname dd12v_wa = ls_dd12v TABLES dd17v_tab = lt_secondary EXCEPTIONS indx_not_found = 1 name_inconsistent = 2 indx_inconsistent = 3 put_failure = 4 put_refused = 5 OTHERS = 6. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_INDX_PUT' ). ENDIF. CALL FUNCTION 'DD_DD_TO_E071' EXPORTING type = 'INDX' name = ls_dd12v-sqltab id = ls_dd12v-indexname IMPORTING obj_name = lv_tname. zcl_abapgit_objects_activation=>add( iv_type = 'INDX' iv_name = lv_tname ). ENDLOOP. deserialize_texts( io_xml = io_xml is_dd02v = ls_dd02v ). deserialize_longtexts( io_xml ). io_xml->read( EXPORTING iv_name = c_s_dataname-tabl_extras CHANGING cg_data = ls_extras ). update_extras( iv_tabname = lv_name is_tabl_extras = ls_extras ). ENDIF. ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: lv_tabname TYPE dd02l-tabname. lv_tabname = ms_item-obj_name. CALL FUNCTION 'DD_GET_NAMETAB_HEADER' EXPORTING tabname = lv_tabname EXCEPTIONS not_found = 1 OTHERS = 2. rv_bool = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. DATA: lo_local_version_output TYPE REF TO zcl_abapgit_xml_output, lo_local_version_input TYPE REF TO zcl_abapgit_xml_input. CREATE OBJECT lo_local_version_output. me->zif_abapgit_object~serialize( lo_local_version_output ). CREATE OBJECT lo_local_version_input EXPORTING iv_xml = lo_local_version_output->render( ). CREATE OBJECT ri_comparator TYPE zcl_abapgit_object_tabl_compar EXPORTING io_local = lo_local_version_input. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-ddic TO rt_steps. APPEND zif_abapgit_object=>gc_step_id-late TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). rs_metadata-ddic = abap_true. ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. rv_is_locked = exists_a_lock_entry_for( iv_lock_object = 'ESDICT' iv_argument = |{ ms_item-obj_type }{ ms_item-obj_name }| ). ENDMETHOD. METHOD zif_abapgit_object~jump. jump_se11( iv_radio = 'RSRD1-DDTYPE' iv_field = 'RSRD1-DDTYPE_VAL' ). ENDMETHOD. METHOD zif_abapgit_object~serialize. DATA: lv_name TYPE ddobjname, ls_dd02v TYPE dd02v, ls_dd09l TYPE dd09l, lt_dd03p TYPE ty_dd03p_tt, lt_dd05m TYPE TABLE OF dd05m, lt_dd08v TYPE TABLE OF dd08v, lt_dd12v TYPE dd12vtab, lt_dd17v TYPE dd17vtab, lt_dd35v TYPE TABLE OF dd35v, lv_index LIKE sy-index, lt_dd36m TYPE dd36mttyp, ls_extras TYPE ty_tabl_extras. FIELD-SYMBOLS: LIKE LINE OF lt_dd12v, LIKE LINE OF lt_dd05m, LIKE LINE OF lt_dd36m, TYPE any. lv_name = ms_item-obj_name. CALL FUNCTION 'DDIF_TABL_GET' EXPORTING name = lv_name langu = mv_language IMPORTING dd02v_wa = ls_dd02v dd09l_wa = ls_dd09l TABLES dd03p_tab = lt_dd03p dd05m_tab = lt_dd05m dd08v_tab = lt_dd08v dd12v_tab = lt_dd12v dd17v_tab = lt_dd17v dd35v_tab = lt_dd35v dd36m_tab = lt_dd36m EXCEPTIONS illegal_input = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from DDIF_TABL_GET' ). ENDIF. IF ls_dd02v IS INITIAL. RETURN. "" object does not exits ENDIF. CLEAR: ls_dd02v-as4user, ls_dd02v-as4date, ls_dd02v-as4time. * reset numeric field, so XML does not crash IF ls_dd02v-prozpuff = ''. CLEAR ls_dd02v-prozpuff. ENDIF. IF ls_dd02v-datmin = ''. CLEAR ls_dd02v-datmin. ENDIF. IF ls_dd02v-datmax = ''. CLEAR ls_dd02v-datmax. ENDIF. IF ls_dd02v-datavg = ''. CLEAR ls_dd02v-datavg. ENDIF. CLEAR: ls_dd09l-as4user, ls_dd09l-as4date, ls_dd09l-as4time. ASSIGN COMPONENT 'ROWORCOLST' OF STRUCTURE ls_dd09l TO . IF sy-subrc = 0 AND = 'C'. CLEAR . ""To avoid diff errors. This field doesn't exists in all releases ENDIF. LOOP AT lt_dd12v ASSIGNING . CLEAR: -as4user, -as4date, -as4time. ENDLOOP. clear_dd03p_fields( CHANGING ct_dd03p = lt_dd03p ). * remove foreign keys inherited from .INCLUDEs DELETE lt_dd08v WHERE noinherit = 'N'. LOOP AT lt_dd05m ASSIGNING . lv_index = sy-tabix. READ TABLE lt_dd08v WITH KEY fieldname = -fieldname TRANSPORTING NO FIELDS. IF sy-subrc <> 0. DELETE lt_dd05m INDEX lv_index. ENDIF. ENDLOOP. * remove inherited search helps DELETE lt_dd35v WHERE shlpinher = abap_true. LOOP AT lt_dd36m ASSIGNING . lv_index = sy-tabix. READ TABLE lt_dd35v WITH KEY fieldname = -fieldname TRANSPORTING NO FIELDS. IF sy-subrc <> 0. DELETE lt_dd36m INDEX lv_index. ENDIF. ENDLOOP. io_xml->add( iv_name = 'DD02V' ig_data = ls_dd02v ). IF NOT ls_dd09l IS INITIAL. io_xml->add( iv_name = 'DD09L' ig_data = ls_dd09l ). ENDIF. io_xml->add( iv_name = 'DD03P_TABLE' ig_data = lt_dd03p ). io_xml->add( iv_name = 'DD05M_TABLE' ig_data = lt_dd05m ). io_xml->add( iv_name = 'DD08V_TABLE' ig_data = lt_dd08v ). io_xml->add( iv_name = 'DD12V' ig_data = lt_dd12v ). io_xml->add( iv_name = 'DD17V' ig_data = lt_dd17v ). io_xml->add( iv_name = 'DD35V_TALE' ig_data = lt_dd35v ). io_xml->add( iv_name = 'DD36M' ig_data = lt_dd36m ). serialize_texts( io_xml ). serialize_longtexts( io_xml = io_xml iv_longtext_id = c_longtext_id_tabl ). serialize_idoc_segment( io_xml ). ls_extras = read_extras( iv_tabname = lv_name ). io_xml->add( iv_name = c_s_dataname-tabl_extras ig_data = ls_extras ). ENDMETHOD. ENDCLASS. ",8145,False,1730.7639032256354,median "CLASS zcl_abapgit_gui_router DEFINITION PUBLIC FINAL CREATE PUBLIC. PUBLIC SECTION. INTERFACES zif_abapgit_gui_event_handler. PROTECTED SECTION. PRIVATE SECTION. METHODS general_page_routing IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(rs_handled) TYPE zif_abapgit_gui_event_handler=>ty_handling_result RAISING zcx_abapgit_exception . METHODS abapgit_services_actions IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(rs_handled) TYPE zif_abapgit_gui_event_handler=>ty_handling_result RAISING zcx_abapgit_exception . METHODS db_actions IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(rs_handled) TYPE zif_abapgit_gui_event_handler=>ty_handling_result RAISING zcx_abapgit_exception . CLASS-METHODS file_download IMPORTING !iv_package TYPE devclass !iv_xstr TYPE xstring RAISING zcx_abapgit_exception . METHODS git_services IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(rs_handled) TYPE zif_abapgit_gui_event_handler=>ty_handling_result RAISING zcx_abapgit_exception . METHODS sap_gui_actions IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(rs_handled) TYPE zif_abapgit_gui_event_handler=>ty_handling_result RAISING zcx_abapgit_exception . METHODS other_utilities IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(rs_handled) TYPE zif_abapgit_gui_event_handler=>ty_handling_result RAISING zcx_abapgit_exception . METHODS zip_services IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(rs_handled) TYPE zif_abapgit_gui_event_handler=>ty_handling_result RAISING zcx_abapgit_exception . METHODS repository_services IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(rs_handled) TYPE zif_abapgit_gui_event_handler=>ty_handling_result RAISING zcx_abapgit_exception . METHODS get_page_diff IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(ri_page) TYPE REF TO zif_abapgit_gui_renderable RAISING zcx_abapgit_exception . METHODS get_page_branch_overview IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key RETURNING VALUE(ri_page) TYPE REF TO zif_abapgit_gui_renderable RAISING zcx_abapgit_exception . METHODS get_page_stage IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(ri_page) TYPE REF TO zif_abapgit_gui_renderable RAISING zcx_abapgit_exception . CLASS-METHODS jump_display_transport IMPORTING !iv_transport TYPE trkorr RAISING zcx_abapgit_exception . CLASS-METHODS jump_display_user IMPORTING !iv_username TYPE xubname RAISING zcx_abapgit_exception . METHODS call_browser IMPORTING !iv_url TYPE csequence RAISING zcx_abapgit_exception . METHODS get_state_settings IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(rv_state) TYPE i . METHODS get_state_diff IMPORTING !ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(rv_state) TYPE i . METHODS get_state_db_edit IMPORTING ii_event TYPE REF TO zif_abapgit_gui_event RETURNING VALUE(rv_state) TYPE i . METHODS main_page RETURNING VALUE(ri_page) TYPE REF TO zif_abapgit_gui_renderable RAISING zcx_abapgit_exception. ENDCLASS. CLASS zcl_abapgit_gui_router IMPLEMENTATION. METHOD abapgit_services_actions. DATA li_main_page TYPE REF TO zcl_abapgit_gui_page_main. IF ii_event->mv_action = zif_abapgit_definitions=>c_action-abapgit_home. CREATE OBJECT li_main_page EXPORTING iv_only_favorites = abap_true. rs_handled-page = li_main_page. rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. ENDIF. ENDMETHOD. METHOD call_browser. zcl_abapgit_ui_factory=>get_frontend_services( )->execute( iv_document = |{ iv_url }| ). ENDMETHOD. METHOD db_actions. DATA ls_db_key TYPE zif_abapgit_persistence=>ty_content. DATA lo_query TYPE REF TO zcl_abapgit_string_map. lo_query = ii_event->query( ). CASE ii_event->mv_action. WHEN zif_abapgit_definitions=>c_action-db_edit. lo_query->to_abap( CHANGING cs_container = ls_db_key ). CREATE OBJECT rs_handled-page TYPE zcl_abapgit_gui_page_db_edit EXPORTING is_key = ls_db_key. rs_handled-state = get_state_db_edit( ii_event ). WHEN zif_abapgit_definitions=>c_action-db_display. lo_query->to_abap( CHANGING cs_container = ls_db_key ). CREATE OBJECT rs_handled-page TYPE zcl_abapgit_gui_page_db_dis EXPORTING is_key = ls_db_key. rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. ENDCASE. ENDMETHOD. METHOD file_download. DATA: lv_path TYPE string, lv_default TYPE string, li_fe_serv TYPE REF TO zif_abapgit_frontend_services, lv_package TYPE devclass. lv_package = iv_package. TRANSLATE lv_package USING '/#'. CONCATENATE lv_package '_' sy-datlo '_' sy-timlo INTO lv_default. li_fe_serv = zcl_abapgit_ui_factory=>get_frontend_services( ). lv_path = li_fe_serv->show_file_save_dialog( iv_title = 'Export ZIP' iv_extension = 'zip' iv_default_filename = lv_default ). li_fe_serv->file_download( iv_path = lv_path iv_xstr = iv_xstr ). ENDMETHOD. METHOD general_page_routing. DATA: lv_key TYPE zif_abapgit_persistence=>ty_repo-key, lv_last_repo_key TYPE zif_abapgit_persistence=>ty_repo-key, lt_repo_fav_list TYPE zif_abapgit_repo_srv=>ty_repo_list, lt_repo_all_list TYPE zif_abapgit_repo_srv=>ty_repo_list. lv_key = ii_event->query( )->get( 'KEY' ). CASE ii_event->mv_action. WHEN zcl_abapgit_gui=>c_action-go_home. lv_last_repo_key = zcl_abapgit_persistence_user=>get_instance( )->get_repo_show( ). IF lv_last_repo_key IS NOT INITIAL. CREATE OBJECT rs_handled-page TYPE zcl_abapgit_gui_page_repo_view EXPORTING iv_key = lv_last_repo_key. rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. ELSE. rs_handled-page = main_page( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. ENDIF. WHEN zif_abapgit_definitions=>c_action-go_db. "" Go DB util page CREATE OBJECT rs_handled-page TYPE zcl_abapgit_gui_page_db. rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN zif_abapgit_definitions=>c_action-go_debuginfo. "" Go debug info rs_handled-page = zcl_abapgit_gui_page_debuginfo=>create( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN zif_abapgit_definitions=>c_action-go_settings. "" Go global settings rs_handled-page = zcl_abapgit_gui_page_sett_glob=>create( ). rs_handled-state = get_state_settings( ii_event ). WHEN zif_abapgit_definitions=>c_action-go_settings_personal. "" Go personal settings rs_handled-page = zcl_abapgit_gui_page_sett_pers=>create( ). rs_handled-state = get_state_settings( ii_event ). WHEN zif_abapgit_definitions=>c_action-go_background_run. "" Go background run page rs_handled-page = zcl_abapgit_gui_page_run_bckg=>create( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN zif_abapgit_definitions=>c_action-go_repo_diff "" Go Diff page OR zif_abapgit_definitions=>c_action-go_file_diff. rs_handled-page = get_page_diff( ii_event ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page_w_bookmark. WHEN zif_abapgit_definitions=>c_action-go_stage. "" Go Staging page rs_handled-page = get_page_stage( ii_event ). rs_handled-state = get_state_diff( ii_event ). WHEN zif_abapgit_definitions=>c_action-go_branch_overview. "" Go repo branch overview rs_handled-page = get_page_branch_overview( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN zif_abapgit_definitions=>c_action-go_tutorial. "" Go to tutorial rs_handled-page = zcl_abapgit_gui_page_tutorial=>create( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN zif_abapgit_definitions=>c_action-documentation. "" abapGit docs zcl_abapgit_services_abapgit=>open_abapgit_wikipage( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. WHEN zif_abapgit_definitions=>c_action-go_explore. "" dotabap zcl_abapgit_services_abapgit=>open_dotabap_homepage( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. WHEN zif_abapgit_definitions=>c_action-changelog. "" abapGit full changelog zcl_abapgit_services_abapgit=>open_abapgit_changelog( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. ENDCASE. ENDMETHOD. METHOD main_page. DATA lt_repo_fav_list TYPE zif_abapgit_repo_srv=>ty_repo_list. DATA lt_repo_all_list TYPE zif_abapgit_repo_srv=>ty_repo_list. "" for performance reasons, only load favorites lt_repo_fav_list = zcl_abapgit_repo_srv=>get_instance( )->list_favorites( ). IF lt_repo_fav_list IS INITIAL. "" if there are no favorites, check if there are any repositories at all "" if not, go to tutorial where the user can create the first repository lt_repo_all_list = zcl_abapgit_repo_srv=>get_instance( )->list( ). IF lt_repo_all_list IS NOT INITIAL. CREATE OBJECT ri_page TYPE zcl_abapgit_gui_page_main EXPORTING iv_only_favorites = abap_false. ELSE. ri_page = zcl_abapgit_gui_page_tutorial=>create( ). ENDIF. ELSE. CREATE OBJECT ri_page TYPE zcl_abapgit_gui_page_main EXPORTING iv_only_favorites = abap_true. ENDIF. ENDMETHOD. METHOD get_page_branch_overview. DATA: lo_repo TYPE REF TO zcl_abapgit_repo_online, lo_page TYPE REF TO zcl_abapgit_gui_page_boverview. lo_repo ?= zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). CREATE OBJECT lo_page EXPORTING io_repo = lo_repo. ri_page = lo_page. ENDMETHOD. METHOD get_page_diff. DATA: ls_file TYPE zif_abapgit_definitions=>ty_file, ls_object TYPE zif_abapgit_definitions=>ty_item, lo_page TYPE REF TO zcl_abapgit_gui_page_diff, lv_key TYPE zif_abapgit_persistence=>ty_repo-key. lv_key = ii_event->query( )->get( 'KEY' ). ls_file-path = ii_event->query( )->get( 'PATH' ). ls_file-filename = ii_event->query( )->get( 'FILENAME' ). "" unescape ? ls_object-obj_type = ii_event->query( )->get( 'OBJ_TYPE' ). ls_object-obj_name = ii_event->query( )->get( 'OBJ_NAME' ). "" unescape ? CREATE OBJECT lo_page EXPORTING iv_key = lv_key is_file = ls_file is_object = ls_object. ri_page = lo_page. ENDMETHOD. METHOD get_page_stage. DATA: lo_repo TYPE REF TO zcl_abapgit_repo_online, lv_key TYPE zif_abapgit_persistence=>ty_repo-key, lv_seed TYPE string, lo_stage_page TYPE REF TO zcl_abapgit_gui_page_stage, lo_code_inspector_page TYPE REF TO zcl_abapgit_gui_page_code_insp, lo_page_repo TYPE REF TO zcl_abapgit_gui_page_repo_view, lv_answer TYPE c LENGTH 1, lv_question_text TYPE string, lv_question_title TYPE string, lv_show_create_branch_popup TYPE c LENGTH 1, lx_error TYPE REF TO cx_sy_move_cast_error. lv_key = ii_event->query( )->get( 'KEY' ). lv_seed = ii_event->query( )->get( 'SEED' ). TRY. lo_repo ?= zcl_abapgit_repo_srv=>get_instance( )->get( lv_key ). CATCH cx_sy_move_cast_error INTO lx_error. zcx_abapgit_exception=>raise( `Staging is only possible for online repositories.` ). ENDTRY. IF lo_repo->get_local_settings( )-code_inspector_check_variant IS NOT INITIAL. CREATE OBJECT lo_code_inspector_page EXPORTING io_repo = lo_repo. IF lo_code_inspector_page->is_nothing_to_display( ) = abap_true. "" force refresh on stage, to make sure the latest local and remote files are used lo_repo->refresh( ). CREATE OBJECT lo_stage_page EXPORTING io_repo = lo_repo iv_seed = lv_seed iv_sci_result = zif_abapgit_definitions=>c_sci_result-passed. ri_page = lo_stage_page. ELSE. ri_page = lo_code_inspector_page. ENDIF. ELSEIF lo_repo->get_selected_branch( ) CP zif_abapgit_definitions=>c_git_branch-tags. lv_show_create_branch_popup = abap_true. lv_question_title = 'Staging on a tag'. lv_question_text = 'You are currently working on a tag.'. lv_question_text = |{ lv_question_text } You must be on a branch to stage.|. lv_question_text = |{ lv_question_text } Create new branch?|. ELSEIF lo_repo->get_selected_commit( ) IS NOT INITIAL. lv_show_create_branch_popup = abap_true. lv_question_title = 'Staging on a checked out commit'. lv_question_text = 'You are currently checked out in a commit.'. lv_question_text = |{ lv_question_text } You must be on a branch to stage.|. lv_question_text = |{ lv_question_text } Create new branch?|. ELSE. "" force refresh on stage, to make sure the latest local and remote files are used lo_repo->refresh( ). CREATE OBJECT lo_stage_page EXPORTING io_repo = lo_repo iv_seed = lv_seed. ri_page = lo_stage_page. ENDIF. IF lv_show_create_branch_popup = abap_true. lv_answer = zcl_abapgit_ui_factory=>get_popups( )->popup_to_confirm( iv_titlebar = lv_question_title iv_text_question = lv_question_text iv_text_button_1 = 'New branch' ""Ideally the button name would be Create branch, but it did not fit iv_icon_button_1 = 'ICON_OKAY' iv_text_button_2 = 'Cancel' iv_icon_button_2 = 'ICON_CANCEL' iv_default_button = '2' iv_display_cancel_button = abap_false ). IF lv_answer = '1'. TRY. zcl_abapgit_services_git=>create_branch( iv_key = lo_repo->get_key( ) ). CATCH zcx_abapgit_cancel. ""Continue processing so we can return to the correct page ENDTRY. ENDIF. CREATE OBJECT lo_page_repo TYPE zcl_abapgit_gui_page_repo_view EXPORTING iv_key = lo_repo->get_key( ). ri_page = lo_page_repo. ENDIF. ENDMETHOD. METHOD get_state_db_edit. "" In display mode, replace the page IF ii_event->mv_current_page_name = 'ZCL_ABAPGIT_GUI_PAGE_DB_DIS'. rv_state = zcl_abapgit_gui=>c_event_state-new_page_replacing. ELSE. rv_state = zcl_abapgit_gui=>c_event_state-new_page. ENDIF. ENDMETHOD. METHOD get_state_diff. "" Bookmark current page before jumping to diff page IF ii_event->mv_current_page_name CP 'ZCL_ABAPGIT_GUI_PAGE_DIFF'. rv_state = zcl_abapgit_gui=>c_event_state-new_page. ELSE. rv_state = zcl_abapgit_gui=>c_event_state-new_page_w_bookmark. ENDIF. ENDMETHOD. METHOD get_state_settings. "" Bookmark current page before jumping to any settings page IF ii_event->mv_current_page_name CP 'ZCL_ABAPGIT_GUI_PAGE_SETT_*'. rv_state = zcl_abapgit_gui=>c_event_state-new_page_replacing. ELSE. rv_state = zcl_abapgit_gui=>c_event_state-new_page_w_bookmark. ENDIF. ENDMETHOD. METHOD git_services. DATA lv_key TYPE zif_abapgit_persistence=>ty_repo-key. lv_key = ii_event->query( )->get( 'KEY' ). CASE ii_event->mv_action. WHEN zif_abapgit_definitions=>c_action-git_pull. "" GIT Pull zcl_abapgit_services_git=>pull( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-git_reset. "" GIT Reset zcl_abapgit_services_git=>reset( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-git_branch_create. "" GIT Create new branch zcl_abapgit_services_git=>create_branch( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-git_branch_delete. "" GIT Delete remote branch zcl_abapgit_services_git=>delete_branch( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-git_branch_switch. "" GIT Switch branch zcl_abapgit_services_git=>switch_branch( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-go_tag_overview. "" GIT Tag overview zcl_abapgit_services_git=>tag_overview( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-git_tag_create. "" GIT Tag create CREATE OBJECT rs_handled-page TYPE zcl_abapgit_gui_page_tag EXPORTING io_repo = zcl_abapgit_repo_srv=>get_instance( )->get( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN zif_abapgit_definitions=>c_action-git_tag_delete. "" GIT Tag create zcl_abapgit_services_git=>delete_tag( lv_key ). zcl_abapgit_services_repo=>refresh( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-git_tag_switch. "" GIT Switch Tag zcl_abapgit_services_git=>switch_tag( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. ENDCASE. ENDMETHOD. METHOD jump_display_transport. DATA: lv_transport_adt_uri TYPE string, lv_adt_link TYPE string, lv_adt_jump_enabled TYPE abap_bool. lv_adt_jump_enabled = zcl_abapgit_persist_factory=>get_settings( )->read( )->get_adt_jump_enabled( ). IF lv_adt_jump_enabled = abap_true. TRY. CALL METHOD ('CL_CTS_ADT_TM_URI_BUILDER')=>('CREATE_ADT_URI') EXPORTING trnumber = iv_transport RECEIVING result = lv_transport_adt_uri. lv_adt_link = |adt://{ sy-sysid }{ lv_transport_adt_uri }|. zcl_abapgit_ui_factory=>get_frontend_services( )->execute( iv_document = lv_adt_link ). CATCH cx_root. CALL FUNCTION 'TR_DISPLAY_REQUEST' EXPORTING i_trkorr = iv_transport. ENDTRY. ELSE. CALL FUNCTION 'TR_DISPLAY_REQUEST' EXPORTING i_trkorr = iv_transport. ENDIF. ENDMETHOD. METHOD jump_display_user. "" todo, user display in ADT CALL FUNCTION 'BAPI_USER_DISPLAY' EXPORTING username = iv_username. ENDMETHOD. METHOD other_utilities. TYPES ty_char600 TYPE c LENGTH 600. DATA lv_clip_content TYPE string. DATA lt_clipboard TYPE STANDARD TABLE OF ty_char600. CASE ii_event->mv_action. WHEN zif_abapgit_definitions=>c_action-ie_devtools. zcl_abapgit_services_basis=>open_ie_devtools( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. WHEN zif_abapgit_definitions=>c_action-clipboard. lv_clip_content = ii_event->query( )->get( 'CLIPBOARD' ). APPEND lv_clip_content TO lt_clipboard. zcl_abapgit_ui_factory=>get_frontend_services( )->clipboard_export( lt_clipboard ). MESSAGE 'Successfully exported URL to Clipboard.' TYPE 'S'. rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. ENDCASE. ENDMETHOD. METHOD repository_services. DATA: lv_key TYPE zif_abapgit_persistence=>ty_repo-key, lo_repo TYPE REF TO zcl_abapgit_repo, li_log TYPE REF TO zif_abapgit_log. lv_key = ii_event->query( )->get( 'KEY' ). IF lv_key IS NOT INITIAL. lo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( lv_key ). ENDIF. CASE ii_event->mv_action. WHEN zif_abapgit_definitions=>c_action-repo_newoffline. "" New offline repo rs_handled-page = zcl_abapgit_gui_page_addofflin=>create( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN zif_abapgit_definitions=>c_action-repo_add_all_obj_to_trans_req. "" Add objects to transport zcl_abapgit_transport=>add_all_objects_to_trans_req( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-repo_refresh. "" Repo refresh zcl_abapgit_services_repo=>refresh( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-repo_syntax_check. CREATE OBJECT rs_handled-page TYPE zcl_abapgit_gui_page_syntax "" Syntax check EXPORTING io_repo = lo_repo. rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN zif_abapgit_definitions=>c_action-repo_code_inspector. "" Code inspector CREATE OBJECT rs_handled-page TYPE zcl_abapgit_gui_page_code_insp EXPORTING io_repo = lo_repo. rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN zif_abapgit_definitions=>c_action-repo_purge. "" Repo purge all objects (uninstall) zcl_abapgit_services_repo=>purge( lv_key ). CREATE OBJECT rs_handled-page TYPE zcl_abapgit_gui_page_main EXPORTING iv_only_favorites = abap_true. rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page_replacing. WHEN zif_abapgit_definitions=>c_action-repo_remove. "" Repo remove zcl_abapgit_services_repo=>remove( lv_key ). CREATE OBJECT rs_handled-page TYPE zcl_abapgit_gui_page_main EXPORTING iv_only_favorites = abap_true. rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page_replacing. WHEN zif_abapgit_definitions=>c_action-repo_newonline. "" New offline repo rs_handled-page = zcl_abapgit_gui_page_addonline=>create( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN zif_abapgit_definitions=>c_action-repo_refresh_checksums. "" Rebuild local checksums zcl_abapgit_services_repo=>refresh_local_checksums( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-repo_toggle_fav. "" Toggle repo as favorite zcl_abapgit_services_repo=>toggle_favorite( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-repo_transport_to_branch. "" Transport to branch zcl_abapgit_services_repo=>transport_to_branch( lv_key ). rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN zif_abapgit_definitions=>c_action-repo_settings. "" Repo settings rs_handled-page = zcl_abapgit_gui_page_sett_repo=>create( lo_repo ). rs_handled-state = get_state_settings( ii_event ). WHEN zif_abapgit_definitions=>c_action-repo_local_settings. "" Local repo settings rs_handled-page = zcl_abapgit_gui_page_sett_locl=>create( lo_repo ). rs_handled-state = get_state_settings( ii_event ). WHEN zif_abapgit_definitions=>c_action-repo_remote_settings. "" Remote repo settings rs_handled-page = zcl_abapgit_gui_page_sett_remo=>create( lo_repo ). rs_handled-state = get_state_settings( ii_event ). WHEN zif_abapgit_definitions=>c_action-repo_background. "" Repo background mode rs_handled-page = zcl_abapgit_gui_page_sett_bckg=>create( lo_repo ). rs_handled-state = get_state_settings( ii_event ). WHEN zif_abapgit_definitions=>c_action-repo_infos. "" Repo infos rs_handled-page = zcl_abapgit_gui_page_sett_info=>create( lo_repo ). rs_handled-state = get_state_settings( ii_event ). WHEN zif_abapgit_definitions=>c_action-repo_log. "" Repo log li_log = lo_repo->get_log( ). zcl_abapgit_log_viewer=>show_log( li_log ). rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. ENDCASE. ENDMETHOD. METHOD sap_gui_actions. DATA: ls_item TYPE zif_abapgit_definitions=>ty_item, lx_ex TYPE REF TO zcx_abapgit_exception, li_html_viewer TYPE REF TO zif_abapgit_html_viewer. CASE ii_event->mv_action. WHEN zif_abapgit_definitions=>c_action-jump. "" Open object editor ls_item-obj_type = ii_event->query( )->get( 'TYPE' ). ls_item-obj_name = ii_event->query( )->get( 'NAME' ). ls_item-obj_name = cl_http_utility=>unescape_url( |{ ls_item-obj_name }| ). li_html_viewer = zcl_abapgit_ui_factory=>get_html_viewer( ). TRY. "" Hide HTML Viewer in dummy screen0 for direct CALL SCREEN to work li_html_viewer->set_visiblity( abap_false ). zcl_abapgit_objects=>jump( ls_item ). li_html_viewer->set_visiblity( abap_true ). CATCH zcx_abapgit_exception INTO lx_ex. li_html_viewer->set_visiblity( abap_true ). RAISE EXCEPTION lx_ex. ENDTRY. rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. WHEN zif_abapgit_definitions=>c_action-jump_transport. jump_display_transport( |{ ii_event->query( )->get( 'TRANSPORT' ) }| ). rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. WHEN zif_abapgit_definitions=>c_action-jump_user. jump_display_user( |{ ii_event->query( )->get( 'USER' ) }| ). rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. WHEN zif_abapgit_definitions=>c_action-url. call_browser( ii_event->query( )->get( 'URL' ) ). rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. ENDCASE. ENDMETHOD. METHOD zif_abapgit_gui_event_handler~on_event. rs_handled = zcl_abapgit_exit=>get_instance( )->on_event( ii_event ). IF rs_handled-state IS INITIAL. rs_handled = general_page_routing( ii_event ). ENDIF. IF rs_handled-state IS INITIAL. rs_handled = repository_services( ii_event ). ENDIF. IF rs_handled-state IS INITIAL. rs_handled = git_services( ii_event ). ENDIF. IF rs_handled-state IS INITIAL. rs_handled = zip_services( ii_event ). ENDIF. IF rs_handled-state IS INITIAL. rs_handled = db_actions( ii_event ). ENDIF. IF rs_handled-state IS INITIAL. rs_handled = abapgit_services_actions( ii_event ). ENDIF. IF rs_handled-state IS INITIAL. rs_handled = sap_gui_actions( ii_event ). ENDIF. IF rs_handled-state IS INITIAL. rs_handled = other_utilities( ii_event ). ENDIF. IF rs_handled-state IS INITIAL. rs_handled-state = zcl_abapgit_gui=>c_event_state-not_handled. ENDIF. ENDMETHOD. METHOD zip_services. DATA: lv_key TYPE zif_abapgit_persistence=>ty_repo-key, lo_repo TYPE REF TO zcl_abapgit_repo, lv_path TYPE string, lv_dest TYPE rfcdest, lv_msg TYPE c LENGTH 200, lv_xstr TYPE xstring, lv_package TYPE zif_abapgit_persistence=>ty_repo-package, lv_folder_logic TYPE string, lv_main_lang_only TYPE zif_abapgit_persistence=>ty_local_settings-main_language_only. CONSTANTS: BEGIN OF lc_page, main_view TYPE string VALUE 'ZCL_ABAPGIT_GUI_PAGE_MAIN', repo_view TYPE string VALUE 'ZCL_ABAPGIT_GUI_PAGE_REPO_VIEW', END OF lc_page. lv_key = ii_event->query( )->get( 'KEY' ). CASE ii_event->mv_action. WHEN zif_abapgit_definitions=>c_action-zip_import "" Import repo from ZIP OR zif_abapgit_definitions=>c_action-rfc_compare. "" Compare repo via RFC lo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( lv_key ). IF ii_event->mv_action = zif_abapgit_definitions=>c_action-zip_import. lv_path = zcl_abapgit_ui_factory=>get_frontend_services( )->show_file_open_dialog( iv_title = 'Import ZIP' iv_extension = 'zip' iv_default_filename = '*.zip' ). lv_xstr = zcl_abapgit_ui_factory=>get_frontend_services( )->file_upload( lv_path ). ELSE. lv_dest = zcl_abapgit_ui_factory=>get_popups( )->popup_search_help( 'RFCDES-RFCDEST' ). IF lv_dest IS INITIAL. rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. RETURN. ENDIF. lv_package = lo_repo->get_package( ). lv_folder_logic = lo_repo->get_dot_abapgit( )->get_folder_logic( ). lv_main_lang_only = lo_repo->get_local_settings( )-main_language_only. CALL FUNCTION 'Z_ABAPGIT_SERIALIZE_PACKAGE' DESTINATION lv_dest EXPORTING iv_package = lv_package iv_folder_logic = lv_folder_logic iv_main_lang_only = lv_main_lang_only IMPORTING ev_xstring = lv_xstr EXCEPTIONS system_failure = 1 MESSAGE lv_msg communication_failure = 2 MESSAGE lv_msg OTHERS = 3. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |RFC import error: { lv_msg }| ). ENDIF. ENDIF. lo_repo->set_files_remote( zcl_abapgit_zip=>load( lv_xstr ) ). zcl_abapgit_services_repo=>refresh( lv_key ). CASE ii_event->mv_current_page_name. WHEN lc_page-repo_view. rs_handled-state = zcl_abapgit_gui=>c_event_state-re_render. WHEN lc_page-main_view. CREATE OBJECT rs_handled-page TYPE zcl_abapgit_gui_page_repo_view EXPORTING iv_key = lo_repo->get_key( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN OTHERS. rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. ENDCASE. WHEN zif_abapgit_definitions=>c_action-zip_export. "" Export repo as ZIP lo_repo = zcl_abapgit_repo_srv=>get_instance( )->get( lv_key ). lv_xstr = zcl_abapgit_zip=>encode_files( lo_repo->get_files_local( ) ). file_download( iv_package = lo_repo->get_package( ) iv_xstr = lv_xstr ). rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. WHEN zif_abapgit_definitions=>c_action-zip_package. "" Export package as ZIP rs_handled-page = zcl_abapgit_gui_page_ex_pckage=>create( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. WHEN zif_abapgit_definitions=>c_action-zip_transport. "" Export transports as ZIP zcl_abapgit_transport_mass=>run( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-no_more_act. WHEN zif_abapgit_definitions=>c_action-zip_object. "" Export object as ZIP rs_handled-page = zcl_abapgit_gui_page_ex_object=>create( ). rs_handled-state = zcl_abapgit_gui=>c_event_state-new_page. ENDCASE. ENDMETHOD. ENDCLASS. ",8292,False,1955.98038142172,median "CLASS zcl_abapgit_objects_program DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super. PUBLIC SECTION. TYPES: BEGIN OF ty_progdir, name TYPE progdir-name, state TYPE progdir-state, sqlx TYPE progdir-sqlx, edtx TYPE progdir-edtx, varcl TYPE progdir-varcl, dbapl TYPE progdir-dbapl, dbna TYPE progdir-dbna, clas TYPE progdir-clas, type TYPE progdir-type, occurs TYPE progdir-occurs, subc TYPE progdir-subc, appl TYPE progdir-appl, secu TYPE progdir-secu, cnam TYPE progdir-cnam, cdat TYPE progdir-cdat, unam TYPE progdir-unam, udat TYPE progdir-udat, vern TYPE progdir-vern, levl TYPE progdir-levl, rstat TYPE progdir-rstat, rmand TYPE progdir-rmand, rload TYPE progdir-rload, fixpt TYPE progdir-fixpt, sset TYPE progdir-sset, sdate TYPE progdir-sdate, stime TYPE progdir-stime, idate TYPE progdir-idate, itime TYPE progdir-itime, ldbname TYPE progdir-ldbname, uccheck TYPE progdir-uccheck, END OF ty_progdir. METHODS serialize_program IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_output OPTIONAL is_item TYPE zif_abapgit_definitions=>ty_item io_files TYPE REF TO zcl_abapgit_objects_files iv_program TYPE programm OPTIONAL iv_extra TYPE clike OPTIONAL RAISING zcx_abapgit_exception. METHODS read_progdir IMPORTING iv_program TYPE programm RETURNING VALUE(rs_progdir) TYPE ty_progdir. METHODS deserialize_program IMPORTING is_progdir TYPE ty_progdir it_source TYPE abaptxt255_tab it_tpool TYPE textpool_table iv_package TYPE devclass RAISING zcx_abapgit_exception. PROTECTED SECTION. TYPES: ty_spaces_tt TYPE STANDARD TABLE OF i WITH DEFAULT KEY . TYPES: BEGIN OF ty_dynpro, header TYPE rpy_dyhead, containers TYPE dycatt_tab, fields TYPE dyfatc_tab, flow_logic TYPE swydyflow, spaces TYPE ty_spaces_tt, END OF ty_dynpro . TYPES: ty_dynpro_tt TYPE STANDARD TABLE OF ty_dynpro WITH DEFAULT KEY . TYPES: BEGIN OF ty_cua, adm TYPE rsmpe_adm, sta TYPE STANDARD TABLE OF rsmpe_stat WITH DEFAULT KEY, fun TYPE STANDARD TABLE OF rsmpe_funt WITH DEFAULT KEY, men TYPE STANDARD TABLE OF rsmpe_men WITH DEFAULT KEY, mtx TYPE STANDARD TABLE OF rsmpe_mnlt WITH DEFAULT KEY, act TYPE STANDARD TABLE OF rsmpe_act WITH DEFAULT KEY, but TYPE STANDARD TABLE OF rsmpe_but WITH DEFAULT KEY, pfk TYPE STANDARD TABLE OF rsmpe_pfk WITH DEFAULT KEY, set TYPE STANDARD TABLE OF rsmpe_staf WITH DEFAULT KEY, doc TYPE STANDARD TABLE OF rsmpe_atrt WITH DEFAULT KEY, tit TYPE STANDARD TABLE OF rsmpe_titt WITH DEFAULT KEY, biv TYPE STANDARD TABLE OF rsmpe_buts WITH DEFAULT KEY, END OF ty_cua . METHODS serialize_dynpros IMPORTING !iv_program_name TYPE programm RETURNING VALUE(rt_dynpro) TYPE ty_dynpro_tt RAISING zcx_abapgit_exception . METHODS serialize_cua IMPORTING !iv_program_name TYPE programm RETURNING VALUE(rs_cua) TYPE ty_cua RAISING zcx_abapgit_exception . METHODS deserialize_dynpros IMPORTING !it_dynpros TYPE ty_dynpro_tt RAISING zcx_abapgit_exception . METHODS deserialize_textpool IMPORTING !iv_program TYPE programm !it_tpool TYPE textpool_table !iv_language TYPE langu OPTIONAL !iv_is_include TYPE abap_bool DEFAULT abap_false RAISING zcx_abapgit_exception . METHODS deserialize_cua IMPORTING !iv_program_name TYPE programm !is_cua TYPE ty_cua RAISING zcx_abapgit_exception . METHODS is_any_dynpro_locked IMPORTING !iv_program TYPE programm RETURNING VALUE(rv_is_any_dynpro_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_cua_locked IMPORTING !iv_program TYPE programm RETURNING VALUE(rv_is_cua_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_text_locked IMPORTING !iv_program TYPE programm RETURNING VALUE(rv_is_text_locked) TYPE abap_bool RAISING zcx_abapgit_exception . CLASS-METHODS add_tpool IMPORTING !it_tpool TYPE textpool_table RETURNING VALUE(rt_tpool) TYPE zif_abapgit_definitions=>ty_tpool_tt . CLASS-METHODS read_tpool IMPORTING !it_tpool TYPE zif_abapgit_definitions=>ty_tpool_tt RETURNING VALUE(rt_tpool) TYPE zif_abapgit_definitions=>ty_tpool_tt . PRIVATE SECTION. METHODS: condense_flow EXPORTING et_spaces TYPE ty_spaces_tt CHANGING ct_flow TYPE swydyflow, uncondense_flow IMPORTING it_flow TYPE swydyflow it_spaces TYPE ty_spaces_tt RETURNING VALUE(rt_flow) TYPE swydyflow. CLASS-METHODS auto_correct_cua_adm IMPORTING is_cua TYPE zcl_abapgit_objects_program=>ty_cua CHANGING cs_adm TYPE rsmpe_adm. ENDCLASS. CLASS ZCL_ABAPGIT_OBJECTS_PROGRAM IMPLEMENTATION. METHOD add_tpool. FIELD-SYMBOLS: LIKE LINE OF it_tpool, LIKE LINE OF rt_tpool. LOOP AT it_tpool ASSIGNING . APPEND INITIAL LINE TO rt_tpool ASSIGNING . MOVE-CORRESPONDING TO . IF -id = 'S'. -split = -entry. -entry = -entry+8. ENDIF. ENDLOOP. ENDMETHOD. METHOD auto_correct_cua_adm. "" issue #1807 automatic correction of CUA interfaces saved incorrectly in the past (ADM was not saved in the XML) CONSTANTS: lc_num_n_space TYPE string VALUE ' 0123456789', lc_num_only TYPE string VALUE '0123456789'. FIELD-SYMBOLS: TYPE rsmpe_pfk, TYPE rsmpe_act, TYPE rsmpe_men. IF cs_adm IS NOT INITIAL AND ( cs_adm-actcode CO lc_num_n_space AND cs_adm-mencode CO lc_num_n_space AND cs_adm-pfkcode CO lc_num_n_space ). ""Check performed in form check_adm of include LSMPIF03 RETURN. ENDIF. LOOP AT is_cua-act ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO lc_num_only. cs_adm-actcode = -code. ENDIF. ENDLOOP. LOOP AT is_cua-men ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO lc_num_only. cs_adm-mencode = -code. ENDIF. ENDLOOP. LOOP AT is_cua-pfk ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO lc_num_only. cs_adm-pfkcode = -code. ENDIF. ENDLOOP. ENDMETHOD. METHOD condense_flow. DATA: lv_spaces LIKE LINE OF et_spaces. FIELD-SYMBOLS: LIKE LINE OF ct_flow. CLEAR et_spaces. LOOP AT ct_flow ASSIGNING . lv_spaces = 0. WHILE NOT -line IS INITIAL AND -line(1) = space. lv_spaces = lv_spaces + 1. -line = -line+1. ENDWHILE. APPEND lv_spaces TO et_spaces. ENDLOOP. ENDMETHOD. METHOD deserialize_cua. DATA: ls_tr_key TYPE trkey, ls_adm TYPE rsmpe_adm. IF lines( is_cua-sta ) = 0 AND lines( is_cua-fun ) = 0 AND lines( is_cua-men ) = 0 AND lines( is_cua-mtx ) = 0 AND lines( is_cua-act ) = 0 AND lines( is_cua-but ) = 0 AND lines( is_cua-pfk ) = 0 AND lines( is_cua-set ) = 0 AND lines( is_cua-doc ) = 0 AND lines( is_cua-tit ) = 0 AND lines( is_cua-biv ) = 0. RETURN. ENDIF. SELECT SINGLE devclass INTO ls_tr_key-devclass FROM tadir WHERE pgmid = 'R3TR' AND object = ms_item-obj_type AND obj_name = ms_item-obj_name. ""#EC CI_GENBUFF IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'not found in tadir' ). ENDIF. ls_tr_key-obj_type = ms_item-obj_type. ls_tr_key-obj_name = ms_item-obj_name. ls_tr_key-sub_type = 'CUAD'. ls_tr_key-sub_name = iv_program_name. ls_adm = is_cua-adm. auto_correct_cua_adm( EXPORTING is_cua = is_cua CHANGING cs_adm = ls_adm ). sy-tcode = 'SE41' ##write_ok. "" evil hack, workaround to handle fixes in note 2159455 CALL FUNCTION 'RS_CUA_INTERNAL_WRITE' EXPORTING program = iv_program_name language = mv_language tr_key = ls_tr_key adm = ls_adm state = 'I' TABLES sta = is_cua-sta fun = is_cua-fun men = is_cua-men mtx = is_cua-mtx act = is_cua-act but = is_cua-but pfk = is_cua-pfk set = is_cua-set doc = is_cua-doc tit = is_cua-tit biv = is_cua-biv EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc <> 0. * if moving code from SAPlink, see https://github.com/larshp/abapGit/issues/562 zcx_abapgit_exception=>raise( |Error from RS_CUA_INTERNAL_WRITE. Subrc = { sy-subrc }| ). ENDIF. zcl_abapgit_objects_activation=>add( iv_type = 'CUAD' iv_name = iv_program_name ). ENDMETHOD. METHOD deserialize_dynpros. CONSTANTS lc_rpyty_force_off TYPE char01 VALUE '/' ##NO_TEXT. DATA: lv_name TYPE dwinactiv-obj_name, ls_dynpro LIKE LINE OF it_dynpros. FIELD-SYMBOLS: TYPE rpy_dyfatc. * ls_dynpro is changed by the function module, a field-symbol will cause * the program to dump since it_dynpros cannot be changed LOOP AT it_dynpros INTO ls_dynpro. ls_dynpro-flow_logic = uncondense_flow( it_flow = ls_dynpro-flow_logic it_spaces = ls_dynpro-spaces ). LOOP AT ls_dynpro-fields ASSIGNING . * if the DDIC element has a PARAMETER_ID and the flag ""from_dict"" is active * the import will enable the SET-/GET_PARAM flag. In this case: ""force off"" IF -param_id IS NOT INITIAL AND -from_dict = abap_true. IF -set_param IS INITIAL. -set_param = lc_rpyty_force_off. ENDIF. IF -get_param IS INITIAL. -get_param = lc_rpyty_force_off. ENDIF. ENDIF. * If the previous conditions are met the value 'F' will be taken over * during de-serialization potentially overlapping other fields in the screen, * we set the tag to the correct value 'X' IF -type = 'CHECK' AND -from_dict = abap_true AND -text IS INITIAL AND -modific IS INITIAL. -modific = 'X'. ENDIF. ""fix for issue #2747: IF -foreignkey IS INITIAL. -foreignkey = lc_rpyty_force_off. ENDIF. ENDLOOP. CALL FUNCTION 'RPY_DYNPRO_INSERT' EXPORTING header = ls_dynpro-header suppress_exist_checks = abap_true TABLES containers = ls_dynpro-containers fields_to_containers = ls_dynpro-fields flow_logic = ls_dynpro-flow_logic EXCEPTIONS cancelled = 1 already_exists = 2 program_not_exists = 3 not_executed = 4 missing_required_field = 5 illegal_field_value = 6 field_not_allowed = 7 not_generated = 8 illegal_field_position = 9 OTHERS = 10. IF sy-subrc <> 2 AND sy-subrc <> 0. zcx_abapgit_exception=>raise( |Error from RPY_DYNPRO_INSERT: { sy-subrc }| ). ENDIF. * todo, RPY_DYNPRO_UPDATE? CONCATENATE ls_dynpro-header-program ls_dynpro-header-screen INTO lv_name RESPECTING BLANKS. ASSERT NOT lv_name IS INITIAL. zcl_abapgit_objects_activation=>add( iv_type = 'DYNP' iv_name = lv_name ). ENDLOOP. ENDMETHOD. METHOD deserialize_program. DATA: lv_exists TYPE abap_bool, lv_progname TYPE reposrc-progname, ls_tpool LIKE LINE OF it_tpool, lv_title TYPE rglif-title, ls_progdir_new TYPE progdir. FIELD-SYMBOLS: TYPE any. CALL FUNCTION 'RS_CORR_INSERT' EXPORTING object = is_progdir-name object_class = 'ABAP' devclass = iv_package master_language = mv_language mode = 'I' suppress_dialog = abap_true EXCEPTIONS cancelled = 1 permission_failure = 2 unknown_objectclass = 3 OTHERS = 4. IF sy-subrc = 1. zcx_abapgit_exception=>raise( |Error from RS_CORR_INSERT, Cancelled, { sy-msgid }, { sy-msgno }| ). ELSEIF sy-subrc <> 0. zcx_abapgit_exception=>raise( |Error from RS_CORR_INSERT, { sy-msgid }, { sy-msgno }| ). ENDIF. READ TABLE it_tpool INTO ls_tpool WITH KEY id = 'R'. IF sy-subrc = 0. * there is a bug in RPY_PROGRAM_UPDATE, the header line of TTAB is not * cleared, so the title length might be inherited from a different program. ASSIGN ('(SAPLSIFP)TTAB') TO . IF sy-subrc = 0. CLEAR . ENDIF. lv_title = ls_tpool-entry. ENDIF. SELECT SINGLE progname FROM reposrc INTO lv_progname WHERE progname = is_progdir-name AND r3state = 'A'. IF sy-subrc = 0. lv_exists = abap_true. ELSE. lv_exists = abap_false. ENDIF. IF lv_exists = abap_true. zcl_abapgit_language=>set_current_language( mv_language ). CALL FUNCTION 'RPY_PROGRAM_UPDATE' EXPORTING program_name = is_progdir-name title_string = lv_title save_inactive = 'I' TABLES source_extended = it_source EXCEPTIONS cancelled = 1 permission_error = 2 not_found = 3 OTHERS = 4. IF sy-subrc <> 0. zcl_abapgit_language=>restore_login_language( ). IF sy-msgid = 'EU' AND sy-msgno = '510'. zcx_abapgit_exception=>raise( 'User is currently editing program' ). ELSE. zcx_abapgit_exception=>raise( |PROG { is_progdir-name }, updating error: { sy-msgid } { sy-msgno }| ). ENDIF. ENDIF. zcl_abapgit_language=>restore_login_language( ). ELSEIF strlen( is_progdir-name ) > 30. * function module RPY_PROGRAM_INSERT cannot handle function group includes "" special treatment for extensions "" if the program name exceeds 30 characters it is not a usual "" ABAP program but might be some extension, which requires the internal "" addition EXTENSION TYPE, see "" http://help.sap.com/abapdocu_751/en/abapinsert_report_internal.htm#!ABAP_ADDITION_1@1@ "" This e.g. occurs in case of transportable Code Inspector variants (ending with ===VC) INSERT REPORT is_progdir-name FROM it_source STATE 'I' EXTENSION TYPE is_progdir-name+30. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT REPORT .. EXTENSION TYPE' ). ENDIF. ELSE. INSERT REPORT is_progdir-name FROM it_source STATE 'I' PROGRAM TYPE is_progdir-subc. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT REPORT' ). ENDIF. ENDIF. IF NOT it_tpool[] IS INITIAL. INSERT TEXTPOOL is_progdir-name FROM it_tpool LANGUAGE mv_language STATE 'I'. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT TEXTPOOL' ). ENDIF. ENDIF. CALL FUNCTION 'READ_PROGDIR' EXPORTING i_progname = is_progdir-name i_state = 'I' IMPORTING e_progdir = ls_progdir_new EXCEPTIONS not_exists = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |not found in PROGDIR. Subrc = { sy-subrc }| ). ENDIF. * todo, package? ls_progdir_new-ldbname = is_progdir-ldbname. ls_progdir_new-dbna = is_progdir-dbna. ls_progdir_new-dbapl = is_progdir-dbapl. ls_progdir_new-rload = is_progdir-rload. ls_progdir_new-fixpt = is_progdir-fixpt. ls_progdir_new-varcl = is_progdir-varcl. ls_progdir_new-appl = is_progdir-appl. ls_progdir_new-rstat = is_progdir-rstat. CALL FUNCTION 'UPDATE_PROGDIR' EXPORTING i_progdir = ls_progdir_new i_progname = ls_progdir_new-name i_state = ls_progdir_new-state EXCEPTIONS not_executed = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |PROG, error inserting. Subrc = { sy-subrc }| ). ENDIF. SELECT SINGLE * FROM progdir INTO ls_progdir_new WHERE name = ls_progdir_new-name AND state = ls_progdir_new-state. IF sy-subrc = 0 AND is_progdir-varcl = space AND ls_progdir_new-varcl = abap_true. * function module UPDATE_PROGDIR does not update VARCL UPDATE progdir SET varcl = is_progdir-varcl WHERE name = ls_progdir_new-name AND state = ls_progdir_new-state. ""#EC CI_SUBRC ENDIF. zcl_abapgit_objects_activation=>add( iv_type = 'REPS' iv_name = is_progdir-name ). ENDMETHOD. METHOD deserialize_textpool. DATA lv_language TYPE langu. DATA lv_state TYPE c. DATA lv_delete TYPE abap_bool. IF iv_language IS INITIAL. lv_language = mv_language. ELSE. lv_language = iv_language. ENDIF. IF lv_language = mv_language. lv_state = 'I'. ""Textpool in master language needs to be activated ELSE. lv_state = 'A'. ""Translations are always active ENDIF. IF it_tpool IS INITIAL. IF iv_is_include = abap_false OR lv_state = 'A'. DELETE TEXTPOOL iv_program ""Remove initial description from textpool if LANGUAGE iv_program ""original program does not have a textpool STATE lv_state. lv_delete = abap_true. ELSE. INSERT TEXTPOOL iv_program ""In case of includes: Deletion of textpool in FROM it_tpool ""master language cannot be activated because LANGUAGE lv_language ""this woul activate the deletion of the textpool STATE lv_state. ""of the mail program -> insert empty textpool ENDIF. ELSE. IF lines( it_tpool ) = 1 AND lv_language = mv_language. READ TABLE it_tpool WITH KEY id = 'R' TRANSPORTING NO FIELDS. IF sy-subrc = 0. RETURN. ""No action because description in master language is already there ENDIF. ENDIF. INSERT TEXTPOOL iv_program FROM it_tpool LANGUAGE lv_language STATE lv_state. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT TEXTPOOL' ). ENDIF. ENDIF. IF lv_state = 'I'. ""Textpool in master language needs to be activated zcl_abapgit_objects_activation=>add( iv_type = 'REPT' iv_name = iv_program iv_delete = lv_delete ). ENDIF. ENDMETHOD. METHOD is_any_dynpro_locked. DATA: lt_dynpros TYPE zcl_abapgit_objects_program=>ty_dynpro_tt, lv_object TYPE seqg3-garg. FIELD-SYMBOLS: TYPE zcl_abapgit_objects_program=>ty_dynpro. lt_dynpros = serialize_dynpros( iv_program ). LOOP AT lt_dynpros ASSIGNING . lv_object = |{ -header-screen }{ -header-program }|. IF exists_a_lock_entry_for( iv_lock_object = 'ESCRP' iv_argument = lv_object ) = abap_true. rv_is_any_dynpro_locked = abap_true. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD is_cua_locked. DATA: lv_object TYPE eqegraarg. lv_object = |CU{ iv_program }|. OVERLAY lv_object WITH ' '. lv_object = lv_object && '*'. rv_is_cua_locked = exists_a_lock_entry_for( iv_lock_object = 'ESCUAPAINT' iv_argument = lv_object ). ENDMETHOD. METHOD is_text_locked. DATA: lv_object TYPE eqegraarg. lv_object = |*{ iv_program }|. rv_is_text_locked = exists_a_lock_entry_for( iv_lock_object = 'EABAPTEXTE' iv_argument = lv_object ). ENDMETHOD. METHOD read_progdir. DATA: ls_sapdir TYPE progdir. CALL FUNCTION 'READ_PROGDIR' EXPORTING i_progname = iv_program i_state = 'A' IMPORTING e_progdir = ls_sapdir. MOVE-CORRESPONDING ls_sapdir TO rs_progdir. CLEAR: rs_progdir-edtx, rs_progdir-cnam, rs_progdir-cdat, rs_progdir-unam, rs_progdir-udat, rs_progdir-levl, rs_progdir-vern, rs_progdir-rmand, rs_progdir-sdate, rs_progdir-stime, rs_progdir-idate, rs_progdir-itime, rs_progdir-varcl, rs_progdir-state. ENDMETHOD. METHOD read_tpool. FIELD-SYMBOLS: LIKE LINE OF it_tpool, LIKE LINE OF rt_tpool. LOOP AT it_tpool ASSIGNING . APPEND INITIAL LINE TO rt_tpool ASSIGNING . MOVE-CORRESPONDING TO . IF -id = 'S'. CONCATENATE -split -entry INTO -entry RESPECTING BLANKS. ENDIF. ENDLOOP. ENDMETHOD. METHOD serialize_cua. CALL FUNCTION 'RS_CUA_INTERNAL_FETCH' EXPORTING program = iv_program_name language = mv_language state = 'A' IMPORTING adm = rs_cua-adm TABLES sta = rs_cua-sta fun = rs_cua-fun men = rs_cua-men mtx = rs_cua-mtx act = rs_cua-act but = rs_cua-but pfk = rs_cua-pfk set = rs_cua-set doc = rs_cua-doc tit = rs_cua-tit biv = rs_cua-biv EXCEPTIONS not_found = 1 unknown_version = 2 OTHERS = 3. IF sy-subrc > 1. zcx_abapgit_exception=>raise( |Error from RS_CUA_INTERNAL_FETCH, { sy-subrc }| ). ENDIF. ENDMETHOD. METHOD serialize_dynpros. DATA: ls_header TYPE rpy_dyhead, lt_containers TYPE dycatt_tab, lt_fields_to_containers TYPE dyfatc_tab, lt_flow_logic TYPE swydyflow, lt_d020s TYPE TABLE OF d020s, lt_fieldlist_int TYPE TABLE OF d021s. ""internal format FIELD-SYMBOLS: LIKE LINE OF lt_d020s, TYPE scrpostyle, LIKE LINE OF lt_containers, LIKE LINE OF lt_fields_to_containers, LIKE LINE OF rt_dynpro, LIKE LINE OF lt_fieldlist_int. ""#2746: relevant flag values (taken from include MSEUSBIT) CONSTANTS: lc_flg1ddf TYPE x VALUE '20', lc_flg3fku TYPE x VALUE '08', lc_flg3for TYPE x VALUE '04', lc_flg3fdu TYPE x VALUE '02'. CALL FUNCTION 'RS_SCREEN_LIST' EXPORTING dynnr = '' progname = iv_program_name TABLES dynpros = lt_d020s EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc = 2. zcx_abapgit_exception=>raise( |Error from RS_SCREEN_LIST. Subrc = { sy-subrc }| ). ENDIF. SORT lt_d020s BY dnum ASCENDING. * loop dynpros and skip generated selection screens LOOP AT lt_d020s ASSIGNING WHERE type <> 'S' AND type <> 'W' AND type <> 'J' AND NOT dnum IS INITIAL. CALL FUNCTION 'RPY_DYNPRO_READ' EXPORTING progname = iv_program_name dynnr = -dnum IMPORTING header = ls_header TABLES containers = lt_containers fields_to_containers = lt_fields_to_containers flow_logic = lt_flow_logic EXCEPTIONS cancelled = 1 not_found = 2 permission_error = 3 OTHERS = 4. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |Error while reading dynpro: { sy-subrc }| ). ENDIF. ""#2746: we need the dynpro fields in internal format: FREE lt_fieldlist_int. CALL FUNCTION 'RPY_DYNPRO_READ_NATIVE' EXPORTING progname = iv_program_name dynnr = -dnum TABLES fieldlist = lt_fieldlist_int. LOOP AT lt_fields_to_containers ASSIGNING . * output style is a NUMC field, the XML conversion will fail if it contains invalid value * field does not exist in all versions ASSIGN COMPONENT 'OUTPUTSTYLE' OF STRUCTURE TO . IF sy-subrc = 0 AND = ' '. CLEAR . ENDIF. ""2746: we apply the same logic as in SAPLWBSCREEN ""for setting or unsetting the foreignkey field: UNASSIGN . READ TABLE lt_fieldlist_int ASSIGNING WITH KEY fnam = -name. IF IS ASSIGNED. IF -flg1 O lc_flg1ddf AND -flg3 O lc_flg3for AND -flg3 Z lc_flg3fdu AND -flg3 Z lc_flg3fku. -foreignkey = 'X'. ELSE. CLEAR -foreignkey. ENDIF. ENDIF. ENDLOOP. LOOP AT lt_containers ASSIGNING . IF -c_resize_v = abap_false. CLEAR -c_line_min. ENDIF. IF -c_resize_h = abap_false. CLEAR -c_coln_min. ENDIF. ENDLOOP. APPEND INITIAL LINE TO rt_dynpro ASSIGNING . -header = ls_header. -containers = lt_containers. -fields = lt_fields_to_containers. condense_flow( IMPORTING et_spaces = -spaces CHANGING ct_flow = lt_flow_logic ). -flow_logic = lt_flow_logic. ENDLOOP. ENDMETHOD. METHOD serialize_program. DATA: ls_progdir TYPE ty_progdir, lv_program_name TYPE programm, lt_dynpros TYPE ty_dynpro_tt, ls_cua TYPE ty_cua, lt_source TYPE TABLE OF abaptxt255, lt_tpool TYPE textpool_table, ls_tpool LIKE LINE OF lt_tpool, lo_xml TYPE REF TO zcl_abapgit_xml_output. IF iv_program IS INITIAL. lv_program_name = is_item-obj_name. ELSE. lv_program_name = iv_program. ENDIF. zcl_abapgit_language=>set_current_language( mv_language ). CALL FUNCTION 'RPY_PROGRAM_READ' EXPORTING program_name = lv_program_name with_lowercase = abap_true TABLES source_extended = lt_source textelements = lt_tpool EXCEPTIONS cancelled = 1 not_found = 2 permission_error = 3 OTHERS = 4. IF sy-subrc = 2. zcl_abapgit_language=>restore_login_language( ). RETURN. ELSEIF sy-subrc <> 0. zcl_abapgit_language=>restore_login_language( ). zcx_abapgit_exception=>raise( |Error reading program with RPY_PROGRAM_READ. Subrc = { sy-subrc }| ). ENDIF. zcl_abapgit_language=>restore_login_language( ). ls_progdir = read_progdir( lv_program_name ). IF io_xml IS BOUND. lo_xml = io_xml. ELSE. CREATE OBJECT lo_xml. ENDIF. lo_xml->add( iv_name = 'PROGDIR' ig_data = ls_progdir ). IF ls_progdir-subc = '1' OR ls_progdir-subc = 'M'. lt_dynpros = serialize_dynpros( lv_program_name ). lo_xml->add( iv_name = 'DYNPROS' ig_data = lt_dynpros ). ls_cua = serialize_cua( lv_program_name ). IF NOT ls_cua IS INITIAL. lo_xml->add( iv_name = 'CUA' ig_data = ls_cua ). ENDIF. ENDIF. READ TABLE lt_tpool WITH KEY id = 'R' INTO ls_tpool. IF sy-subrc = 0 AND ls_tpool-key = '' AND ls_tpool-length = 0. DELETE lt_tpool INDEX sy-tabix. ENDIF. lo_xml->add( iv_name = 'TPOOL' ig_data = add_tpool( lt_tpool ) ). IF NOT io_xml IS BOUND. io_files->add_xml( iv_extra = iv_extra io_xml = lo_xml ). ENDIF. io_files->add_abap( iv_extra = iv_extra it_abap = lt_source ). ENDMETHOD. METHOD uncondense_flow. DATA: lv_spaces LIKE LINE OF it_spaces. FIELD-SYMBOLS: LIKE LINE OF it_flow, LIKE LINE OF rt_flow. LOOP AT it_flow ASSIGNING . APPEND INITIAL LINE TO rt_flow ASSIGNING . -line = -line. READ TABLE it_spaces INDEX sy-tabix INTO lv_spaces. IF sy-subrc = 0. SHIFT -line RIGHT BY lv_spaces PLACES IN CHARACTER MODE. ENDIF. ENDLOOP. ENDMETHOD. ENDCLASS. ",8197,False,1673.5618500499022,median "CLASS zcl_abapgit_objects_program DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super. PUBLIC SECTION. TYPES: BEGIN OF ty_progdir, name TYPE progdir-name, state TYPE progdir-state, sqlx TYPE progdir-sqlx, edtx TYPE progdir-edtx, varcl TYPE progdir-varcl, dbapl TYPE progdir-dbapl, dbna TYPE progdir-dbna, clas TYPE progdir-clas, type TYPE progdir-type, occurs TYPE progdir-occurs, subc TYPE progdir-subc, appl TYPE progdir-appl, secu TYPE progdir-secu, cnam TYPE progdir-cnam, cdat TYPE progdir-cdat, unam TYPE progdir-unam, udat TYPE progdir-udat, vern TYPE progdir-vern, levl TYPE progdir-levl, rstat TYPE progdir-rstat, rmand TYPE progdir-rmand, rload TYPE progdir-rload, fixpt TYPE progdir-fixpt, sset TYPE progdir-sset, sdate TYPE progdir-sdate, stime TYPE progdir-stime, idate TYPE progdir-idate, itime TYPE progdir-itime, ldbname TYPE progdir-ldbname, uccheck TYPE progdir-uccheck, END OF ty_progdir. METHODS serialize_program IMPORTING io_xml TYPE REF TO zif_abapgit_xml_output OPTIONAL is_item TYPE zif_abapgit_definitions=>ty_item io_files TYPE REF TO zcl_abapgit_objects_files iv_program TYPE programm OPTIONAL iv_extra TYPE clike OPTIONAL RAISING zcx_abapgit_exception. METHODS read_progdir IMPORTING iv_program TYPE programm RETURNING VALUE(rs_progdir) TYPE ty_progdir. METHODS deserialize_program IMPORTING is_progdir TYPE ty_progdir it_source TYPE abaptxt255_tab it_tpool TYPE textpool_table iv_package TYPE devclass RAISING zcx_abapgit_exception. PROTECTED SECTION. TYPES: ty_spaces_tt TYPE STANDARD TABLE OF i WITH DEFAULT KEY . TYPES: BEGIN OF ty_dynpro, header TYPE rpy_dyhead, containers TYPE dycatt_tab, fields TYPE dyfatc_tab, flow_logic TYPE swydyflow, spaces TYPE ty_spaces_tt, END OF ty_dynpro . TYPES: ty_dynpro_tt TYPE STANDARD TABLE OF ty_dynpro WITH DEFAULT KEY . TYPES: BEGIN OF ty_cua, adm TYPE rsmpe_adm, sta TYPE STANDARD TABLE OF rsmpe_stat WITH DEFAULT KEY, fun TYPE STANDARD TABLE OF rsmpe_funt WITH DEFAULT KEY, men TYPE STANDARD TABLE OF rsmpe_men WITH DEFAULT KEY, mtx TYPE STANDARD TABLE OF rsmpe_mnlt WITH DEFAULT KEY, act TYPE STANDARD TABLE OF rsmpe_act WITH DEFAULT KEY, but TYPE STANDARD TABLE OF rsmpe_but WITH DEFAULT KEY, pfk TYPE STANDARD TABLE OF rsmpe_pfk WITH DEFAULT KEY, set TYPE STANDARD TABLE OF rsmpe_staf WITH DEFAULT KEY, doc TYPE STANDARD TABLE OF rsmpe_atrt WITH DEFAULT KEY, tit TYPE STANDARD TABLE OF rsmpe_titt WITH DEFAULT KEY, biv TYPE STANDARD TABLE OF rsmpe_buts WITH DEFAULT KEY, END OF ty_cua . METHODS serialize_dynpros IMPORTING !iv_program_name TYPE programm RETURNING VALUE(rt_dynpro) TYPE ty_dynpro_tt RAISING zcx_abapgit_exception . METHODS serialize_cua IMPORTING !iv_program_name TYPE programm RETURNING VALUE(rs_cua) TYPE ty_cua RAISING zcx_abapgit_exception . METHODS deserialize_dynpros IMPORTING !it_dynpros TYPE ty_dynpro_tt RAISING zcx_abapgit_exception . METHODS deserialize_textpool IMPORTING !iv_program TYPE programm !it_tpool TYPE textpool_table !iv_language TYPE langu OPTIONAL !iv_is_include TYPE abap_bool DEFAULT abap_false RAISING zcx_abapgit_exception . METHODS deserialize_cua IMPORTING !iv_program_name TYPE programm !is_cua TYPE ty_cua RAISING zcx_abapgit_exception . METHODS is_any_dynpro_locked IMPORTING !iv_program TYPE programm RETURNING VALUE(rv_is_any_dynpro_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_cua_locked IMPORTING !iv_program TYPE programm RETURNING VALUE(rv_is_cua_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_text_locked IMPORTING !iv_program TYPE programm RETURNING VALUE(rv_is_text_locked) TYPE abap_bool RAISING zcx_abapgit_exception . CLASS-METHODS add_tpool IMPORTING !it_tpool TYPE textpool_table RETURNING VALUE(rt_tpool) TYPE zif_abapgit_definitions=>ty_tpool_tt . CLASS-METHODS read_tpool IMPORTING !it_tpool TYPE zif_abapgit_definitions=>ty_tpool_tt RETURNING VALUE(rt_tpool) TYPE zif_abapgit_definitions=>ty_tpool_tt . PRIVATE SECTION. METHODS: uncondense_flow IMPORTING it_flow TYPE swydyflow it_spaces TYPE ty_spaces_tt RETURNING VALUE(rt_flow) TYPE swydyflow. CLASS-METHODS auto_correct_cua_adm IMPORTING is_cua TYPE ty_cua CHANGING cs_adm TYPE rsmpe_adm. ENDCLASS. CLASS zcl_abapgit_objects_program IMPLEMENTATION. METHOD add_tpool. FIELD-SYMBOLS: LIKE LINE OF it_tpool, LIKE LINE OF rt_tpool. LOOP AT it_tpool ASSIGNING . APPEND INITIAL LINE TO rt_tpool ASSIGNING . MOVE-CORRESPONDING TO . IF -id = 'S'. -split = -entry. -entry = -entry+8. ENDIF. ENDLOOP. ENDMETHOD. METHOD auto_correct_cua_adm. "" issue #1807 automatic correction of CUA interfaces saved incorrectly in the past (ADM was not saved in the XML) CONSTANTS: lc_num_n_space TYPE string VALUE ' 0123456789', lc_num_only TYPE string VALUE '0123456789'. FIELD-SYMBOLS: TYPE rsmpe_pfk, TYPE rsmpe_act, TYPE rsmpe_men. IF cs_adm IS NOT INITIAL AND cs_adm-actcode CO lc_num_n_space AND cs_adm-mencode CO lc_num_n_space AND cs_adm-pfkcode CO lc_num_n_space. ""Check performed in form check_adm of include LSMPIF03 RETURN. ENDIF. LOOP AT is_cua-act ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO lc_num_only. cs_adm-actcode = -code. ENDIF. ENDLOOP. LOOP AT is_cua-men ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO lc_num_only. cs_adm-mencode = -code. ENDIF. ENDLOOP. LOOP AT is_cua-pfk ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO lc_num_only. cs_adm-pfkcode = -code. ENDIF. ENDLOOP. ENDMETHOD. METHOD deserialize_cua. DATA: ls_tr_key TYPE trkey, ls_adm TYPE rsmpe_adm. IF lines( is_cua-sta ) = 0 AND lines( is_cua-fun ) = 0 AND lines( is_cua-men ) = 0 AND lines( is_cua-mtx ) = 0 AND lines( is_cua-act ) = 0 AND lines( is_cua-but ) = 0 AND lines( is_cua-pfk ) = 0 AND lines( is_cua-set ) = 0 AND lines( is_cua-doc ) = 0 AND lines( is_cua-tit ) = 0 AND lines( is_cua-biv ) = 0. RETURN. ENDIF. SELECT SINGLE devclass INTO ls_tr_key-devclass FROM tadir WHERE pgmid = 'R3TR' AND object = ms_item-obj_type AND obj_name = ms_item-obj_name. ""#EC CI_GENBUFF IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'not found in tadir' ). ENDIF. ls_tr_key-obj_type = ms_item-obj_type. ls_tr_key-obj_name = ms_item-obj_name. ls_tr_key-sub_type = 'CUAD'. ls_tr_key-sub_name = iv_program_name. ls_adm = is_cua-adm. auto_correct_cua_adm( EXPORTING is_cua = is_cua CHANGING cs_adm = ls_adm ). sy-tcode = 'SE41' ##write_ok. "" evil hack, workaround to handle fixes in note 2159455 CALL FUNCTION 'RS_CUA_INTERNAL_WRITE' EXPORTING program = iv_program_name language = mv_language tr_key = ls_tr_key adm = ls_adm state = 'I' TABLES sta = is_cua-sta fun = is_cua-fun men = is_cua-men mtx = is_cua-mtx act = is_cua-act but = is_cua-but pfk = is_cua-pfk set = is_cua-set doc = is_cua-doc tit = is_cua-tit biv = is_cua-biv EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc <> 0. * if moving code from SAPlink, see https://github.com/abapGit/abapGit/issues/562 zcx_abapgit_exception=>raise_t100( ). ENDIF. zcl_abapgit_objects_activation=>add( iv_type = 'CUAD' iv_name = iv_program_name ). ENDMETHOD. METHOD deserialize_dynpros. CONSTANTS lc_rpyty_force_off TYPE c LENGTH 1 VALUE '/'. DATA: lv_name TYPE dwinactiv-obj_name, ls_dynpro LIKE LINE OF it_dynpros. FIELD-SYMBOLS: TYPE rpy_dyfatc. * ls_dynpro is changed by the function module, a field-symbol will cause * the program to dump since it_dynpros cannot be changed LOOP AT it_dynpros INTO ls_dynpro. "" todo: kept for compatibility, remove after grace period #3680 ls_dynpro-flow_logic = uncondense_flow( it_flow = ls_dynpro-flow_logic it_spaces = ls_dynpro-spaces ). LOOP AT ls_dynpro-fields ASSIGNING . * if the DDIC element has a PARAMETER_ID and the flag ""from_dict"" is active * the import will enable the SET-/GET_PARAM flag. In this case: ""force off"" IF -param_id IS NOT INITIAL AND -from_dict = abap_true. IF -set_param IS INITIAL. -set_param = lc_rpyty_force_off. ENDIF. IF -get_param IS INITIAL. -get_param = lc_rpyty_force_off. ENDIF. ENDIF. * If the previous conditions are met the value 'F' will be taken over * during de-serialization potentially overlapping other fields in the screen, * we set the tag to the correct value 'X' IF -type = 'CHECK' AND -from_dict = abap_true AND -text IS INITIAL AND -modific IS INITIAL. -modific = 'X'. ENDIF. ""fix for issue #2747: IF -foreignkey IS INITIAL. -foreignkey = lc_rpyty_force_off. ENDIF. ENDLOOP. CALL FUNCTION 'RPY_DYNPRO_INSERT' EXPORTING header = ls_dynpro-header suppress_exist_checks = abap_true TABLES containers = ls_dynpro-containers fields_to_containers = ls_dynpro-fields flow_logic = ls_dynpro-flow_logic EXCEPTIONS cancelled = 1 already_exists = 2 program_not_exists = 3 not_executed = 4 missing_required_field = 5 illegal_field_value = 6 field_not_allowed = 7 not_generated = 8 illegal_field_position = 9 OTHERS = 10. IF sy-subrc <> 2 AND sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. * todo, RPY_DYNPRO_UPDATE? CONCATENATE ls_dynpro-header-program ls_dynpro-header-screen INTO lv_name RESPECTING BLANKS. ASSERT NOT lv_name IS INITIAL. zcl_abapgit_objects_activation=>add( iv_type = 'DYNP' iv_name = lv_name ). ENDLOOP. ENDMETHOD. METHOD deserialize_program. DATA: lv_exists TYPE abap_bool, lt_empty_src LIKE it_source, lv_progname TYPE reposrc-progname, ls_tpool LIKE LINE OF it_tpool, lv_title TYPE rglif-title, ls_progdir_new TYPE progdir. FIELD-SYMBOLS: TYPE any. CALL FUNCTION 'RS_CORR_INSERT' EXPORTING object = is_progdir-name object_class = 'ABAP' devclass = iv_package master_language = mv_language mode = 'I' suppress_dialog = abap_true EXCEPTIONS cancelled = 1 permission_failure = 2 unknown_objectclass = 3 OTHERS = 4. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. READ TABLE it_tpool INTO ls_tpool WITH KEY id = 'R'. IF sy-subrc = 0. * there is a bug in RPY_PROGRAM_UPDATE, the header line of TTAB is not * cleared, so the title length might be inherited from a different program. ASSIGN ('(SAPLSIFP)TTAB') TO . IF sy-subrc = 0. CLEAR . ENDIF. lv_title = ls_tpool-entry. ENDIF. SELECT SINGLE progname FROM reposrc INTO lv_progname WHERE progname = is_progdir-name AND r3state = 'A'. lv_exists = boolc( sy-subrc = 0 ). IF lv_exists = abap_true. zcl_abapgit_language=>set_current_language( mv_language ). CALL FUNCTION 'RPY_PROGRAM_UPDATE' EXPORTING program_name = is_progdir-name title_string = lv_title save_inactive = 'I' TABLES source_extended = it_source EXCEPTIONS cancelled = 1 permission_error = 2 not_found = 3 OTHERS = 4. IF sy-subrc <> 0. zcl_abapgit_language=>restore_login_language( ). IF sy-msgid = 'EU' AND sy-msgno = '510'. zcx_abapgit_exception=>raise( 'User is currently editing program' ). ELSEIF sy-msgid = 'EU' AND sy-msgno = '522'. * for generated table maintenance function groups, the author is set to SAP* instead of the user which * generates the function group. This hits some standard checks, pulling new code again sets the author * to the current user which avoids the check zcx_abapgit_exception=>raise( |Delete function group and pull again, { is_progdir-name } (EU522)| ). ELSE. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDIF. zcl_abapgit_language=>restore_login_language( ). ELSEIF strlen( is_progdir-name ) > 30. * function module RPY_PROGRAM_INSERT cannot handle function group includes "" special treatment for extensions "" if the program name exceeds 30 characters it is not a usual "" ABAP program but might be some extension, which requires the internal "" addition EXTENSION TYPE, see "" http://help.sap.com/abapdocu_751/en/abapinsert_report_internal.htm#!ABAP_ADDITION_1@1@ "" This e.g. occurs in case of transportable Code Inspector variants (ending with ===VC) INSERT REPORT is_progdir-name FROM it_source STATE 'I' EXTENSION TYPE is_progdir-name+30. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT REPORT .. EXTENSION TYPE' ). ENDIF. ELSE. INSERT REPORT is_progdir-name FROM it_source STATE 'I' PROGRAM TYPE is_progdir-subc. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDIF. IF NOT it_tpool[] IS INITIAL. INSERT TEXTPOOL is_progdir-name FROM it_tpool LANGUAGE mv_language STATE 'I'. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT TEXTPOOL' ). ENDIF. ENDIF. CALL FUNCTION 'READ_PROGDIR' EXPORTING i_progname = is_progdir-name i_state = 'I' IMPORTING e_progdir = ls_progdir_new EXCEPTIONS not_exists = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |not found in PROGDIR. Subrc = { sy-subrc }| ). ENDIF. * todo, package? ls_progdir_new-ldbname = is_progdir-ldbname. ls_progdir_new-dbna = is_progdir-dbna. ls_progdir_new-dbapl = is_progdir-dbapl. ls_progdir_new-rload = is_progdir-rload. ls_progdir_new-fixpt = is_progdir-fixpt. ls_progdir_new-varcl = is_progdir-varcl. ls_progdir_new-appl = is_progdir-appl. ls_progdir_new-rstat = is_progdir-rstat. ls_progdir_new-sqlx = is_progdir-sqlx. ls_progdir_new-uccheck = is_progdir-uccheck. ls_progdir_new-clas = is_progdir-clas. CALL FUNCTION 'UPDATE_PROGDIR' EXPORTING i_progdir = ls_progdir_new i_progname = ls_progdir_new-name i_state = ls_progdir_new-state EXCEPTIONS not_executed = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |PROG, error inserting. Subrc = { sy-subrc }| ). ENDIF. SELECT SINGLE * FROM progdir INTO ls_progdir_new WHERE name = ls_progdir_new-name AND state = ls_progdir_new-state. IF sy-subrc = 0 AND is_progdir-varcl = space AND ls_progdir_new-varcl = abap_true. * function module UPDATE_PROGDIR does not update VARCL UPDATE progdir SET varcl = is_progdir-varcl WHERE name = ls_progdir_new-name AND state = ls_progdir_new-state. ""#EC CI_SUBRC ENDIF. zcl_abapgit_objects_activation=>add( iv_type = 'REPS' iv_name = is_progdir-name ). ENDMETHOD. METHOD deserialize_textpool. DATA lv_language TYPE langu. DATA lv_state TYPE c. DATA lv_delete TYPE abap_bool. IF iv_language IS INITIAL. lv_language = mv_language. ELSE. lv_language = iv_language. ENDIF. IF lv_language = mv_language. lv_state = 'I'. ""Textpool in main language needs to be activated ELSE. lv_state = 'A'. ""Translations are always active ENDIF. IF it_tpool IS INITIAL. IF iv_is_include = abap_false OR lv_state = 'A'. DELETE TEXTPOOL iv_program ""Remove initial description from textpool if LANGUAGE lv_language ""original program does not have a textpool STATE lv_state. lv_delete = abap_true. ELSE. INSERT TEXTPOOL iv_program ""In case of includes: Deletion of textpool in FROM it_tpool ""main language cannot be activated because LANGUAGE lv_language ""this woul activate the deletion of the textpool STATE lv_state. ""of the mail program -> insert empty textpool ENDIF. ELSE. IF lines( it_tpool ) = 1 AND lv_language = mv_language. READ TABLE it_tpool WITH KEY id = 'R' TRANSPORTING NO FIELDS. IF sy-subrc = 0. RETURN. ""No action because description in main language is already there ENDIF. ENDIF. INSERT TEXTPOOL iv_program FROM it_tpool LANGUAGE lv_language STATE lv_state. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT TEXTPOOL' ). ENDIF. ENDIF. IF lv_state = 'I'. ""Textpool in main language needs to be activated zcl_abapgit_objects_activation=>add( iv_type = 'REPT' iv_name = iv_program iv_delete = lv_delete ). ENDIF. ENDMETHOD. METHOD is_any_dynpro_locked. DATA: lt_dynpros TYPE ty_dynpro_tt, lv_object TYPE seqg3-garg. FIELD-SYMBOLS: TYPE ty_dynpro. lt_dynpros = serialize_dynpros( iv_program ). LOOP AT lt_dynpros ASSIGNING . lv_object = |{ -header-screen }{ -header-program }|. IF exists_a_lock_entry_for( iv_lock_object = 'ESCRP' iv_argument = lv_object ) = abap_true. rv_is_any_dynpro_locked = abap_true. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD is_cua_locked. DATA: lv_object TYPE eqegraarg. lv_object = |CU{ iv_program }|. OVERLAY lv_object WITH ' '. lv_object = lv_object && '*'. rv_is_cua_locked = exists_a_lock_entry_for( iv_lock_object = 'ESCUAPAINT' iv_argument = lv_object ). ENDMETHOD. METHOD is_text_locked. DATA: lv_object TYPE eqegraarg. lv_object = |*{ iv_program }|. rv_is_text_locked = exists_a_lock_entry_for( iv_lock_object = 'EABAPTEXTE' iv_argument = lv_object ). ENDMETHOD. METHOD read_progdir. DATA: ls_sapdir TYPE progdir. CALL FUNCTION 'READ_PROGDIR' EXPORTING i_progname = iv_program i_state = 'A' IMPORTING e_progdir = ls_sapdir. MOVE-CORRESPONDING ls_sapdir TO rs_progdir. CLEAR: rs_progdir-edtx, rs_progdir-cnam, rs_progdir-cdat, rs_progdir-unam, rs_progdir-udat, rs_progdir-levl, rs_progdir-vern, rs_progdir-rmand, rs_progdir-sdate, rs_progdir-stime, rs_progdir-idate, rs_progdir-itime, rs_progdir-varcl, rs_progdir-state. ENDMETHOD. METHOD read_tpool. FIELD-SYMBOLS: LIKE LINE OF it_tpool, LIKE LINE OF rt_tpool. LOOP AT it_tpool ASSIGNING . APPEND INITIAL LINE TO rt_tpool ASSIGNING . MOVE-CORRESPONDING TO . IF -id = 'S'. CONCATENATE -split -entry INTO -entry RESPECTING BLANKS. ENDIF. ENDLOOP. ENDMETHOD. METHOD serialize_cua. CALL FUNCTION 'RS_CUA_INTERNAL_FETCH' EXPORTING program = iv_program_name language = mv_language state = 'A' IMPORTING adm = rs_cua-adm TABLES sta = rs_cua-sta fun = rs_cua-fun men = rs_cua-men mtx = rs_cua-mtx act = rs_cua-act but = rs_cua-but pfk = rs_cua-pfk set = rs_cua-set doc = rs_cua-doc tit = rs_cua-tit biv = rs_cua-biv EXCEPTIONS not_found = 1 unknown_version = 2 OTHERS = 3. IF sy-subrc > 1. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDMETHOD. METHOD serialize_dynpros. DATA: ls_header TYPE rpy_dyhead, lt_containers TYPE dycatt_tab, lt_fields_to_containers TYPE dyfatc_tab, lt_flow_logic TYPE swydyflow, lt_d020s TYPE TABLE OF d020s, lt_fieldlist_int TYPE TABLE OF d021s. ""internal format FIELD-SYMBOLS: LIKE LINE OF lt_d020s, TYPE scrpostyle, LIKE LINE OF lt_containers, LIKE LINE OF lt_fields_to_containers, LIKE LINE OF rt_dynpro, LIKE LINE OF lt_fieldlist_int. ""#2746: relevant flag values (taken from include MSEUSBIT) CONSTANTS: lc_flg1ddf TYPE x VALUE '20', lc_flg3fku TYPE x VALUE '08', lc_flg3for TYPE x VALUE '04', lc_flg3fdu TYPE x VALUE '02'. CALL FUNCTION 'RS_SCREEN_LIST' EXPORTING dynnr = '' progname = iv_program_name TABLES dynpros = lt_d020s EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc = 2. zcx_abapgit_exception=>raise_t100( ). ENDIF. SORT lt_d020s BY dnum ASCENDING. * loop dynpros and skip generated selection screens LOOP AT lt_d020s ASSIGNING WHERE type <> 'S' AND type <> 'W' AND type <> 'J' AND NOT dnum IS INITIAL. CALL FUNCTION 'RPY_DYNPRO_READ' EXPORTING progname = iv_program_name dynnr = -dnum IMPORTING header = ls_header TABLES containers = lt_containers fields_to_containers = lt_fields_to_containers flow_logic = lt_flow_logic EXCEPTIONS cancelled = 1 not_found = 2 permission_error = 3 OTHERS = 4. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ""#2746: we need the dynpro fields in internal format: FREE lt_fieldlist_int. CALL FUNCTION 'RPY_DYNPRO_READ_NATIVE' EXPORTING progname = iv_program_name dynnr = -dnum TABLES fieldlist = lt_fieldlist_int. LOOP AT lt_fields_to_containers ASSIGNING . * output style is a NUMC field, the XML conversion will fail if it contains invalid value * field does not exist in all versions ASSIGN COMPONENT 'OUTPUTSTYLE' OF STRUCTURE TO . IF sy-subrc = 0 AND = ' '. CLEAR . ENDIF. ""2746: we apply the same logic as in SAPLWBSCREEN ""for setting or unsetting the foreignkey field: UNASSIGN . READ TABLE lt_fieldlist_int ASSIGNING WITH KEY fnam = -name. IF IS ASSIGNED. IF -flg1 O lc_flg1ddf AND -flg3 O lc_flg3for AND -flg3 Z lc_flg3fdu AND -flg3 Z lc_flg3fku. -foreignkey = 'X'. ELSE. CLEAR -foreignkey. ENDIF. ENDIF. ENDLOOP. LOOP AT lt_containers ASSIGNING . IF -c_resize_v = abap_false. CLEAR -c_line_min. ENDIF. IF -c_resize_h = abap_false. CLEAR -c_coln_min. ENDIF. ENDLOOP. APPEND INITIAL LINE TO rt_dynpro ASSIGNING . -header = ls_header. -containers = lt_containers. -fields = lt_fields_to_containers. -flow_logic = lt_flow_logic. ENDLOOP. ENDMETHOD. METHOD serialize_program. DATA: ls_progdir TYPE ty_progdir, lv_program_name TYPE programm, lt_dynpros TYPE ty_dynpro_tt, ls_cua TYPE ty_cua, lt_source TYPE TABLE OF abaptxt255, lt_tpool TYPE textpool_table, ls_tpool LIKE LINE OF lt_tpool, li_xml TYPE REF TO zif_abapgit_xml_output. IF iv_program IS INITIAL. lv_program_name = is_item-obj_name. ELSE. lv_program_name = iv_program. ENDIF. zcl_abapgit_language=>set_current_language( mv_language ). CALL FUNCTION 'RPY_PROGRAM_READ' EXPORTING program_name = lv_program_name with_includelist = abap_false with_lowercase = abap_true TABLES source_extended = lt_source textelements = lt_tpool EXCEPTIONS cancelled = 1 not_found = 2 permission_error = 3 OTHERS = 4. IF sy-subrc = 2. zcl_abapgit_language=>restore_login_language( ). RETURN. ELSEIF sy-subrc <> 0. zcl_abapgit_language=>restore_login_language( ). zcx_abapgit_exception=>raise_t100( ). ENDIF. zcl_abapgit_language=>restore_login_language( ). ls_progdir = read_progdir( lv_program_name ). IF io_xml IS BOUND. li_xml = io_xml. ELSE. CREATE OBJECT li_xml TYPE zcl_abapgit_xml_output. ENDIF. li_xml->add( iv_name = 'PROGDIR' ig_data = ls_progdir ). IF ls_progdir-subc = '1' OR ls_progdir-subc = 'M'. lt_dynpros = serialize_dynpros( lv_program_name ). li_xml->add( iv_name = 'DYNPROS' ig_data = lt_dynpros ). ls_cua = serialize_cua( lv_program_name ). IF NOT ls_cua IS INITIAL. li_xml->add( iv_name = 'CUA' ig_data = ls_cua ). ENDIF. ENDIF. READ TABLE lt_tpool WITH KEY id = 'R' INTO ls_tpool. IF sy-subrc = 0 AND ls_tpool-key = '' AND ls_tpool-length = 0. DELETE lt_tpool INDEX sy-tabix. ENDIF. li_xml->add( iv_name = 'TPOOL' ig_data = add_tpool( lt_tpool ) ). IF NOT io_xml IS BOUND. io_files->add_xml( iv_extra = iv_extra ii_xml = li_xml ). ENDIF. io_files->add_abap( iv_extra = iv_extra it_abap = lt_source ). ENDMETHOD. METHOD uncondense_flow. DATA: lv_spaces LIKE LINE OF it_spaces. FIELD-SYMBOLS: LIKE LINE OF it_flow, LIKE LINE OF rt_flow. LOOP AT it_flow ASSIGNING . APPEND INITIAL LINE TO rt_flow ASSIGNING . -line = -line. READ TABLE it_spaces INDEX sy-tabix INTO lv_spaces. IF sy-subrc = 0. SHIFT -line RIGHT BY lv_spaces PLACES IN CHARACTER MODE. ENDIF. ENDLOOP. ENDMETHOD. ENDCLASS. ",8010,False,1623.5821637933955,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.components { import flash.display.DisplayObject; import flash.display.InteractiveObject; import flash.display.StageDisplayState; import flash.events.ContextMenuEvent; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.FullScreenEvent; import flash.events.SoftKeyboardEvent; import flash.events.UncaughtErrorEvent; import flash.external.ExternalInterface; import flash.geom.Rectangle; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.system.Capabilities; import flash.ui.ContextMenu; import flash.ui.ContextMenuItem; import flash.utils.Dictionary; import flash.utils.setInterval; import mx.core.EventPriority; import mx.core.FlexGlobals; import mx.core.IInvalidating; import mx.core.InteractionMode; import mx.core.Singleton; import mx.core.UIComponentGlobals; import mx.core.mx_internal; import mx.managers.FocusManager; import mx.managers.IActiveWindowManager; import mx.managers.ILayoutManager; import mx.managers.ISystemManager; import mx.managers.SystemManager; import mx.managers.ToolTipManager; import mx.utils.BitFlagUtil; import mx.utils.DensityUtil; import mx.utils.LoaderUtil; import mx.utils.Platform; import spark.layouts.supportClasses.LayoutBase; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched after the Application has been initialized, * processed by the LayoutManager, and attached to the display list. * * @eventType mx.events.FlexEvent.APPLICATION_COMPLETE * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ [Event(name=""applicationComplete"", type=""mx.events.FlexEvent"")] /** * Dispatched when an HTTPService call fails. * * @eventType flash.events.ErrorEvent.ERROR * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ [Event(name=""error"", type=""flash.events.ErrorEvent"")] /** * Dispatched when an uncaught error is caught by the Global Exception Handler * * @eventType flash.events.UncaughtErrorEvent.UNCAUGHT_ERROR * * @langversion 3.0 * @playerversion Flash 10.1 * @playerversion AIR 2.0 * @productversion Flex 4.5 */ [Event(name=""uncaughtError"", type=""flash.events.UncaughtErrorEvent"")] //-------------------------------------- // Styles //-------------------------------------- /** * The background color of the application. This color is used as the stage color for the * application and the background color for the HTML embed tag. * * @default 0x464646 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ [Style(name=""backgroundColor"", type=""uint"", format=""Color"", inherit=""no"")] /** * Height in pixels left for os top status bar display. *

    Status bar height is set by default to 20 pixels (at 160 DPI) for iOS7, on the following default skins:

    *
      *
    • >skins.spark.ApplicationSkin
    • *
    • spark.skins.mobile.TabbedViewNavigatorApplicationSkin
    • *
    • spark.skins.mobile.ViewNavigatorApplicationSkin
    • *
    */ [Style(name=""osStatusBarHeight"", type=""Number"", format=""Length"", inherit=""no"", theme=""mobile"")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name=""direction"", kind=""property"")] [Exclude(name=""tabIndex"", kind=""property"")] [Exclude(name=""toolTip"", kind=""property"")] [Exclude(name=""x"", kind=""property"")] [Exclude(name=""y"", kind=""property"")] //-------------------------------------- // Other metadata //-------------------------------------- /** * The frameworks must be initialized by SystemManager. * This factoryClass will be automatically subclassed by any * MXML applications that don't explicitly specify a different * factoryClass. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ [Frame(factoryClass=""mx.managers.SystemManager"")] [ResourceBundle(""components"")] /** * Flex defines a default, or Application, container that lets you start * adding content to your application without explicitly defining * another container. * *

    The Application container has the following default characteristics:

    * * * * * * * * * * * * * * * * * * * * * *
    CharacteristicDescription
    Default size375 pixels high and 500 pixels wide in the Standalone Flash Player, * and all available space in a browser
    Minimum size0 pixels wide and 0 pixels high
    Maximum sizeNo limit
    Default skin classspark.skins.spark.ApplicationSkin
    * * @mxml * *

    The <s:Application> tag inherits all of the tag * attributes of its superclass and adds the following tag attributes:

    * *
     *  <s:Application
     *    Properties
     *    applicationDPI=Device dependent""
     *    backgroundColor=""0xFFFFFF""
     *    colorCorrection=""default""
     *    controlBarContent=""null""
     *    controlBarLayout=""HorizontalLayout""
     *    controlBarVisible=""true""
     *    frameRate=""24""
     *    pageTitle""""
     *    preloader=""No default""
     *    preloaderChromeColor=""No default""
     *    resizeForSoftKeyboard=true""
     *    runtimeDPIProvider=""RuntimeDPIProvider""
     *    scriptRecursionLimit=""1000""
     *    scriptTimeLimit=""60""
     *    splashScreenImage=""""
     *    splashScreenMinimumDisplayTime=""1000""
     *    splashScreenScaleMode=""none""
     *    usePreloader=""true""
     *    viewSourceURL=""""
     *    xmlns:No default=""No default""
     *
     *    Events
     *    applicationComplete=""No default""
     *    error=""No default""
     *  />
     *  
    * * @see spark.skins.spark.ApplicationSkin * @includeExample examples/ApplicationContainerExample.mxml * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public class Application extends SkinnableContainer { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private */ private static const CONTROLBAR_PROPERTY_FLAG:uint = 1 << 0; /** * @private */ private static const LAYOUT_PROPERTY_FLAG:uint = 1 << 1; /** * @private */ private static const VISIBLE_PROPERTY_FLAG:uint = 1 << 2; //-------------------------------------------------------------------------- // // Class properties // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function Application() { UIComponentGlobals.layoutManager = ILayoutManager( Singleton.getInstance(""mx.managers::ILayoutManager"")); UIComponentGlobals.layoutManager.usePhasedInstantiation = true; if (!FlexGlobals.topLevelApplication) FlexGlobals.topLevelApplication = this; super(); showInAutomationHierarchy = true; initResizeBehavior(); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Variable that determines whether this application is running on iOS. */ private var isIOS:Boolean = false; /** * @private * This variable stores the last object that received the SOFT_KEYBOARD_ACTIVATE * event. */ private var softKeyboardTarget:Object = null; /** * @private * Flag set to true if the application has temporarily set its explicit * width and height to deal with orientation. */ private var explicitSizingForOrientation:Boolean = false; /** * @private * Caches the application's width and height values for better resizing * of the screen during orientation changes. Keys are composed of the width and * height values in a string of the form ""w:h"", e.g. ""1004:768"" and represent * the screen dimensions before the orientation change. Values are * objects containing width and height properties that represent the screen dimensions * after the orientation change. */ private var cachedDimensions:Dictionary; /** * @private * Previous width of the application prior to an orientation change */ private var previousWidth:Number; /** * @private * Previous height of the application prior to an orientation change */ private var previousHeight:Number; /** * @private * Flag to determine if the keyboard is active during an orientation change, * to minimize renders during the orientation change. */ private var keyboardActiveInOrientationChange:Boolean = false; /** * @private */ private var resizeHandlerAdded:Boolean = false; /** * @private */ private var percentBoundsChanged:Boolean; /** * @private * Placeholder for Preloader object reference. */ private var preloadObj:Object; /** * @private * This flag indicates whether the width of the Application instance * can change or has been explicitly set by the developer. * When the stage is resized we use this flag to know whether the * width of the Application should be modified. */ private var resizeWidth:Boolean = true; /** * @private * This flag indicates whether the height of the Application instance * can change or has been explicitly set by the developer. * When the stage is resized we use this flag to know whether the * height of the Application should be modified. */ private var resizeHeight:Boolean = true; /** * @private */ private static var _softKeyboardBehavior:String = null; /** * @private */ mx_internal var isSoftKeyboardActive:Boolean = false; /** * @private */ private var synchronousResize:Boolean = false; /** * @private * (Possibly null) reference to the View Source context menu item, * so that we can update it for runtime localization. */ private var viewSourceCMI:ContextMenuItem; /** * @private * Return the density scaling factor for the application */ private function get scaleFactor():Number { if (systemManager) return (systemManager as SystemManager).densityScale; return 1; } //---------------------------------- // colorCorrection //---------------------------------- [Inspectable(enumeration=""default,off,on"", defaultValue=""default"" )] /** * The value of the stage's colorCorrection property. * If this application does not have access to the stage's colorCorrection property, * the value of the colorCorrection property is null. * *

    Only the main application is allowed to set the colorCorrection * property. If a nested application's needs to set the color correction property, it * must set it by referencing the main application's instance.

    * * @default ColorCorrection.DEFAULT * * @see flash.display.ColorCorrection * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get colorCorrection():String { try { var sm:ISystemManager = systemManager; if (sm && sm.stage) return sm.stage.colorCorrection; } catch (e:SecurityError) { // ignore error if this application is not allow // to view the colorCorrection property. } return null; } /** * @private */ public function set colorCorrection(value:String):void { // Since only the main application is allowed to change the value this property, there // is no need to catch security violations like in the getter. var sm:ISystemManager = systemManager; if (sm && sm.stage && sm.isTopLevelRoot()) sm.stage.colorCorrection = value; } /** * @private * Several properties are proxied to controlBarGroup. However, when controlBarGroup * is not around, we need to store values set on SkinnableContainer. This object * stores those values. If controlBarGroup is around, the values are stored * on the controlBarGroup directly. However, we need to know what values * have been set by the developer on the SkinnableContainer (versus set on * the controlBarGroup or defaults of the controlBarGroup) as those are values * we want to carry around if the controlBarGroup changes (via a new skin). * In order to store this info effeciently, controlBarGroupProperties becomes * a uint to store a series of BitFlags. These bits represent whether a * property has been explicitely set on this SkinnableContainer. When the * controlBarGroup is not around, controlBarGroupProperties is a typeless * object to store these proxied properties. When controlBarGroup is around, * controlBarGroupProperties stores booleans as to whether these properties * have been explicitely set or not. */ private var controlBarGroupProperties:Object = { visible: true }; //---------------------------------- // controlBarGroup //---------------------------------- [SkinPart(required=""false"")] /** * The skin part that defines the appearance of the * control bar area of the container. * By default, the ApplicationSkin class defines the control bar area to appear at the top * of the content area of the Application container with a grey background. * * @see spark.skins.spark.ApplicationSkin * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public var controlBarGroup:Group; //---------------------------------- // controlBarContent //---------------------------------- [ArrayElementType(""mx.core.IVisualElement"")] /** * The set of components to include in the control bar area of the * Application container. * The location and appearance of the control bar area of the Application container * is determined by the spark.skins.spark.ApplicationSkin class. * By default, the ApplicationSkin class defines the control bar area to appear at the top * of the content area of the Application container with a grey background. * Create a custom skin to change the default appearance of the control bar. * * @default null * * @see spark.skins.spark.ApplicationSkin * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get controlBarContent():Array { if (controlBarGroup) return controlBarGroup.getMXMLContent(); else return controlBarGroupProperties.controlBarContent; } /** * @private */ public function set controlBarContent(value:Array):void { if (controlBarGroup) { controlBarGroup.mxmlContent = value; controlBarGroupProperties = BitFlagUtil.update(controlBarGroupProperties as uint, CONTROLBAR_PROPERTY_FLAG, value != null); } else controlBarGroupProperties.controlBarContent = value; invalidateSkinState(); } //---------------------------------- // controlBarLayout //---------------------------------- /** * Defines the layout of the control bar area of the container. * * @default HorizontalLayout * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get controlBarLayout():LayoutBase { return (controlBarGroup) ? controlBarGroup.layout : controlBarGroupProperties.layout; } public function set controlBarLayout(value:LayoutBase):void { if (controlBarGroup) { controlBarGroup.layout = value; controlBarGroupProperties = BitFlagUtil.update(controlBarGroupProperties as uint, LAYOUT_PROPERTY_FLAG, true); } else controlBarGroupProperties.layout = value; } //---------------------------------- // controlBarVisible //---------------------------------- /** * If true, the control bar is visible. * The flag has no affect if there is no value set for * the controlBarContent property. * *

    Note: The Application container does not monitor the * controlBarGroup property. * If other code makes it invisible, the Application container might * not update correctly.

    * * @default true * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get controlBarVisible():Boolean { return (controlBarGroup) ? controlBarGroup.visible : controlBarGroupProperties.visible; } public function set controlBarVisible(value:Boolean):void { if (controlBarGroup) { controlBarGroup.visible = value; controlBarGroupProperties = BitFlagUtil.update(controlBarGroupProperties as uint, VISIBLE_PROPERTY_FLAG, value); } else controlBarGroupProperties.visible = value; invalidateSkinState(); if (skin) skin.invalidateSize(); } //-------------------------------------------------------------------------- // // Compile-time pseudo-properties // //-------------------------------------------------------------------------- // These declarations correspond to the MXML-compile-time attributes // allowed on the tag. These attributes affect the MXML // compiler, but they aren't actually used in the runtime framework. // The declarations appear here in order to provide metadata about these // attributes for Flash Builder. //---------------------------------- // frameRate //---------------------------------- [Inspectable(defaultValue=""24"")] /** * Specifies the frame rate of the application. * *

    Note: This property cannot be set by ActionScript code; it must be set in MXML code.

    * * @default 24 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public var frameRate:Number; //---------------------------------- // pageTitle //---------------------------------- /** * Specifies a string that appears in the title bar of the browser. * This property provides the same functionality as the * HTML <title> tag. * *

    Note: This property cannot be set by ActionScript code; it must be set in MXML code. * The value set in MXML code is designed to be used by a tool to update the HTML templates * provided with the SDK.

    * * @default """" * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public var pageTitle:String; //---------------------------------- // preloader //---------------------------------- [Inspectable(defaultValue=""mx.preloaders.DownloadProgressBar"")] /** * The application container supports an application preloader that * uses a download progress bar to show the download and initialization progress * of an application SWF file. * By default, the application preloader is enabled. * The preloader tracks how many bytes have been downloaded and continually * updates the progress bar. * *

    Use this property to specify the path of a * component that defines a custom progress indicator. * To create a custom progress indicator, you typically create a subclass of the * SparkDownloadProgressBar or DownloadProgressBar class, or create a subclass of * the flash.display.Sprite class that implements the * mx.preloaders.IPreloaderDisplay interface.

    * *

    Note: This property cannot be set by ActionScript code; it must be set in MXML code.

    * * @see mx.preloaders.SparkDownloadProgressBar * @see mx.preloaders.DownloadProgressBar * @see flash.display.Sprite * @see mx.preloaders.IPreloaderDisplay * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public var preloader:Object; //---------------------------------- // preloaderChromeColor //---------------------------------- [Inspectable(defaultValue=""0xCCCCCC"", format=""Color"")] /** * Specifies the chrome color used by the default preloader component. This property * has the same effect as the chromeColor style used by Spark skins. * Typically this property should be set to the same value as the * Application container's chromeColor style property. * *

    Note: This property cannot be set by ActionScript code; it must be set in MXML code.

    * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ /* This property is not directly read by the download progress bar (preloader) * component. It is here so that it gets picked up by the compiler and included * in the info() structure for the generated system manager. The download progress bar * grabs the value directly from the info() structure. */ public var preloaderChromeColor:uint; //---------------------------------- // scriptRecursionLimit //---------------------------------- [Inspectable(defaultValue=""1000"")] /** * Specifies the maximum depth of Flash Player or AIR * call stack before the player stops. * This is essentially the stack overflow limit. * *

    Note: This property cannot be set by ActionScript code; it must be set in MXML code.

    * * @default 1000 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public var scriptRecursionLimit:int; //---------------------------------- // scriptTimeLimit //---------------------------------- [Inspectable(defaultValue=""60"")] /** * Specifies the maximum duration, in seconds, that an ActionScript * event handler can execute before Flash Player or AIR assumes * that it is hung, and aborts it. * The maximum allowable value that you can set is 60 seconds. * * @default 60 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public var scriptTimeLimit:Number; //---------------------------------- // splashScreenImage //---------------------------------- /** * The image class for the SplashScreen preloader. * Typically you set this property to either an embedded resource * or the name of a SplashScreenImage class defined in a separate MXML file. * Example of setting splashScreenImage to an embedded image: * *
    splashScreenImage=""@Embed('Default.png')""
    * *

    Note: The property has effect only when the preloader * property is set to spark.preloaders.SplashScreen. * The spark.preloaders.SplashScreen class is the default preloader for Mobile Flex applications. * This property cannot be set by ActionScript code; it must be set in MXML code.

    * *

    Note: You must add the frameworks\\libs\\mobile\\mobilecomponents.swc to the * library path of the application to support the splash screen in a desktop application.

    * * @see spark.preloaders.SplashScreen * @see #splashScreenScaleMode * @see #splashScreenMinimumDisplayTime * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get splashScreenImage():Class { // When set through mxml, the compiler uses the value in the generated loader class. return systemManager.info()[""splashScreenImage""]; } /** * @private */ public function set splashScreenImage(value:Class):void { systemManager.info()[""splashScreenImage""] = value; } //---------------------------------- // splashScreenScaleMode //---------------------------------- [Inspectable(enumeration=""none,letterbox,stretch,zoom"", defaultValue=""none"")] /** * The splash screen image scale mode: * *
      *
    • A value of none implies that the image size is set * to match its intrinsic size.
    • * *
    • A value of stretch sets the width and the height of the image to the * stage width and height, possibly changing the content aspect ratio.
    • * *
    • A value of letterbox sets the width and height of the image * as close to the stage width and height as possible while maintaining aspect ratio. * The image is stretched to a maximum of the stage bounds, * with spacing added inside the stage to maintain the aspect ratio if necessary.
    • * *
    • A value of zoom is similar to letterbox, except * that zoom stretches the image past the bounds of the stage, * to remove the spacing required to maintain aspect ratio. * This setting has the effect of using the entire bounds of the stage, but also * possibly cropping some of the image.
    • *
    * *

    The portion of the stage that is not covered by the image shows * in the Application container's backgroundColor.

    * *

    Note: The property has effect only when the splashScreenImage property * is set and the preloader property is set to spark.preloaders.SplashScreen. * The spark.preloaders.SplashScreen class is the default preloader for Mobile Flex applications. * This property cannot be set by ActionScript code; it must be set in MXML code.

    * *

    Note: You must add the frameworks\\libs\\mobile\\mobilecomponents.swc to the * library path of the application to support the splash screen in a desktop application.

    * * @default ""none"" * @see #splashScreenImage * @see #splashScreenMinimumDisplayTime * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public var splashScreenScaleMode:String; //---------------------------------- // splashScreenMinimumDisplayTime //---------------------------------- /** * Minimum amount of time, in milliseconds, to show the splash screen image. * Specify the splash screen image by using the splashScreenImage property. * *

    Note: The property has effect only when the splashScreenImage property * is set and the preloader property is set to spark.preloaders.SplashScreen. * The spark.preloaders.SplashScreen class is the default preloader for Mobile Flex applications. * This property cannot be set by ActionScript code; it must be set in MXML code.

    * *

    Note: You must add the frameworks\\libs\\mobile\\mobilecomponents.swc to the * library path of the application to support the splash screen in a desktop application.

    * * @default 1000 * * @see #splashScreenImage * @see #splashScreenScaleMode * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public var splashScreenMinimumDisplayTime:Number; //---------------------------------- // applicationDPI //---------------------------------- /** * Storage for the applicationDPI property. * * @private */ private var _applicationDPI:Number = NaN; [Inspectable(category=""General"", enumeration=""120,160,240,320,480,640"")] /** * The DPI of the application. * * By default, this is the DPI of the device that the application is currently running on. * * When set in MXML, Flex will scale the Application to match its DPI to the * runtimeDPI. * * This property cannot be set by ActionScript code; it must be set in MXML code. * * @see #runtimeDPI * @see mx.core.DPIClassification * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get applicationDPI():Number { if (isNaN(_applicationDPI)) { var value:String = systemManager.info()[""applicationDPI""]; _applicationDPI = value ? Number(value) : runtimeDPI; } return _applicationDPI; } /** * @private */ public function set applicationDPI(value:Number):void { // Can't change at run-time so do nothing here. // The compiler will propagate the MXML value to the // systemManager's info object. } //---------------------------------- // runtimeDPI //---------------------------------- /** * The DPI of the device the application is currently running on. * * Flex rounds the value to one of the DPIClassification choices. * * @see #applicationDPI * @see mx.core.DPIClassification * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get runtimeDPI():Number { return DensityUtil.getRuntimeDPI(); } //---------------------------------- // runtimeDPIProvider //---------------------------------- /** * A class that extends RuntimeDPIProvider and overrides the default Flex * calculations for runtimeDPI. * *

    Flex's default mappings are: * * * * * * * *
    160 DPI<140 DPI
    160 DPI>=140 DPI and <=200 DPI
    240 DPI>=200 DPI and <=280 DPI
    320 DPI>=280 DPI and <=400 DPI
    480 DPI>=400 DPI and <=560 DPI
    640 DPI>=640 DPI
    *

    * * This property cannot be set by ActionScript code; it must be set in MXML code. * * @default spark.components.RuntimeDPIProvider * * @see #applicationDPI * @see #runtimeDPI * @see mx.core.DPIClassification * @see mx.core.RuntimeDPIProvider * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get runtimeDPIProvider():Class { return systemManager.info()[""runtimeDPIProvider""]; } /** * @private */ public function set runtimeDPIProvider(value:Class):void { // Can't change at run-time so do nothing here. // The compiler will propagate the MXML value to the // systemManager's info object. } //---------------------------------- // usePreloader //---------------------------------- [Inspectable(defaultValue=""true"")] /** * If true, specifies to display the application preloader. * *

    Note: This property cannot be set by ActionScript code; it must be set in MXML code.

    * * @default true * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public var usePreloader:Boolean; //-------------------------------------------------------------------------- // // Overridden properties (to block metadata from superclasses) // //-------------------------------------------------------------------------- //---------------------------------- // id //---------------------------------- [Inspectable(environment=""none"")] /** * @private */ override public function get id():String { if (!super.id && this == FlexGlobals.topLevelApplication && ExternalInterface.available) { return ExternalInterface.objectID; } return super.id; } //---------------------------------- // percentHeight //---------------------------------- /** * @private */ override public function set percentHeight(value:Number):void { if (value != super.percentHeight) { super.percentHeight = value; percentBoundsChanged = true; invalidateProperties(); } } //---------------------------------- // percentWidth //---------------------------------- /** * @private */ override public function set percentWidth(value:Number):void { if (value != super.percentWidth) { super.percentWidth = value; percentBoundsChanged = true; invalidateProperties(); } } //---------------------------------- // tabIndex //---------------------------------- [Inspectable(environment=""none"")] /** * @private */ override public function set tabIndex(value:int):void { } //---------------------------------- // toolTip //---------------------------------- [Inspectable(environment=""none"")] /** * @private */ override public function set toolTip(value:String):void { } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // aspectRatio //---------------------------------- /** * Returns the aspect ratio of the top level stage based on its width * and height. If the width of the stage is greater than the height, * the stage is considered to be in ""landscape"" orientation. Otherwise, * portrait is returned. * * @return This method will return ""landscape"" if the application is * in a landsacpe orientation, and ""portrait"" otherwise. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get aspectRatio():String { var actualHeight:Number = height; // If the application has resized itself in response to the // softKeyboard becoming visible, we need to compare against // the height without the keyboard active if (isSoftKeyboardActive && softKeyboardBehavior == ""none"" && resizeForSoftKeyboard) actualHeight += softKeyboardRect.height; return width > actualHeight ? ""landscape"" : ""portrait""; } //---------------------------------- // parameters //---------------------------------- /** * @private * Storage for the parameters property. * This variable is set in the initialize() method of SystemManager. */ mx_internal var _parameters:Object; /** * An Object containing name-value * pairs representing the parameters provided to this Application. * *

    You can use a for-in loop to extract all the names and values * from the parameters Object.

    * *

    There are two sources of parameters: the query string of the * Application's URL, and the value of the FlashVars HTML parameter * (this affects only the main Application).

    * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get parameters():Object { return _parameters; } //---------------------------------- // resizeForSoftKeyboard //---------------------------------- private var _resizeForSoftKeyboard:Boolean = false; /** * Some devices do not support a hardware keyboard. * Instead, these devices use a keyboard that opens on * the screen when necessary. * The screen keyboard, also called a soft or virtual keyboard, * closes after the user enters the information, or when the user cancels the operation. * A value of true means the application * is resized when the soft keyboard is open or * closed. * *

    To enable application resizing, you must also set the * <softKeyboardBehavior> attribute in the * application's xml descriptor file to none.

    * * @default false * * @langversion 3.0 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function get resizeForSoftKeyboard():Boolean { return _resizeForSoftKeyboard; } public function set resizeForSoftKeyboard(value:Boolean):void { if (_resizeForSoftKeyboard != value) { _resizeForSoftKeyboard = value; } } //---------------------------------- // url //---------------------------------- /** * @private * Storage for the url property. * This variable is set in the initialize(). */ mx_internal var _url:String; /** * The URL from which this Application's SWF file was loaded. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get url():String { return _url; } //---------------------------------- // viewSourceURL //---------------------------------- /** * @private * Storage for viewSourceURL property. */ private var _viewSourceURL:String; /** * URL where the application's source can be viewed. Setting this * property inserts a ""View Source"" menu item into the application's * default context menu. Selecting the menu item opens the * viewSourceURL in a new window. * *

    You must set the viewSourceURL property * using MXML, not using ActionScript, as the following example shows:

    * *
         *    <Application viewSourceURL=""http://path/to/source"">
         *      ...
         *    </Application>
    * * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get viewSourceURL():String { return _viewSourceURL; } /** * @private */ public function set viewSourceURL(value:String):void { _viewSourceURL = value; } //-------------------------------------------------------------------------- // // Overridden methods: UIComponent // //-------------------------------------------------------------------------- /** * @private */ override protected function invalidateParentSizeAndDisplayList():void { if (!includeInLayout) return; var p:IInvalidating = parent as IInvalidating; if (!p) { if (parent is ISystemManager) ISystemManager(parent).invalidateParentSizeAndDisplayList(); return; } super.invalidateParentSizeAndDisplayList(); } /** * @private */ override public function initialize():void { // trace(""FxApp initialize FxApp""); var sm:ISystemManager = systemManager; // add listener if one is already attached if (hasEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR)) systemManager.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorRedispatcher); // Determine if we are running on an iOS device isIOS = Platform.isIOS; // To prevent a flicker described in SDK-30133, a flex application listens // for orientationChanging events dispatched by iOS AIR applications. // In the handler, the stage's width and height are swapped, and a validation // pass is forced to allow the application to resize and re-layout itself before the // orientation change animation occurs if (isIOS && sm && sm.stage && sm.isTopLevelRoot()) { sm.stage.addEventListener(""orientationChanging"", stage_orientationChangingHandler); sm.stage.addEventListener(""orientationChange"", stage_orientationChange); sm.stage.addEventListener(FullScreenEvent.FULL_SCREEN, stage_fullScreenHandler) ; // if full screen app, clear status bar height if ( sm.stage.displayState == StageDisplayState.FULL_SCREEN || sm.stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE ) { setStyle(""osStatusBarHeight"", 0); } } _url = LoaderUtil.normalizeURL(sm.loaderInfo); _parameters = sm.loaderInfo.parameters; initManagers(sm); // Setup the default context menu here. This allows the application // developer to override it in the initialize event, if desired. initContextMenu(); super.initialize(); // Stick a timer here so that we will execute script every 1.5s // no matter what. // This is strictly for the debugger to be able to halt. // Note: isDebugger is true only with a Debugger Player. if (sm.isTopLevel() && Capabilities.isDebugger == true) setInterval(debugTickler, 1500); } /** * @private * This is the event handler for the stage's orientationChanging event. It * cancels the orientation animation and manually swaps the width and height * of the application to allow the application to validate itself before * the orientation change occurs. The orientaitonChanging is only listened * for on iOS devices. */ private function stage_orientationChangingHandler(event:Event):void { var sm:ISystemManager = systemManager; // Manually update orientation width and height if the application's explicit // sizes aren't set. If they are, we assume the application will handle // orientation on their own. // SDK-30625: check stage for null since the Application may not be on-screen yet // if orientation changes during start-up. if (!stage || !isNaN(explicitWidth) || !isNaN(explicitHeight)) return; if (!cachedDimensions) cachedDimensions = new Dictionary(); // remember the current dimensions previousWidth = width; previousHeight = height; var key:String = width + "":"" + height; // On some platforms (e.g. iOS and Playbook) if the soft keyboard is up // it deactivates before orientation change and reactivates after it; // the value of isSoftKeyboardActive thus changes during orientation change. // We are remembering the initial value of isSoftKeyboardActivate in this // situation for use in avoiding excessive resizing during the orientation change. keyboardActiveInOrientationChange = isSoftKeyboardActive; // if we're rotating 180 degrees don't do any screen resizing var beforeOrientation:String = event[""beforeOrientation""]; var afterOrientation:String = event[""afterOrientation""]; if ((beforeOrientation == ""default"" && afterOrientation == ""upsideDown"") || (beforeOrientation == ""upsideDown"" && afterOrientation == ""default"") || (beforeOrientation == ""rotatedLeft"" && afterOrientation == ""rotatedRight"") || (beforeOrientation == ""rotatedRight"" && afterOrientation == ""rotatedLeft"")) return; var newWidth:Number; var newHeight:Number; // if we have a cached value, use it if (cachedDimensions[key]) { newWidth = cachedDimensions[key].width; newHeight = cachedDimensions[key].height; } else // no cached value; just swap the numbers for now { // use stageHeight as the new width if you can get it newWidth = stage ? stage.stageHeight / scaleFactor : height; newHeight = width; } setActualSize(newWidth, newHeight); // Indicate that the width and height have changed because of orientation explicitSizingForOrientation = true; // Force a validation validateNow(); } /** * @private * Handler for the stage orientation change event. At this point, we need * to undo the explicit width and height that was set when the application is * reoriented on an iOS device. See stage_orientationChangingHandler for more * information. */ private function stage_orientationChange(event:Event):void { // SDK-30625: check stage for null since the Application may not be on-screen yet // if orientation changes during start-up. if (!stage || !explicitSizingForOrientation) return; // update cache if keyboard was not previously active if (!keyboardActiveInOrientationChange) { updateScreenSizeCache(stage.stageWidth / scaleFactor, stage.stageHeight / scaleFactor); } explicitSizingForOrientation = false; } /** @private previous value of osStatusBarHeight on iOS when switch to full screen * */ protected var savedOsStatusBarHeight: Number = 0; /** * @private * Handler to temporarily remove osStatusBarHeight is stage is set to full screen * only of iOS devices */ protected function stage_fullScreenHandler(event: FullScreenEvent): void { if (stage.displayState == StageDisplayState.FULL_SCREEN || stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE) { var statusBarHeight : Number = getStyle(""osStatusBarHeight""); if (statusBarHeight > 0) { savedOsStatusBarHeight = statusBarHeight; setStyle(""osStatusBarHeight"", 0) ; } } else { if (savedOsStatusBarHeight > 0) { setStyle(""osStatusBarHeight"", savedOsStatusBarHeight); savedOsStatusBarHeight = 0; } } } /** * @private * Update the screen size cache with the new values. The previous values are * pulled from the values currently set in the cache. * Note that if the old and new width/height values are unchanged no values are * cached under the assumption that this was a 180 degree rotation. * */ private function updateScreenSizeCache(newWidth:Number, newHeight:Number):void { // same dimensions, probably 180 degree rotation; don't cache if (previousWidth == newWidth && previousHeight == newHeight) return; var key:String = previousWidth + "":"" + previousHeight; if (cachedDimensions[key]) { // update the cached values if they are different cachedDimensions[key].width = newWidth; cachedDimensions[key].height = newHeight; } else { var orientationChangeKey:String = previousWidth + "":"" + previousHeight; var reverseOrientationChangeKey:String = newWidth + "":"" + newHeight; // cache values both ways, i.e. old -> new and new -> old cachedDimensions[orientationChangeKey] = { width:newWidth, height:newHeight }; cachedDimensions[reverseOrientationChangeKey] = { width:previousWidth, height:previousHeight }; } } /** * @private */ override protected function createChildren():void { super.createChildren(); // Only listen for softKeyboard events // if the runtime supports a soft keyboard if (softKeyboardBehavior != """") { addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE, softKeyboardActivateHandler, true, EventPriority.DEFAULT, true); addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE, softKeyboardDeactivateHandler, true, EventPriority.DEFAULT, true); // Listen for the deactivate event so we can close the softKeyboard var nativeApp:Object = FlexGlobals.topLevelApplication. systemManager.getDefinitionByName(""flash.desktop.NativeApplication""); if (nativeApp && nativeApp[""nativeApplication""]) EventDispatcher(nativeApp[""nativeApplication""]). addEventListener(Event.DEACTIVATE, nativeApplication_deactivateHandler); } } /** * @private */ override protected function commitProperties():void { super.commitProperties(); resizeWidth = isNaN(explicitWidth); resizeHeight = isNaN(explicitHeight); if (resizeWidth || resizeHeight) { resizeHandler(new Event(Event.RESIZE)); if (!resizeHandlerAdded) { // weak reference systemManager.addEventListener(Event.RESIZE, resizeHandler, false, 0, true); resizeHandlerAdded = true; } } else { if (resizeHandlerAdded) { systemManager.removeEventListener(Event.RESIZE, resizeHandler); resizeHandlerAdded = false; } } if (percentBoundsChanged) { updateBounds(); percentBoundsChanged = false; } } /** * @private */ override protected function resourcesChanged():void { super.resourcesChanged(); // ""View Source"" on the context menu if (viewSourceCMI) { viewSourceCMI.caption = resourceManager.getString(""components"", ""viewSource""); } } /** * @private */ override protected function partAdded(partName:String, instance:Object):void { super.partAdded(partName, instance); if (instance == controlBarGroup) { // copy proxied values from controlBarGroupProperties (if set) to contentGroup var newControlBarGroupProperties:uint = 0; if (controlBarGroupProperties.controlBarContent !== undefined) { controlBarGroup.mxmlContent = controlBarGroupProperties.controlBarContent; newControlBarGroupProperties = BitFlagUtil.update(newControlBarGroupProperties, CONTROLBAR_PROPERTY_FLAG, true); } if (controlBarGroupProperties.layout !== undefined) { controlBarGroup.layout = controlBarGroupProperties.layout; newControlBarGroupProperties = BitFlagUtil.update(newControlBarGroupProperties, LAYOUT_PROPERTY_FLAG, true); } if (controlBarGroupProperties.visible !== undefined) { controlBarGroup.visible = controlBarGroupProperties.visible; newControlBarGroupProperties = BitFlagUtil.update(newControlBarGroupProperties, VISIBLE_PROPERTY_FLAG, true); } controlBarGroupProperties = newControlBarGroupProperties; } } /** * @private * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function partRemoved(partName:String, instance:Object):void { super.partRemoved(partName, instance); if (instance == controlBarGroup) { // copy proxied values from contentGroup (if explicitely set) to contentGroupProperties var newControlBarGroupProperties:Object = {}; if (BitFlagUtil.isSet(controlBarGroupProperties as uint, CONTROLBAR_PROPERTY_FLAG)) newControlBarGroupProperties.controlBarContent = controlBarGroup.getMXMLContent(); if (BitFlagUtil.isSet(controlBarGroupProperties as uint, LAYOUT_PROPERTY_FLAG)) newControlBarGroupProperties.layout = controlBarGroup.layout; if (BitFlagUtil.isSet(controlBarGroupProperties as uint, VISIBLE_PROPERTY_FLAG)) newControlBarGroupProperties.visible = controlBarGroup.visible; controlBarGroupProperties = newControlBarGroupProperties; controlBarGroup.mxmlContent = null; controlBarGroup.layout = null; } } /** * @private * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function getCurrentSkinState():String { var state:String = enabled ? ""normal"" : ""disabled""; if (controlBarGroup) { if (BitFlagUtil.isSet(controlBarGroupProperties as uint, CONTROLBAR_PROPERTY_FLAG) && BitFlagUtil.isSet(controlBarGroupProperties as uint, VISIBLE_PROPERTY_FLAG)) state += ""WithControlBar""; } else { if (controlBarGroupProperties.controlBarContent && controlBarGroupProperties.visible) state += ""WithControlBar""; } return state; } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); if (!styleProp || styleProp == ""styleName"" || styleProp == ""interactionMode"") { // Turn off tooltip support for all mobile applications ToolTipManager.enabled = getStyle(""interactionMode"") != InteractionMode.TOUCH; } } //---------------------------------- // unscaledHeight //---------------------------------- /** * @private */ override mx_internal function setUnscaledHeight(value:Number):void { // we invalidate so we can properly add/remove the resize // event handler (SDK-12664) invalidateProperties(); super.setUnscaledHeight(value); } //---------------------------------- // unscaledWidth //---------------------------------- /** * @private */ override mx_internal function setUnscaledWidth(value:Number):void { // we invalidate so we can properly add/remove the resize // event handler (SDK-12664) invalidateProperties(); super.setUnscaledWidth(value); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * This is here so we get the this pointer set to Application. */ private function debugTickler():void { // We need some bytes of code in order to have a place to break. var i:int = 0; } /** * @private */ private function initManagers(sm:ISystemManager):void { if (sm.isTopLevel()) { focusManager = new FocusManager(this); var awm:IActiveWindowManager = IActiveWindowManager(sm.getImplementation(""mx.managers::IActiveWindowManager"")); if (awm) awm.activate(this); else focusManager.activate(); } } /** * @private * Disable all the built-in items except ""Print..."". */ private function initContextMenu():void { // context menu already set // nothing to init if (flexContextMenu != null) { // make sure we set it back on systemManager b/c it may have been overridden by now if (systemManager is InteractiveObject) InteractiveObject(systemManager).contextMenu = contextMenu as ContextMenu; return; } var defaultMenu:ContextMenu = new ContextMenu(); defaultMenu.hideBuiltInItems(); defaultMenu.builtInItems.print = true; if (_viewSourceURL) { // don't worry! this gets updated in resourcesChanged() const caption:String = resourceManager.getString(""components"", ""viewSource""); viewSourceCMI = new ContextMenuItem(caption, true); viewSourceCMI.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuItemSelectHandler); // Append custom option, validating customItems first as in the // mobile context this is null. if (defaultMenu.customItems) defaultMenu.customItems.push(viewSourceCMI); } contextMenu = defaultMenu; if (systemManager is InteractiveObject) InteractiveObject(systemManager).contextMenu = defaultMenu; } /** * @private * Check to see if we're able to synchronize our size with the stage * immediately rather than deferring (dependent on WATSON 2200950). */ private function initResizeBehavior():void { var version:Array = Capabilities.version.split(' ')[1].split(','); synchronousResize = (parseFloat(version[0]) > 10 || (parseFloat(version[0]) == 10 && parseFloat(version[1]) >= 1)) && !Platform.isAir; } /** * @private * Called if resizeForSoftKeyboard is true and the softKeyboard * has been activated. */ private function softKeyboardActivateHandler(event:SoftKeyboardEvent):void { // Add a listener for the softKeyboard deactivate event to the event target event.target.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE, softKeyboardDeactivateHandler); if (this === FlexGlobals.topLevelApplication) { if (softKeyboardTarget && softKeyboardTarget != event.target) clearSoftKeyboardTarget(); softKeyboardTarget = event.target; // If the display object that activates the softkeyboard is removed without // losing focus, the runtime may not dispatch a deactivate event. So the // framework adds a REMOVE_FROM_STAGE event listener to the target and manually // clears the focus. softKeyboardTarget.addEventListener(Event.REMOVED_FROM_STAGE, softKeyboardTarget_removeFromStageHandler, false, EventPriority.DEFAULT, true); // On iOS, if the softKeyboard target is removed from the stage as a result // of a user input with another focusable component, the application will not // receive a SOFT_KEYBOARD_DEACTIVATE event, only the target will. if (isIOS) { softKeyboardTarget.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE, softKeyboardDeactivateHandler, false, EventPriority.DEFAULT, true); } // Get the keyboard size var keyboardRect:Rectangle = softKeyboardRect; if (keyboardRect.height > 0) isSoftKeyboardActive = true; if (softKeyboardBehavior == ""none"" && resizeForSoftKeyboard) { var appHeight:Number = (stage.stageHeight - keyboardRect.height) / scaleFactor; var appWidth:Number = stage.stageWidth / scaleFactor; if (appHeight != height || appWidth != width) { setActualSize(appWidth, appHeight); validateNow(); // Validate so that other listeners like Scroller get the updated dimensions } // update the screen size cache if (keyboardActiveInOrientationChange) { keyboardActiveInOrientationChange = false; updateScreenSizeCache(appWidth, appHeight); } } } } /** * @private * Called if resizeForSoftKeyboard is true and the softKeyboard * has been deactivated. */ private function softKeyboardDeactivateHandler(event:SoftKeyboardEvent):void { if (this === FlexGlobals.topLevelApplication && isSoftKeyboardActive) { if (softKeyboardTarget) clearSoftKeyboardTarget(); isSoftKeyboardActive = false; if (softKeyboardBehavior == ""none"" && resizeForSoftKeyboard && !keyboardActiveInOrientationChange) { // Restore the original values setActualSize(stage.stageWidth / scaleFactor, stage.stageHeight / scaleFactor); validateNow(); // Validate so that other listeners like Scroller get the updated dimensions } } } /** * @private */ private function nativeApplication_deactivateHandler(event:Event):void { // Close the softKeyboard if we deactivate the application. This works // around an iOS bug where the SoftKeyboard.DEACTIVATE event isn't // dispatched when the application is deactivated. if (isSoftKeyboardActive) { stage.focus = null; softKeyboardDeactivateHandler(null); } } /** * @private * Called when a softKeyboard activation target is removed from the * stage. If the target has stage focus, then the focus is set to null. * This will cause a SOFT_KEYBOARD_DEACTIVATE event to be dispatched. */ private function softKeyboardTarget_removeFromStageHandler(event:Event):void { if (stage.focus == softKeyboardTarget) stage.focus = null; // clearSoftKeyboardTarget() is called in response to the SOFT_KEYBOARD_DEACTIVATE // event and will clear the removeFromStage listener and softKeyboardDeactivate // events from the target. } /** * @private * This method clears the cached softKeyboard target and removes the * removeFromStage handler that is added in the softKeyboardActivateHandler * method. */ private function clearSoftKeyboardTarget():void { if (softKeyboardTarget) { if (isIOS) { softKeyboardTarget.removeEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE, softKeyboardDeactivateHandler); } softKeyboardTarget.removeEventListener(Event.REMOVED_FROM_STAGE, softKeyboardTarget_removeFromStageHandler); softKeyboardTarget = null; } } /** * Helper function to get the AIR application descriptor attribute called ""softKeyboardBehavior"". */ mx_internal static function get softKeyboardBehavior():String { if (_softKeyboardBehavior != null) { return _softKeyboardBehavior; } else { // Since we might not be running on AIR, need to get the class by name. // Also, make sure to cache the value so we only run this once var nativeApp:Object = FlexGlobals.topLevelApplication.systemManager.getDefinitionByName(""flash.desktop.NativeApplication""); if (nativeApp) { try { var appXML:XML = XML(nativeApp[""nativeApplication""][""applicationDescriptor""]); var ns:Namespace = appXML.namespace(); _softKeyboardBehavior = String(appXML..ns::softKeyboardBehavior); } catch (e:Error) { // TODO (aharui): Marshall this someday? _softKeyboardBehavior = """"; } } else { _softKeyboardBehavior = """"; } return _softKeyboardBehavior; } } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private * Triggered by a resize event of the stage. * Sets the new width and height. * After the SystemManager performs its function, * it is only necessary to notify the children of the change. */ private function resizeHandler(event:Event):void { // don't run while keyboard is up and orientation is changing if (keyboardActiveInOrientationChange) return; // If we're already due to update our bounds on the next // commitProperties pass, avoid the redundancy. if (!percentBoundsChanged) { updateBounds(); // Update immediately when stage resizes so that we may appear // in synch with the stage rather than visually ""catching up"". if (synchronousResize) UIComponentGlobals.layoutManager.validateNow(); } } /** * @private * Called when the ""View Source"" item in the application's context menu is * selected. */ protected function menuItemSelectHandler(event:Event):void { navigateToURL(new URLRequest(_viewSourceURL), ""_blank""); } /** * @private * Sets the new width and height after the Stage has resized * or when percentHeight or percentWidth has changed. */ private function updateBounds():void { // When user has not specified any width/height, // application assumes the size of the stage. // If developer has specified width/height, // the application will not resize. // If developer has specified percent width/height, // application will resize to the required value // based on the current SystemManager's width/height. // If developer has specified min/max values, // then application will not resize beyond those values. // ignore updateBounds while orientation is changing if (keyboardActiveInOrientationChange) return; var w:Number; var h:Number if (resizeWidth) { if (isNaN(percentWidth)) { w = DisplayObject(systemManager).width; } else { super.percentWidth = Math.max(percentWidth, 0); super.percentWidth = Math.min(percentWidth, 100); w = percentWidth*DisplayObject(systemManager).width/100; } if (!isNaN(explicitMaxWidth)) w = Math.min(w, explicitMaxWidth); if (!isNaN(explicitMinWidth)) w = Math.max(w, explicitMinWidth); } else { w = width; } if (resizeHeight) { if (isNaN(percentHeight)) { h = DisplayObject(systemManager).height; } else { super.percentHeight = Math.max(percentHeight, 0); super.percentHeight = Math.min(percentHeight, 100); h = percentHeight*DisplayObject(systemManager).height/100; } if (!isNaN(explicitMaxHeight)) h = Math.min(h, explicitMaxHeight); if (!isNaN(explicitMinHeight)) h = Math.max(h, explicitMinHeight); } else { h = height; } if (w != width || h != height) { invalidateProperties(); invalidateSize(); } setActualSize(w, h); invalidateDisplayList(); } /** * @private */ override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { // this can get called before we know our systemManager. Hook it up later in initialize() if (type == UncaughtErrorEvent.UNCAUGHT_ERROR && systemManager) systemManager.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorRedispatcher); super.addEventListener(type, listener, useCapture, priority, useWeakReference) } /** * @private */ override public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { super.removeEventListener(type, listener, useCapture); if (type == UncaughtErrorEvent.UNCAUGHT_ERROR && systemManager) systemManager.loaderInfo.uncaughtErrorEvents.removeEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorRedispatcher); } private function uncaughtErrorRedispatcher(event:Event):void { if (!dispatchEvent(event)) event.preventDefault(); } mx_internal var _softKeyboardRect:Rectangle; mx_internal function get softKeyboardRect():Rectangle { if (_softKeyboardRect == null) return stage.softKeyboardRect; return _softKeyboardRect; } } } ",16176,True,3078.128552296638,median "package com.ankamagames.dofus.logic.game.roleplay.frames { import com.ankamagames.atouin.Atouin; import com.ankamagames.atouin.AtouinConstants; import com.ankamagames.atouin.data.map.CellData; import com.ankamagames.atouin.enums.PlacementStrataEnums; import com.ankamagames.atouin.managers.FrustumManager; import com.ankamagames.atouin.managers.InteractiveCellManager; import com.ankamagames.atouin.managers.MapDisplayManager; import com.ankamagames.atouin.managers.SelectionManager; import com.ankamagames.atouin.messages.AdjacentMapClickMessage; import com.ankamagames.atouin.messages.AdjacentMapOutMessage; import com.ankamagames.atouin.messages.AdjacentMapOverMessage; import com.ankamagames.atouin.messages.CellClickMessage; import com.ankamagames.atouin.renderers.ZoneDARenderer; import com.ankamagames.atouin.types.FrustumShape; import com.ankamagames.atouin.types.GraphicCell; import com.ankamagames.atouin.types.Selection; import com.ankamagames.atouin.utils.CellIdConverter; import com.ankamagames.atouin.utils.DataMapProvider; import com.ankamagames.berilia.components.Label; import com.ankamagames.berilia.components.Texture; import com.ankamagames.berilia.enums.StrataEnum; import com.ankamagames.berilia.factories.MenusFactory; import com.ankamagames.berilia.frames.ShortcutsFrame; import com.ankamagames.berilia.managers.KernelEventsManager; import com.ankamagames.berilia.managers.LinkedCursorSpriteManager; import com.ankamagames.berilia.managers.TooltipManager; import com.ankamagames.berilia.managers.UiModuleManager; import com.ankamagames.berilia.types.LocationEnum; import com.ankamagames.berilia.types.data.LinkedCursorData; import com.ankamagames.berilia.types.data.TextTooltipInfo; import com.ankamagames.berilia.utils.BeriliaHookList; import com.ankamagames.dofus.datacenter.interactives.Interactive; import com.ankamagames.dofus.datacenter.interactives.Sign; import com.ankamagames.dofus.datacenter.jobs.Skill; import com.ankamagames.dofus.datacenter.monsters.Monster; import com.ankamagames.dofus.datacenter.npcs.Npc; import com.ankamagames.dofus.datacenter.npcs.NpcAction; import com.ankamagames.dofus.datacenter.npcs.TaxCollectorFirstname; import com.ankamagames.dofus.datacenter.npcs.TaxCollectorName; import com.ankamagames.dofus.datacenter.world.Area; import com.ankamagames.dofus.datacenter.world.MapPosition; import com.ankamagames.dofus.datacenter.world.SubArea; import com.ankamagames.dofus.internalDatacenter.DataEnum; import com.ankamagames.dofus.internalDatacenter.breach.BreachBranchWrapper; import com.ankamagames.dofus.internalDatacenter.guild.AllianceWrapper; import com.ankamagames.dofus.internalDatacenter.guild.GuildWrapper; import com.ankamagames.dofus.internalDatacenter.house.HouseWrapper; import com.ankamagames.dofus.internalDatacenter.world.WorldPointWrapper; import com.ankamagames.dofus.kernel.Kernel; import com.ankamagames.dofus.kernel.net.ConnectionsHandler; import com.ankamagames.dofus.logic.common.actions.EmptyStackAction; import com.ankamagames.dofus.logic.common.managers.PlayerManager; import com.ankamagames.dofus.logic.game.common.actions.guild.GuildFightJoinRequestAction; import com.ankamagames.dofus.logic.game.common.actions.humanVendor.ExchangeOnHumanVendorRequestAction; import com.ankamagames.dofus.logic.game.common.frames.AllianceFrame; import com.ankamagames.dofus.logic.game.common.frames.BreachFrame; import com.ankamagames.dofus.logic.game.common.frames.SocialFrame; import com.ankamagames.dofus.logic.game.common.managers.PlayedCharacterManager; import com.ankamagames.dofus.logic.game.common.misc.DofusEntities; import com.ankamagames.dofus.logic.game.fight.actions.ShowAllNamesAction; import com.ankamagames.dofus.logic.game.fight.frames.FightPreparationFrame; import com.ankamagames.dofus.logic.game.roleplay.actions.NpcGenericActionRequestAction; import com.ankamagames.dofus.logic.game.roleplay.actions.ShowEntitiesTooltipsAction; import com.ankamagames.dofus.logic.game.roleplay.actions.ShowFightPositionsAction; import com.ankamagames.dofus.logic.game.roleplay.managers.MountAutoTripManager; import com.ankamagames.dofus.logic.game.roleplay.managers.RoleplayManager; import com.ankamagames.dofus.logic.game.roleplay.managers.SkillManager; import com.ankamagames.dofus.logic.game.roleplay.messages.InteractiveElementActivationMessage; import com.ankamagames.dofus.logic.game.roleplay.messages.InteractiveElementMouseOutMessage; import com.ankamagames.dofus.logic.game.roleplay.messages.InteractiveElementMouseOverMessage; import com.ankamagames.dofus.logic.game.roleplay.types.CharacterTooltipInformation; import com.ankamagames.dofus.logic.game.roleplay.types.FightTeam; import com.ankamagames.dofus.logic.game.roleplay.types.GameContextPaddockItemInformations; import com.ankamagames.dofus.logic.game.roleplay.types.MutantTooltipInformation; import com.ankamagames.dofus.logic.game.roleplay.types.PortalTooltipInformation; import com.ankamagames.dofus.logic.game.roleplay.types.PrismTooltipInformation; import com.ankamagames.dofus.logic.game.roleplay.types.RoleplayTeamFightersTooltipInformation; import com.ankamagames.dofus.logic.game.roleplay.types.TaxCollectorTooltipInformation; import com.ankamagames.dofus.misc.lists.ChatHookList; import com.ankamagames.dofus.misc.lists.HookList; import com.ankamagames.dofus.misc.lists.SocialHookList; import com.ankamagames.dofus.network.enums.PlayerLifeStatusEnum; import com.ankamagames.dofus.network.enums.SubEntityBindingPointCategoryEnum; import com.ankamagames.dofus.network.enums.TeamTypeEnum; import com.ankamagames.dofus.network.messages.game.context.fight.GameFightJoinRequestMessage; import com.ankamagames.dofus.network.messages.game.context.roleplay.MapComplementaryInformationsDataMessage; import com.ankamagames.dofus.network.messages.game.context.roleplay.MapFightStartPositionsUpdateMessage; import com.ankamagames.dofus.network.messages.game.context.roleplay.houses.HouseKickIndoorMerchantRequestMessage; import com.ankamagames.dofus.network.messages.game.context.roleplay.party.PartyInvitationRequestMessage; import com.ankamagames.dofus.network.messages.game.inventory.exchanges.ExchangeOnHumanVendorRequestMessage; import com.ankamagames.dofus.network.types.common.PlayerSearchCharacterNameInformation; import com.ankamagames.dofus.network.types.game.context.GameContextActorInformations; import com.ankamagames.dofus.network.types.game.context.GameRolePlayTaxCollectorInformations; import com.ankamagames.dofus.network.types.game.context.TaxCollectorStaticExtendedInformations; import com.ankamagames.dofus.network.types.game.context.fight.FightStartingPositions; import com.ankamagames.dofus.network.types.game.context.fight.FightTeamMemberInformations; import com.ankamagames.dofus.network.types.game.context.fight.FightTeamMemberTaxCollectorInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.AllianceInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GameRolePlayActorInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GameRolePlayCharacterInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GameRolePlayGroupMonsterInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GameRolePlayGroupMonsterWaveInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GameRolePlayMerchantInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GameRolePlayMutantInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GameRolePlayNamedActorInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GameRolePlayNpcInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GameRolePlayPortalInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GameRolePlayPrismInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GameRolePlayTreasureHintInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GroupMonsterStaticInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.GuildInformations; import com.ankamagames.dofus.network.types.game.context.roleplay.MonsterInGroupLightInformations; import com.ankamagames.dofus.network.types.game.interactive.InteractiveElement; import com.ankamagames.dofus.network.types.game.interactive.InteractiveElementSkill; import com.ankamagames.dofus.types.entities.AnimatedCharacter; import com.ankamagames.dofus.types.sequences.AddGfxEntityStep; import com.ankamagames.dofus.uiApi.RoleplayApi; import com.ankamagames.dofus.uiApi.SocialApi; import com.ankamagames.dofus.uiApi.SystemApi; import com.ankamagames.jerakine.data.I18n; import com.ankamagames.jerakine.data.XmlConfig; import com.ankamagames.jerakine.entities.interfaces.IDisplayable; import com.ankamagames.jerakine.entities.interfaces.IEntity; import com.ankamagames.jerakine.entities.interfaces.IInteractive; import com.ankamagames.jerakine.entities.interfaces.IMovable; import com.ankamagames.jerakine.entities.messages.EntityClickMessage; import com.ankamagames.jerakine.entities.messages.EntityMouseOutMessage; import com.ankamagames.jerakine.entities.messages.EntityMouseOverMessage; import com.ankamagames.jerakine.enum.OperatingSystem; import com.ankamagames.jerakine.enum.OptionEnum; import com.ankamagames.jerakine.handlers.messages.mouse.MouseDownMessage; import com.ankamagames.jerakine.handlers.messages.mouse.MouseRightClickMessage; import com.ankamagames.jerakine.handlers.messages.mouse.MouseUpMessage; import com.ankamagames.jerakine.interfaces.IRectangle; import com.ankamagames.jerakine.logger.Log; import com.ankamagames.jerakine.logger.Logger; import com.ankamagames.jerakine.managers.CursorSpriteManager; import com.ankamagames.jerakine.managers.LangManager; import com.ankamagames.jerakine.managers.OptionManager; import com.ankamagames.jerakine.messages.Frame; import com.ankamagames.jerakine.messages.Message; import com.ankamagames.jerakine.messages.events.FramePushedEvent; import com.ankamagames.jerakine.sequencer.SerialSequencer; import com.ankamagames.jerakine.types.Color; import com.ankamagames.jerakine.types.Uri; import com.ankamagames.jerakine.types.enums.DirectionsEnum; import com.ankamagames.jerakine.types.enums.Priority; import com.ankamagames.jerakine.types.positions.MapPoint; import com.ankamagames.jerakine.types.zones.Custom; import com.ankamagames.jerakine.utils.display.Rectangle2; import com.ankamagames.jerakine.utils.display.StageShareManager; import com.ankamagames.jerakine.utils.system.SystemManager; import com.ankamagames.tiphon.display.TiphonSprite; import com.ankamagames.tiphon.events.TiphonEvent; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.ui.Mouse; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; public class RoleplayWorldFrame implements Frame { protected static const _log:Logger = Log.getLogger(getQualifiedClassName(RoleplayWorldFrame)); private static const NO_CURSOR:int = -1; private static const FIGHT_CURSOR:int = 3; private static const NPC_CURSOR:int = 1; private static const DIRECTIONAL_PANEL_ID:int = 316; private static var _entitiesTooltipsFrame:EntitiesTooltipsFrame = new EntitiesTooltipsFrame(); private const _common:String = XmlConfig.getInstance().getEntry(""config.ui.skin""); private var _mouseLabel:Label; private var _mouseTop:Texture; private var _mouseBottom:Texture; private var _mouseRight:Texture; private var _mouseLeft:Texture; private var _mouseTopBlue:Texture; private var _mouseBottomBlue:Texture; private var _mouseRightBlue:Texture; private var _mouseLeftBlue:Texture; private var _texturesReady:Boolean; private var _playerEntity:AnimatedCharacter; private var _playerName:String; private var _allowOnlyCharacterInteraction:Boolean; public var cellClickEnabled:Boolean; private var _infoEntitiesFrame:InfoEntitiesFrame; private var _mouseOverEntityId:Number; private var sysApi:SystemApi; private var _entityTooltipData:Dictionary; private var _redColor:String; private var _mouseDown:Boolean; private var _roleplayApi:RoleplayApi; private var _socialApi:SocialApi; private var _fightPositions:FightStartingPositions; private var _fightPositionsVisible:Boolean; public var pivotingCharacter:Boolean; public function RoleplayWorldFrame() { this._infoEntitiesFrame = new InfoEntitiesFrame(); this.sysApi = new SystemApi(); this._entityTooltipData = new Dictionary(); this._roleplayApi = new RoleplayApi(); this._socialApi = new SocialApi(); super(); } public function get mouseOverEntityId() : Number { return this._mouseOverEntityId; } public function set allowOnlyCharacterInteraction(pAllow:Boolean) : void { this._allowOnlyCharacterInteraction = pAllow; } public function get allowOnlyCharacterInteraction() : Boolean { return this._allowOnlyCharacterInteraction; } public function get priority() : int { return Priority.NORMAL; } private function get roleplayContextFrame() : RoleplayContextFrame { return Kernel.getWorker().getFrame(RoleplayContextFrame) as RoleplayContextFrame; } private function get roleplayMovementFrame() : RoleplayMovementFrame { return Kernel.getWorker().getFrame(RoleplayMovementFrame) as RoleplayMovementFrame; } public function pushed() : Boolean { FrustumManager.getInstance().setBorderInteraction(true); this._allowOnlyCharacterInteraction = false; this.cellClickEnabled = true; this.pivotingCharacter = false; var shortcutsFrame:ShortcutsFrame = Kernel.getWorker().getFrame(ShortcutsFrame) as ShortcutsFrame; if(shortcutsFrame.heldShortcuts.indexOf(""showEntitiesTooltips"") != -1 && !Kernel.getWorker().contains(EntitiesTooltipsFrame)) { if(Kernel.getWorker().contains(RoleplayEntitiesFrame)) { Kernel.getWorker().addFrame(_entitiesTooltipsFrame); } else { Kernel.getWorker().addEventListener(FramePushedEvent.EVENT_FRAME_PUSHED,this.onFramePushed); } } else if(Kernel.getWorker().contains(EntitiesTooltipsFrame)) { Kernel.getWorker().removeFrame(_entitiesTooltipsFrame); } StageShareManager.stage.addEventListener(Event.DEACTIVATE,this.onWindowDeactivate); if(this._texturesReady) { return true; } this._mouseBottom = new Texture(); this._mouseBottom.uri = new Uri(this._common + ""assets.swf|cursorBottom""); this._mouseBottom.finalize(); this._mouseTop = new Texture(); this._mouseTop.uri = new Uri(this._common + ""assets.swf|cursorTop""); this._mouseTop.finalize(); this._mouseRight = new Texture(); this._mouseRight.uri = new Uri(this._common + ""assets.swf|cursorRight""); this._mouseRight.finalize(); this._mouseLeft = new Texture(); this._mouseLeft.uri = new Uri(this._common + ""assets.swf|cursorLeft""); this._mouseLeft.finalize(); this._mouseBottomBlue = new Texture(); this._mouseBottomBlue.uri = new Uri(this._common + ""assets.swf|cursorBottomBlue""); this._mouseBottomBlue.finalize(); this._mouseTopBlue = new Texture(); this._mouseTopBlue.uri = new Uri(this._common + ""assets.swf|cursorTopBlue""); this._mouseTopBlue.finalize(); this._mouseRightBlue = new Texture(); this._mouseRightBlue.uri = new Uri(this._common + ""assets.swf|cursorRightBlue""); this._mouseRightBlue.finalize(); this._mouseLeftBlue = new Texture(); this._mouseLeftBlue.uri = new Uri(this._common + ""assets.swf|cursorLeftBlue""); this._mouseLeftBlue.finalize(); this._mouseLabel = new Label(); this._mouseLabel.css = new Uri(XmlConfig.getInstance().getEntry(""config.ui.skin"") + ""css/normal.css""); this._texturesReady = true; return true; } public function process(msg:Message) : Boolean { var sf:ShortcutsFrame = null; var breachFrame:BreachFrame = null; var amomsg:AdjacentMapOverMessage = null; var targetCell:Point = null; var cellSprite:GraphicCell = null; var cellGlobalPos:Point = null; var item:LinkedCursorData = null; var worldPoint:WorldPointWrapper = null; var neighborId:Number = NaN; var neighborSubarea:SubArea = null; var subareaChange:Boolean = false; var x:int = 0; var y:int = 0; var info:String = null; var text:String = null; var text2:String = null; var text3:String = null; var zoneBound:Rectangle = null; var mcidmsg:MapComplementaryInformationsDataMessage = null; var mousePos:Point = null; var mfspmsg:MapFightStartPositionsUpdateMessage = null; var emomsg:EntityMouseOverMessage = null; var tooltipName:String = null; var entity:IInteractive = null; var animatedCharacter:AnimatedCharacter = null; var infos:* = undefined; var npcEntity:Npc = null; var targetBounds:IRectangle = null; var tooltipMaker:String = null; var cacheName:String = null; var tooltipOffset:Number = NaN; var mrcmsg:MouseRightClickMessage = null; var modContextMenu:Object = null; var menu:Object = null; var rightClickedEntity:IInteractive = null; var rpInteractivesFrame:RoleplayInteractivesFrame = null; var rightClickedInteractiveElement:InteractiveElement = null; var roleplayEntitiesFrame2:RoleplayEntitiesFrame = null; var emoutmsg:EntityMouseOutMessage = null; var ecmsg:EntityClickMessage = null; var entityc:IInteractive = null; var entityClickInfo:GameContextActorInformations = null; var npcInfo:GameRolePlayNpcInformations = null; var menuResult:Boolean = false; var sendInteractiveUseRequest:Boolean = false; var ieamsg:InteractiveElementActivationMessage = null; var interactiveFrame:RoleplayInteractivesFrame = null; var iemovmsg:InteractiveElementMouseOverMessage = null; var infosIe:Object = null; var ttMaker:String = null; var tooltipCacheName:String = null; var interactiveElem:InteractiveElement = null; var interactiveSkill:InteractiveElementSkill = null; var interactive:Interactive = null; var elementId:uint = 0; var roleplayEntitiesFrame:RoleplayEntitiesFrame = null; var houseWrapper:HouseWrapper = null; var isDirectionalPanel:Boolean = false; var iemomsg:InteractiveElementMouseOutMessage = null; var seta:ShowEntitiesTooltipsAction = null; var sfpa:ShowFightPositionsAction = null; var mum:MouseUpMessage = null; var climsg:CellClickMessage = null; var sq:SerialSequencer = null; var amcmsg:AdjacentMapClickMessage = null; var playedEntity:IEntity = null; var currentSubarea:SubArea = null; var mapPos:MapPosition = null; var target2:Rectangle = null; var tooltipData:TextTooltipInfo = null; var objectsUnder:Array = null; var o:DisplayObject = null; var oContainer:DisplayObjectContainer = null; var tooltipTarget:TiphonSprite = null; var rider:TiphonSprite = null; var isCreatureMode:Boolean = false; var head:DisplayObject = null; var r1:Rectangle = null; var r2:Rectangle2 = null; var p:Point = null; var fight:FightTeam = null; var allianceInfos:AllianceInformations = null; var levelDiffInfo:int = 0; var grtci:GameRolePlayTaxCollectorInformations = null; var guildtcinfos:GuildInformations = null; var gwtc:GuildWrapper = null; var awtc:AllianceWrapper = null; var npcInfos:GameRolePlayNpcInformations = null; var npc:Npc = null; var allianceFrame:AllianceFrame = null; var treasureHintInfos:GameRolePlayTreasureHintInformations = null; var npch:Npc = null; var targetLevel:uint = 0; var monster:MonsterInGroupLightInformations = null; var monstersInfo:Vector. = null; var grpgmwi:GameRolePlayGroupMonsterWaveInformations = null; var currentBranch:BreachBranchWrapper = null; var waveInfo:GroupMonsterStaticInformations = null; var rcf:RoleplayContextFrame = null; var actorInfos:GameContextActorInformations = null; var rightClickedinfos:GameContextActorInformations = null; var houseWrapper2:HouseWrapper = null; var linkType:String = null; var linkParams:Object = null; var prismInfo:GameRolePlayPrismInformations = null; var prismName:String = null; var taxCollectorInfo:GameRolePlayTaxCollectorInformations = null; var npcActions:Vector. = null; var ngara:NpcGenericActionRequestAction = null; var fightId:uint = 0; var fightTeamLeader:Number = NaN; var teamType:uint = 0; var gfjrmsg:GameFightJoinRequestMessage = null; var playerEntity3:IEntity = null; var guildId:int = 0; var team:FightTeam = null; var fighter:FightTeamMemberInformations = null; var guild:GuildWrapper = null; var playerEntity:IEntity = null; var forbiddenCellsIds:Array = null; var i:int = 0; var j:int = 0; var mp:MapPoint = null; var mp2:MapPoint = null; var cells:Vector. = null; var cellData:CellData = null; var dmp:DataMapProvider = null; var nearestCell:MapPoint = null; var ieCellData:CellData = null; var skills:Vector. = null; var minimalRange:int = 0; var skillForRange:InteractiveElementSkill = null; var distanceElementToPlayer:int = 0; var forbidden:Boolean = false; var numWalkableCells:uint = 0; var skillData:Skill = null; var iRange:int = 0; var foundDuplicate:Boolean = false; var interactiveSkill2:InteractiveElementSkill = null; var firstBoss:Boolean = false; var breachBranchInfo:* = null; var bossInfo:MonsterInGroupLightInformations = null; var element:Object = null; var elem:Object = null; var target:Rectangle = null; switch(true) { case msg is CellClickMessage: if(this.pivotingCharacter) { return false; } if(!(msg as CellClickMessage).fromAutotrip) { MountAutoTripManager.getInstance().stopCurrentTrip(); } if(this.allowOnlyCharacterInteraction) { return false; } if(this.cellClickEnabled) { climsg = msg as CellClickMessage; try { sq = new SerialSequencer(); sq.addStep(new AddGfxEntityStep(3506,climsg.cellId)); sq.start(); } catch(e:Error) { } (Kernel.getWorker().getFrame(RoleplayEntitiesFrame) as RoleplayEntitiesFrame).currentEmoticon = 0; this.roleplayMovementFrame.resetNextMoveMapChange(); this.roleplayMovementFrame.setFollowingInteraction(null); this.roleplayMovementFrame.askMoveTo(MapPoint.fromCellId(climsg.cellId)); } return true; break; case msg is AdjacentMapClickMessage: if(this.allowOnlyCharacterInteraction) { return false; } if(!(msg as AdjacentMapClickMessage).fromAutotrip) { MountAutoTripManager.getInstance().stopCurrentTrip(); } if(this.cellClickEnabled) { amcmsg = msg as AdjacentMapClickMessage; playedEntity = DofusEntities.getEntity(PlayedCharacterManager.getInstance().id); if(!playedEntity) { _log.warn(""The player tried to move before its character was added to the scene. Aborting.""); return false; } this.roleplayMovementFrame.setNextMoveMapChange(amcmsg.adjacentMapId,(msg as AdjacentMapClickMessage).fromAutotrip); if(!playedEntity.position.equals(MapPoint.fromCellId(amcmsg.cellId))) { this.roleplayMovementFrame.setFollowingInteraction(null); this.roleplayMovementFrame.askMoveTo(MapPoint.fromCellId(amcmsg.cellId)); } else { this.roleplayMovementFrame.setFollowingInteraction(null); this.roleplayMovementFrame.askMapChange(); } } return true; break; case msg is AdjacentMapOutMessage: if(this.allowOnlyCharacterInteraction) { return false; } TooltipManager.hide(""subareaChange""); LinkedCursorSpriteManager.getInstance().removeItem(""changeMapCursor""); return true; break; case msg is AdjacentMapOverMessage: if(this.allowOnlyCharacterInteraction) { return false; } amomsg = AdjacentMapOverMessage(msg); targetCell = CellIdConverter.cellIdToCoord(amomsg.cellId); cellSprite = InteractiveCellManager.getInstance().getCell(amomsg.cellId); cellGlobalPos = cellSprite.parent.localToGlobal(new Point(cellSprite.x,cellSprite.y)); item = new LinkedCursorData(); if(PlayedCharacterManager.getInstance().currentMap.leftNeighbourId == -1 && PlayedCharacterManager.getInstance().currentMap.rightNeighbourId == -1 && PlayedCharacterManager.getInstance().currentMap.topNeighbourId == -1 && PlayedCharacterManager.getInstance().currentMap.bottomNeighbourId == -1) { worldPoint = new WorldPointWrapper(MapDisplayManager.getInstance().getDataMapContainer().id); } else { worldPoint = PlayedCharacterManager.getInstance().currentMap; } if(amomsg.direction == DirectionsEnum.RIGHT) { neighborId = worldPoint.rightNeighbourId; } else if(amomsg.direction == DirectionsEnum.DOWN) { neighborId = worldPoint.bottomNeighbourId; } else if(amomsg.direction == DirectionsEnum.LEFT) { neighborId = worldPoint.leftNeighbourId; } else if(amomsg.direction == DirectionsEnum.UP) { neighborId = worldPoint.topNeighbourId; } neighborSubarea = SubArea.getSubAreaByMapId(neighborId); subareaChange = false; x = 0; y = 0; if(neighborSubarea) { currentSubarea = PlayedCharacterManager.getInstance().currentSubArea; if(neighborSubarea.id != currentSubarea.id) { subareaChange = true; text = I18n.getUiText(""ui.common.toward"",[neighborSubarea.name]); text2 = I18n.getUiText(""ui.common.level"") + "" "" + neighborSubarea.level; } if(PlayerManager.getInstance().isBasicAccount() && !neighborSubarea.basicAccountAllowed) { text3 = I18n.getUiText(""ui.payzone.payzone""); } mapPos = MapPosition.getMapPositionById(neighborId); if(mapPos.showNameOnFingerpost && mapPos.name) { text = I18n.getUiText(""ui.common.toward"",[mapPos.name]); } if(text && text != """") { if(!text2 || text.length > text2.length) { if(!text3 || text.length > text3.length) { this._mouseLabel.text = text; } else { this._mouseLabel.text = text3; } } else if(!text3 || text2.length > text3.length) { this._mouseLabel.text = text2; } else { this._mouseLabel.text = text3; } info = text; if(text2) { info += ""\\n"" + text2; } if(text3) { if(!this._redColor) { this._redColor = XmlConfig.getInstance().getEntry(""colors.hyperlink.warning""); this._redColor = this._redColor.replace(""0x"",""#""); } info += ""\\n"" + text3 + """"; } } } zoneBound = amomsg.zone.getBounds(amomsg.zone); switch(amomsg.direction) { case DirectionsEnum.LEFT: item.sprite = !!subareaChange ? this._mouseLeftBlue : this._mouseLeft; item.lockX = true; item.sprite.x = zoneBound.right; item.offset = new Point(0,0); item.lockY = true; item.sprite.y = cellGlobalPos.y + AtouinConstants.CELL_HEIGHT / 2 * Atouin.getInstance().currentZoom; if(subareaChange) { x = 0; y = item.sprite.height / 2; } break; case DirectionsEnum.UP: item.sprite = !!subareaChange ? this._mouseTopBlue : this._mouseTop; item.lockY = true; item.sprite.y = zoneBound.bottom; item.offset = new Point(0,0); item.lockX = true; item.sprite.x = cellGlobalPos.x + AtouinConstants.CELL_WIDTH / 2 * Atouin.getInstance().currentZoom; if(subareaChange) { x = -this._mouseLabel.textWidth / 2; y = item.sprite.height + 5; } break; case DirectionsEnum.DOWN: item.sprite = !!subareaChange ? this._mouseBottomBlue : this._mouseBottom; item.lockY = true; item.sprite.y = zoneBound.top; item.offset = new Point(0,0); item.lockX = true; item.sprite.x = cellGlobalPos.x + AtouinConstants.CELL_WIDTH / 2 * Atouin.getInstance().currentZoom; if(subareaChange) { x = -this._mouseLabel.textWidth / 2; y = -item.sprite.height - this._mouseLabel.textHeight - 34; } break; case DirectionsEnum.RIGHT: item.sprite = !!subareaChange ? this._mouseRightBlue : this._mouseRight; item.lockX = true; item.sprite.x = zoneBound.left; item.offset = new Point(0,0); item.lockY = true; item.sprite.y = cellGlobalPos.y + AtouinConstants.CELL_HEIGHT / 2 * Atouin.getInstance().currentZoom; if(subareaChange) { x = -this._mouseLabel.textWidth; y = item.sprite.height / 2; } } if(subareaChange) { target2 = new Rectangle(item.sprite.x + x,item.sprite.y + y,1,1); tooltipData = new TextTooltipInfo(info,null,""center""); TooltipManager.show(tooltipData,target2,UiModuleManager.getInstance().getModule(""Ankama_GameUiCore""),false,""subareaChange"",0,0,0,true,null,null,null,""Text"" + neighborId); } LinkedCursorSpriteManager.getInstance().addItem(""changeMapCursor"",item); return true; break; case msg is MapComplementaryInformationsDataMessage: mcidmsg = msg as MapComplementaryInformationsDataMessage; this._fightPositions = mcidmsg.fightStartPositions; sf = Kernel.getWorker().getFrame(ShortcutsFrame) as ShortcutsFrame; if(sf.heldShortcuts.indexOf(""showFightPositions"") != -1 && this._fightPositionsVisible) { this.showFightPositions(); } MountAutoTripManager.getInstance().startNextTripStage(mcidmsg.mapId); if(!StageShareManager.mouseOnStage) { return false; } mousePos = new Point(StageShareManager.stage.mouseX,StageShareManager.stage.mouseY); if(Atouin.getInstance().options.getOption(""frustum"").containsPoint(mousePos)) { objectsUnder = StageShareManager.stage.getObjectsUnderPoint(mousePos); for each(o in objectsUnder) { if(o is FrustumShape) { o.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER)); break; } } } return false; break; case msg is MapFightStartPositionsUpdateMessage: mfspmsg = msg as MapFightStartPositionsUpdateMessage; if(PlayedCharacterManager.getInstance().currentMap && mfspmsg.mapId == PlayedCharacterManager.getInstance().currentMap.mapId) { this._fightPositions = mfspmsg.fightStartPositions; } return true; case msg is EntityMouseOverMessage: emomsg = msg as EntityMouseOverMessage; this._mouseOverEntityId = emomsg.entity.id; tooltipName = ""entity_"" + emomsg.entity.id; this.displayCursor(NO_CURSOR); entity = emomsg.entity as IInteractive; animatedCharacter = entity as AnimatedCharacter; infos = this.roleplayContextFrame.entitiesFrame.getEntityInfos(entity.id) as GameRolePlayActorInformations; if(infos is GameRolePlayNpcInformations && (npcEntity = Npc.getNpcById((infos as GameRolePlayNpcInformations).npcId)) != null && !npcEntity.tooltipVisible) { return false; } if(animatedCharacter) { animatedCharacter = animatedCharacter.getRootEntity(); animatedCharacter.highLightCharacterAndFollower(true); entity = animatedCharacter; if(OptionManager.getOptionManager(""tiphon"").getOption(""auraMode"") == OptionEnum.AURA_ON_ROLLOVER && animatedCharacter.getDirection() == DirectionsEnum.DOWN) { animatedCharacter.visibleAura = true; } infos = this.roleplayContextFrame.entitiesFrame.getEntityInfos(entity.id) as GameRolePlayActorInformations; } if(entity is TiphonSprite) { tooltipTarget = entity as TiphonSprite; rider = (entity as TiphonSprite).getSubEntitySlot(SubEntityBindingPointCategoryEnum.HOOK_POINT_CATEGORY_MOUNT_DRIVER,0) as TiphonSprite; isCreatureMode = Kernel.getWorker().getFrame(RoleplayEntitiesFrame) && RoleplayEntitiesFrame(Kernel.getWorker().getFrame(RoleplayEntitiesFrame)).isCreatureMode; if(rider && !isCreatureMode) { tooltipTarget = rider; } head = tooltipTarget.getSlot(""Tete""); if(head) { r1 = head.getBounds(StageShareManager.stage); r2 = new Rectangle2(r1.x,r1.y,r1.width,r1.height); targetBounds = r2; } else if(tooltipTarget.rect) { p = tooltipTarget.localToGlobal(new Point(tooltipTarget.rect.x,tooltipTarget.rect.y)); targetBounds = new Rectangle2(p.x,p.y,tooltipTarget.rect.width,tooltipTarget.rect.height); } else { p = tooltipTarget.localToGlobal(new Point(tooltipTarget.x,tooltipTarget.y)); targetBounds = new Rectangle2(p.x,p.y,tooltipTarget.width,tooltipTarget.height); } } if(!targetBounds || targetBounds.width == 0 && targetBounds.height == 0) { targetBounds = (entity as IDisplayable).absoluteBounds; } tooltipMaker = null; tooltipOffset = 0; if(this.roleplayContextFrame.entitiesFrame.isFight(entity.id)) { if(this.allowOnlyCharacterInteraction) { return false; } fight = this.roleplayContextFrame.entitiesFrame.getFightTeam(entity.id); infos = new RoleplayTeamFightersTooltipInformation(fight); tooltipMaker = ""roleplayFight""; this.displayCursor(FIGHT_CURSOR,!PlayedCharacterManager.getInstance().restrictions.cantAttackMonster); if(fight.hasOptions() || fight.hasGroupMember()) { tooltipOffset = 35; } } else { switch(true) { case infos is GameRolePlayCharacterInformations: if(infos.contextualId == PlayedCharacterManager.getInstance().id) { levelDiffInfo = 0; } else { targetLevel = int(infos.alignmentInfos.characterPower - infos.contextualId); levelDiffInfo = PlayedCharacterManager.getInstance().levelDiff(targetLevel); } infos = new CharacterTooltipInformation(infos as GameRolePlayCharacterInformations,levelDiffInfo); cacheName = ""CharacterCache""; break; case infos is GameRolePlayMerchantInformations: cacheName = ""MerchantCharacterCache""; break; case infos is GameRolePlayMutantInformations: if((infos as GameRolePlayMutantInformations).humanoidInfo.restrictions.cantAttack) { infos = new CharacterTooltipInformation(infos,0); } else { infos = new MutantTooltipInformation(infos as GameRolePlayMutantInformations); } break; case infos is GameRolePlayTaxCollectorInformations: if(this.allowOnlyCharacterInteraction) { return false; } grtci = infos as GameRolePlayTaxCollectorInformations; guildtcinfos = grtci.identification.guildIdentity; allianceInfos = grtci.identification is TaxCollectorStaticExtendedInformations ? (grtci.identification as TaxCollectorStaticExtendedInformations).allianceIdentity : null; gwtc = GuildWrapper.create(guildtcinfos.guildId,guildtcinfos.guildName,guildtcinfos.guildEmblem,0); awtc = !!allianceInfos ? AllianceWrapper.create(allianceInfos.allianceId,allianceInfos.allianceTag,allianceInfos.allianceName,allianceInfos.allianceEmblem) : null; infos = new TaxCollectorTooltipInformation(TaxCollectorName.getTaxCollectorNameById((infos as GameRolePlayTaxCollectorInformations).identification.lastNameId).name,TaxCollectorFirstname.getTaxCollectorFirstnameById((infos as GameRolePlayTaxCollectorInformations).identification.firstNameId).firstname,gwtc,awtc,(infos as GameRolePlayTaxCollectorInformations).taxCollectorAttack,emomsg.checkSuperposition,grtci.disposition.cellId); cacheName = ""TaxCollectorCache""; break; case infos is GameRolePlayNpcInformations: if(this.allowOnlyCharacterInteraction) { return false; } npcInfos = infos as GameRolePlayNpcInformations; npc = Npc.getNpcById(npcInfos.npcId); infos = new TextTooltipInfo(npc.name,XmlConfig.getInstance().getEntry(""config.ui.skin"") + ""css/tooltip_npc.css"",""green"",0,emomsg.checkSuperposition,npcInfos.disposition.cellId); infos.bgCornerRadius = 10; cacheName = !emomsg.virtual ? ""NPCCacheName"" : ""NPCCacheName_"" + this._mouseOverEntityId; if(npc.actions.length == 0) { break; } if(!emomsg.virtual) { this.displayCursor(NPC_CURSOR); } break; case infos is GameRolePlayGroupMonsterInformations: if(this.allowOnlyCharacterInteraction) { return false; } if(!emomsg.virtual) { this.displayCursor(FIGHT_CURSOR,!PlayedCharacterManager.getInstance().restrictions.cantAttackMonster); } cacheName = !emomsg.virtual ? ""GroupMonsterCache"" : ""GroupMonsterCache_"" + this._mouseOverEntityId; if((emomsg.entity as AnimatedCharacter).followed) { tooltipName = ""entity_"" + (emomsg.entity as AnimatedCharacter).followed.id; } if(PlayedCharacterManager.getInstance().isInBreach) { monstersInfo = new Vector.(); monstersInfo.push(infos.staticInfos.mainCreatureLightInfos); for each(monster in infos.staticInfos.underlings) { monstersInfo.push(monster); } grpgmwi = infos as GameRolePlayGroupMonsterWaveInformations; if(grpgmwi) { for each(waveInfo in grpgmwi.alternatives) { monstersInfo.push(waveInfo.mainCreatureLightInfos); for each(monster in waveInfo.underlings) { monstersInfo.push(monster); } } } cacheName = ""BreachGroupMonsterCache""; tooltipMaker = ""breachMonsterGroup""; breachFrame = Kernel.getWorker().getFrame(BreachFrame) as BreachFrame; if(breachFrame && breachFrame.wrappedBranches && breachFrame.wrappedBranches.length > 0) { currentBranch = breachFrame.wrappedBranches[0] as BreachBranchWrapper; } infos = { ""monsterGroup"":monstersInfo, ""score"":currentBranch.score, ""relativeScore"":currentBranch.relativeScore }; } break; case infos is GameRolePlayPrismInformations: allianceFrame = Kernel.getWorker().getFrame(AllianceFrame) as AllianceFrame; infos = new PrismTooltipInformation(allianceFrame.getPrismSubAreaById(PlayedCharacterManager.getInstance().currentSubArea.id).alliance,emomsg.checkSuperposition,infos.disposition.cellId); cacheName = ""PrismCache""; break; case infos is GameRolePlayPortalInformations: infos = new PortalTooltipInformation((infos as GameRolePlayPortalInformations).portal.areaId,emomsg.checkSuperposition,infos.disposition.cellId); cacheName = ""PortalCache""; break; case infos is GameContextPaddockItemInformations: cacheName = ""PaddockItemCache""; break; case infos is GameRolePlayTreasureHintInformations: if(this.allowOnlyCharacterInteraction) { return false; } treasureHintInfos = infos as GameRolePlayTreasureHintInformations; npch = Npc.getNpcById(treasureHintInfos.npcId); infos = new TextTooltipInfo(npch.name,XmlConfig.getInstance().getEntry(""config.ui.skin"") + ""css/tooltip_npc.css"",""orange"",0); infos.bgCornerRadius = 10; cacheName = ""TrHintCacheName""; break; } } if(!infos) { _log.warn(""Rolling over a unknown entity ("" + emomsg.entity.id + "").""); return false; } if(this.roleplayContextFrame.entitiesFrame.hasIcon(entity.id)) { tooltipOffset = 45; } if(animatedCharacter && !animatedCharacter.rawAnimation && !this._entityTooltipData[animatedCharacter]) { this._entityTooltipData[animatedCharacter] = { ""data"":infos, ""name"":tooltipName, ""tooltipMaker"":tooltipMaker, ""tooltipOffset"":tooltipOffset, ""cacheName"":cacheName }; animatedCharacter.removeEventListener(TiphonEvent.RENDER_SUCCEED,this.onEntityAnimRendered); animatedCharacter.addEventListener(TiphonEvent.RENDER_SUCCEED,this.onEntityAnimRendered); } else { TooltipManager.show(infos,targetBounds,UiModuleManager.getInstance().getModule(""Ankama_Tooltips""),false,tooltipName,LocationEnum.POINT_BOTTOM,LocationEnum.POINT_TOP,tooltipOffset,true,tooltipMaker,null,null,cacheName,false,StrataEnum.STRATA_WORLD,this.sysApi.getCurrentZoom()); } return true; break; case msg is MouseRightClickMessage: mrcmsg = msg as MouseRightClickMessage; modContextMenu = UiModuleManager.getInstance().getModule(""Ankama_ContextMenu"").mainClass; rightClickedEntity = mrcmsg.target as IInteractive; if(rightClickedEntity) { rcf = this.roleplayContextFrame; if(!(rightClickedEntity as AnimatedCharacter) || (rightClickedEntity as AnimatedCharacter).followed == null) { actorInfos = rcf.entitiesFrame.getEntityInfos(rightClickedEntity.id); } else { actorInfos = rcf.entitiesFrame.getEntityInfos((rightClickedEntity as AnimatedCharacter).followed.id); } if(actorInfos is GameRolePlayNamedActorInformations) { if(!(rightClickedEntity is AnimatedCharacter)) { _log.error(""L\\'entity "" + rightClickedEntity.id + "" est un GameRolePlayNamedActorInformations mais n\\'est pas un AnimatedCharacter""); return true; } rightClickedEntity = (rightClickedEntity as AnimatedCharacter).getRootEntity(); rightClickedinfos = this.roleplayContextFrame.entitiesFrame.getEntityInfos(rightClickedEntity.id); menu = MenusFactory.create(rightClickedinfos,""multiplayer"",[rightClickedEntity]); if(menu) { modContextMenu.createContextMenu(menu,null,null,""multiplayerMenu""); } return true; } if(actorInfos is GameRolePlayGroupMonsterInformations) { menu = MenusFactory.create(actorInfos,""monsterGroup"",[rightClickedEntity]); if(menu) { modContextMenu.createContextMenu(menu); } return true; } if(actorInfos is GameRolePlayPortalInformations || actorInfos is GameRolePlayPrismInformations || actorInfos is GameRolePlayTaxCollectorInformations || actorInfos is GameRolePlayNpcInformations) { menu = MenusFactory.create(actorInfos,null,{ ""entity"":rightClickedEntity, ""rightClick"":true }); if(menu) { modContextMenu.createContextMenu(menu); } return true; } } rpInteractivesFrame = Kernel.getWorker().getFrame(RoleplayInteractivesFrame) as RoleplayInteractivesFrame; rightClickedInteractiveElement = rpInteractivesFrame.getInteractiveElement(mrcmsg.target); roleplayEntitiesFrame2 = Kernel.getWorker().getFrame(RoleplayEntitiesFrame) as RoleplayEntitiesFrame; if(rightClickedInteractiveElement && roleplayEntitiesFrame2.housesInformations && roleplayEntitiesFrame2.housesInformations[rightClickedInteractiveElement.elementId]) { houseWrapper2 = roleplayEntitiesFrame2.housesInformations[rightClickedInteractiveElement.elementId]; menu = MenusFactory.create(houseWrapper2,""house""); if(menu) { TooltipManager.hide(); modContextMenu.createContextMenu(menu); } return true; } if(rightClickedInteractiveElement && rightClickedInteractiveElement.elementTypeId != -1) { menu = MenusFactory.create(rightClickedInteractiveElement,""interactiveElement""); if(menu) { TooltipManager.hide(); modContextMenu.createContextMenu(menu); } return true; } return false; break; case msg is EntityMouseOutMessage: emoutmsg = msg as EntityMouseOutMessage; this._mouseOverEntityId = 0; this.displayCursor(NO_CURSOR); animatedCharacter = emoutmsg.entity as AnimatedCharacter; if(emoutmsg.entity) { TooltipManager.hide(""entity_"" + emoutmsg.entity.id); } if(animatedCharacter) { if(animatedCharacter.followed) { TooltipManager.hide(""entity_"" + animatedCharacter.followed.id); } animatedCharacter = animatedCharacter.getRootEntity(); animatedCharacter.highLightCharacterAndFollower(false); if(OptionManager.getOptionManager(""tiphon"").getOption(""auraMode"") == OptionEnum.AURA_ON_ROLLOVER) { animatedCharacter.visibleAura = false; } } return true; case msg is EntityClickMessage: ecmsg = msg as EntityClickMessage; MountAutoTripManager.getInstance().stopCurrentTrip(); entityc = ecmsg.entity as IInteractive; if(entityc is AnimatedCharacter) { entityc = (entityc as AnimatedCharacter).getRootEntity(); } entityClickInfo = this.roleplayContextFrame.entitiesFrame.getEntityInfos(entityc.id); if(ShortcutsFrame.shiftKey) { linkType = ""Map""; linkParams = { ""x"":PlayedCharacterManager.getInstance().currentMap.outdoorX, ""y"":PlayedCharacterManager.getInstance().currentMap.outdoorY, ""worldMapId"":PlayedCharacterManager.getInstance().currentSubArea.worldmap.id, ""elementName"":"""" }; switch(true) { case entityClickInfo is GameRolePlayPortalInformations: linkParams.elementName = I18n.getUiText(""ui.dimension.portal"",[Area.getAreaById((entityClickInfo as GameRolePlayPortalInformations).portal.areaId).name]) + "" ""; break; case entityClickInfo is GameRolePlayPrismInformations: prismInfo = entityClickInfo as GameRolePlayPrismInformations; prismName = this._socialApi.getAllianceNameAndTag(prismInfo.prism); linkParams.elementName = I18n.getUiText(""ui.prism.prismInState"",[I18n.getUiText(""ui.prism.state"" + prismInfo.prism.state)]) + "" "" + LangManager.getInstance().replaceKey(prismName,true) + "" ""; break; case entityClickInfo is GameRolePlayTaxCollectorInformations: taxCollectorInfo = entityClickInfo as GameRolePlayTaxCollectorInformations; linkParams.elementName = I18n.getUiText(""ui.guild.taxCollector"",[taxCollectorInfo.identification.guildIdentity.guildName]) + "" ""; break; case entityClickInfo is GameRolePlayNpcInformations: linkParams.elementName = Npc.getNpcById((entityClickInfo as GameRolePlayNpcInformations).npcId).name + "" ""; break; case entityClickInfo is GameRolePlayGroupMonsterInformations: linkType = PlayedCharacterManager.getInstance().isInAnomaly || PlayedCharacterManager.getInstance().isInBreach ? ""MonsterGroupScale"" : ""MonsterGroup""; linkParams.monsterName = Monster.getMonsterById((entityClickInfo as GameRolePlayGroupMonsterInformations).staticInfos.mainCreatureLightInfos.genericId).name; linkParams.infos = this._roleplayApi.getMonsterGroupString(entityClickInfo); break; case entityClickInfo is GameRolePlayCharacterInformations: linkParams.elementName = (entityClickInfo as GameRolePlayCharacterInformations).name + "" ""; } KernelEventsManager.getInstance().processCallback(BeriliaHookList.MouseShiftClick,{ ""data"":linkType, ""params"":linkParams }); Kernel.getWorker().process(EmptyStackAction.create()); return true; } npcInfo = entityClickInfo as GameRolePlayNpcInformations; if(npcInfo) { npcActions = Npc.getNpcById(npcInfo.npcId).actions; if(!MenusFactory.getMenuMaker(""npc"").maker.disabled && npcActions.length == 1) { ngara = new NpcGenericActionRequestAction(); ngara.npcId = entityc.id; this.process(new EntityMouseOutMessage(entityc)); ngara.actionId = NpcAction.getNpcActionById(npcActions[0]).realId; Kernel.getWorker().process(ngara); return true; } } else if(entityClickInfo is GameRolePlayMerchantInformations) { Kernel.getWorker().process(ExchangeOnHumanVendorRequestAction.create(entityClickInfo.contextualId,entityClickInfo.disposition.cellId)); return true; } menuResult = RoleplayManager.getInstance().displayContextualMenu(entityClickInfo,entityc); if(this.roleplayContextFrame.entitiesFrame.isFight(entityc.id)) { fightId = this.roleplayContextFrame.entitiesFrame.getFightId(entityc.id); fightTeamLeader = this.roleplayContextFrame.entitiesFrame.getFightLeaderId(entityc.id); teamType = this.roleplayContextFrame.entitiesFrame.getFightTeamType(entityc.id); if(teamType == TeamTypeEnum.TEAM_TYPE_TAXCOLLECTOR) { team = this.roleplayContextFrame.entitiesFrame.getFightTeam(entityc.id) as FightTeam; for each(fighter in team.teamInfos.teamMembers) { if(fighter is FightTeamMemberTaxCollectorInformations) { guildId = (fighter as FightTeamMemberTaxCollectorInformations).guildId; } } guild = (Kernel.getWorker().getFrame(SocialFrame) as SocialFrame).guild; if(guild && guildId == guild.guildId) { KernelEventsManager.getInstance().processCallback(SocialHookList.OpenSocial,1,2); Kernel.getWorker().process(GuildFightJoinRequestAction.create(PlayedCharacterManager.getInstance().currentMap.mapId)); return true; } } gfjrmsg = new GameFightJoinRequestMessage(); gfjrmsg.initGameFightJoinRequestMessage(fightTeamLeader,fightId); playerEntity3 = DofusEntities.getEntity(PlayedCharacterManager.getInstance().id); if((playerEntity3 as IMovable).isMoving) { this.roleplayMovementFrame.setFollowingMessage(gfjrmsg); (playerEntity3 as IMovable).stop(); } else { ConnectionsHandler.getConnection().send(gfjrmsg); } } else if(entityc.id != PlayedCharacterManager.getInstance().id && !menuResult) { this.roleplayMovementFrame.setFollowingInteraction(null); if(entityClickInfo is GameRolePlayActorInformations && entityClickInfo is GameRolePlayGroupMonsterInformations) { this.roleplayMovementFrame.setFollowingMonsterFight(entityc); } this.roleplayMovementFrame.askMoveTo(entityc.position); } return true; break; case msg is InteractiveElementActivationMessage: if(!MountAutoTripManager.getInstance().isTravelling && (this.allowOnlyCharacterInteraction || OptionManager.getOptionManager(""dofus"").getOption(""enableForceWalk"") == true && (ShortcutsFrame.ctrlKeyDown || SystemManager.getSingleton().os == OperatingSystem.MAC_OS && ShortcutsFrame.altKeyDown))) { return false; } if(!(msg as InteractiveElementActivationMessage).fromAutotrip) { MountAutoTripManager.getInstance().stopCurrentTrip(); } sendInteractiveUseRequest = true; ieamsg = msg as InteractiveElementActivationMessage; interactiveFrame = Kernel.getWorker().getFrame(RoleplayInteractivesFrame) as RoleplayInteractivesFrame; if(!(interactiveFrame && interactiveFrame.usingInteractive)) { playerEntity = DofusEntities.getEntity(PlayedCharacterManager.getInstance().id); if(!playerEntity) { return true; } forbiddenCellsIds = new Array(); cells = MapDisplayManager.getInstance().getDataMapContainer().dataMap.cells; dmp = DataMapProvider.getInstance(); for(i = 0; i < 8; i++) { mp = ieamsg.position.getNearestCellInDirection(i); if(mp) { cellData = cells[mp.cellId]; forbidden = !cellData.mov || cellData.farmCell; if(!forbidden) { numWalkableCells = 8; for(j = 0; j < 8; j++) { mp2 = mp.getNearestCellInDirection(j); if(mp2 && (!dmp.pointMov(mp2.x,mp2.y,true,mp.cellId) || !dmp.pointMov(mp2.x - 1,mp2.y,true,mp.cellId) && !dmp.pointMov(mp2.x,mp2.y - 1,true,mp.cellId))) { numWalkableCells--; } } if(!numWalkableCells) { forbidden = true; } } if(forbidden) { if(!forbiddenCellsIds) { forbiddenCellsIds = []; } forbiddenCellsIds.push(mp.cellId); } } } ieCellData = cells[ieamsg.position.cellId]; skills = ieamsg.interactiveElement.enabledSkills; minimalRange = 63; for each(skillForRange in skills) { skillData = Skill.getSkillById(skillForRange.skillId); if(skillData) { if(!skillData.useRangeInClient) { minimalRange = 1; } else if(skillData.range < minimalRange) { minimalRange = skillData.range; } } } distanceElementToPlayer = ieamsg.position.distanceToCell(playerEntity.position); if(distanceElementToPlayer <= minimalRange && (!ieCellData.mov || ieCellData.farmCell)) { nearestCell = MapPoint.fromCellId(playerEntity.position.cellId); } else { nearestCell = ieamsg.position.getNearestFreeCellInDirection(ieamsg.position.advancedOrientationTo(playerEntity.position),DataMapProvider.getInstance(),true,true,false,forbiddenCellsIds); if(minimalRange > 1) { for(iRange = 1; iRange < minimalRange; ) { forbiddenCellsIds.push(nearestCell.cellId); nearestCell = nearestCell.getNearestFreeCellInDirection(nearestCell.advancedOrientationTo(playerEntity.position,false),DataMapProvider.getInstance(),true,true,false,forbiddenCellsIds); if(!nearestCell || nearestCell.cellId == playerEntity.position.cellId) { break; } iRange++; } } } if(skills.length == 1 && SkillManager.getInstance().isDoorCursorSkill(skills[0].skillId)) { nearestCell.cellId = ieamsg.position.cellId; sendInteractiveUseRequest = false; } if(!nearestCell || forbiddenCellsIds.indexOf(nearestCell.cellId) != -1) { nearestCell = ieamsg.position; } if(sendInteractiveUseRequest) { this.roleplayMovementFrame.setFollowingInteraction({ ""ie"":ieamsg.interactiveElement, ""skillInstanceId"":ieamsg.skillInstanceId, ""additionalParam"":ieamsg.additionalParam }); } this.roleplayMovementFrame.resetNextMoveMapChange(); this.roleplayMovementFrame.askMoveTo(nearestCell); } return true; break; case msg is InteractiveElementMouseOverMessage: if(this.allowOnlyCharacterInteraction || OptionManager.getOptionManager(""dofus"").getOption(""enableForceWalk"") == true && (ShortcutsFrame.ctrlKeyDown || SystemManager.getSingleton().os == OperatingSystem.MAC_OS && ShortcutsFrame.altKeyDown)) { return false; } iemovmsg = msg as InteractiveElementMouseOverMessage; interactiveElem = iemovmsg.interactiveElement; for each(interactiveSkill in interactiveElem.enabledSkills) { if(interactiveSkill.skillId == DataEnum.SKILL_ACCESS_PADDOCK) { infosIe = this.roleplayContextFrame.currentPaddock; break; } } for each(interactiveSkill in interactiveElem.disabledSkills) { if(SkillManager.getInstance().isDoorCursorSkill(interactiveSkill.skillId)) { foundDuplicate = false; for each(interactiveSkill2 in interactiveElem.enabledSkills) { if(interactiveSkill2.skillId == interactiveSkill.skillId) { foundDuplicate = true; break; } } if(!foundDuplicate) { interactiveElem.enabledSkills.push(interactiveSkill); } break; } } interactive = Interactive.getInteractiveById(interactiveElem.elementTypeId); elementId = iemovmsg.interactiveElement.elementId; roleplayEntitiesFrame = Kernel.getWorker().getFrame(RoleplayEntitiesFrame) as RoleplayEntitiesFrame; if(roleplayEntitiesFrame.housesInformations && roleplayEntitiesFrame.housesInformations[elementId]) { houseWrapper = roleplayEntitiesFrame.housesInformations[elementId]; } breachFrame = Kernel.getWorker().getFrame(BreachFrame) as BreachFrame; if(breachFrame && breachFrame.branches && breachFrame.branches[elementId]) { firstBoss = true; breachBranchInfo = I18n.getUiText(""ui.breach.roomNumber"",[breachFrame.branches[elementId].room]) + "" ("" + SubArea.getSubAreaByMapId(breachFrame.branches[elementId].map).name + "")\\n""; for each(bossInfo in breachFrame.branches[elementId].bosses) { breachBranchInfo += (!firstBoss ? "", "" : """") + Monster.getMonsterById(bossInfo.genericId).name; firstBoss = false; } element = new Object(); element.interactive = breachBranchInfo; SkillManager.getInstance().prepareTooltip(element,interactiveElem); infosIe = element; ttMaker = ""interactiveElement""; tooltipCacheName = ""InteractiveElementCache_"" + element.interactive; } isDirectionalPanel = false; for each(interactiveSkill in interactiveElem.enabledSkills) { if(SkillManager.getInstance().isDirectionalPanel(interactiveSkill.skillId)) { isDirectionalPanel = true; break; } } if(houseWrapper) { infosIe = houseWrapper; } else if(interactiveElem.elementTypeId == DIRECTIONAL_PANEL_ID || isDirectionalPanel) { infosIe = Sign.getSignById(interactiveElem.elementId); ttMaker = ""directionalSign""; } else if(infosIe == null && interactive) { elem = new Object(); elem.interactive = interactive.name; SkillManager.getInstance().prepareTooltip(elem,interactiveElem); infosIe = elem; ttMaker = ""interactiveElement""; tooltipCacheName = ""InteractiveElementCache_"" + elem.interactive; } if(infosIe) { target = iemovmsg.sprite.getRect(StageShareManager.stage); TooltipManager.show(infosIe,new Rectangle(target.right,int(target.y + target.height - AtouinConstants.CELL_HEIGHT),0,0),UiModuleManager.getInstance().getModule(""Ankama_Tooltips""),false,TooltipManager.TOOLTIP_STANDAR_NAME,LocationEnum.POINT_BOTTOMLEFT,LocationEnum.POINT_TOP,0,true,ttMaker,null,null,tooltipCacheName); } return true; break; case msg is InteractiveElementMouseOutMessage: if(this.allowOnlyCharacterInteraction) { return false; } iemomsg = msg as InteractiveElementMouseOutMessage; TooltipManager.hide(); return true; break; case msg is ShowAllNamesAction: if(Kernel.getWorker().contains(InfoEntitiesFrame)) { Kernel.getWorker().removeFrame(this._infoEntitiesFrame); KernelEventsManager.getInstance().processCallback(HookList.ShowPlayersNames,false); } else { Kernel.getWorker().addFrame(this._infoEntitiesFrame); KernelEventsManager.getInstance().processCallback(HookList.ShowPlayersNames,true); } return true; case msg is ShowEntitiesTooltipsAction: seta = msg as ShowEntitiesTooltipsAction; _entitiesTooltipsFrame.triggeredByShortcut = seta.fromShortcut; if(Kernel.getWorker().contains(EntitiesTooltipsFrame)) { Kernel.getWorker().removeFrame(_entitiesTooltipsFrame); } else if(StageShareManager.isActive && !(!_entitiesTooltipsFrame.triggeredByShortcut && !this._mouseDown)) { if(Kernel.getWorker().contains(RoleplayEntitiesFrame)) { Kernel.getWorker().addFrame(_entitiesTooltipsFrame); } else { Kernel.getWorker().addEventListener(FramePushedEvent.EVENT_FRAME_PUSHED,this.onFramePushed); } } return true; case msg is ShowFightPositionsAction: sfpa = msg as ShowFightPositionsAction; sf = Kernel.getWorker().getFrame(ShortcutsFrame) as ShortcutsFrame; if(this._fightPositionsVisible) { this.removeFightPositions(); } else if(StageShareManager.isActive && (sfpa.fromShortcut && sf.heldShortcuts.indexOf(""showFightPositions"") != -1 || this._mouseDown)) { this.showFightPositions(); } return true; case msg is MouseDownMessage: this._mouseDown = true; break; case msg is MouseUpMessage: this._mouseDown = false; mum = msg as MouseUpMessage; sf = Kernel.getWorker().getFrame(ShortcutsFrame) as ShortcutsFrame; if(sf.heldShortcuts.indexOf(""showEntitiesTooltips"") == -1 && Kernel.getWorker().contains(EntitiesTooltipsFrame)) { Kernel.getWorker().removeFrame(_entitiesTooltipsFrame); } else if(sf.heldShortcuts.indexOf(""showFightPositions"") == -1 && this._fightPositionsVisible) { this.removeFightPositions(); } } return false; } private function showFightPositions() : void { if(this._fightPositions) { this.displayZone(FightPreparationFrame.SELECTION_CHALLENGER,this._fightPositions.positionsForChallengers,FightPreparationFrame.COLOR_CHALLENGER,FightPreparationFrame.PLAYER_TEAM_ALPHA); this.displayZone(FightPreparationFrame.SELECTION_DEFENDER,this._fightPositions.positionsForDefenders,FightPreparationFrame.COLOR_DEFENDER,FightPreparationFrame.ENEMY_TEAM_ALPHA); this._fightPositionsVisible = true; KernelEventsManager.getInstance().processCallback(HookList.ShowFightPositions,this._fightPositionsVisible); } } private function removeFightPositions() : void { var sc:Selection = SelectionManager.getInstance().getSelection(FightPreparationFrame.SELECTION_CHALLENGER); if(sc) { sc.remove(); } var sd:Selection = SelectionManager.getInstance().getSelection(FightPreparationFrame.SELECTION_DEFENDER); if(sd) { sd.remove(); } this._fightPositionsVisible = false; KernelEventsManager.getInstance().processCallback(HookList.ShowFightPositions,this._fightPositionsVisible); } private function displayZone(name:String, cells:Vector., color:Color, alpha:Number = 1.0) : void { var s:Selection = new Selection(); var strata:uint = !!Atouin.getInstance().options.getOption(""transparentOverlayMode"") ? uint(PlacementStrataEnums.STRATA_HIGHEST_OF_DOOM) : uint(PlacementStrataEnums.STRATA_AREA); s.renderer = new ZoneDARenderer(strata,alpha); s.color = color; s.zone = new Custom(cells); (s.renderer as ZoneDARenderer).currentStrata = strata; SelectionManager.getInstance().addSelection(s,name); SelectionManager.getInstance().update(name,0,true); } public function pulled() : Boolean { StageShareManager.stage.removeEventListener(Event.DEACTIVATE,this.onWindowDeactivate); Mouse.show(); LinkedCursorSpriteManager.getInstance().removeItem(""changeMapCursor""); CursorSpriteManager.resetCursor(); FrustumManager.getInstance().setBorderInteraction(false); if(this._fightPositionsVisible) { this.removeFightPositions(); } return true; } private function onFramePushed(pEvent:FramePushedEvent) : void { var shortcutsFrame:ShortcutsFrame = null; if(pEvent.frame is RoleplayEntitiesFrame) { pEvent.currentTarget.removeEventListener(FramePushedEvent.EVENT_FRAME_PUSHED,this.onFramePushed); shortcutsFrame = Kernel.getWorker().getFrame(ShortcutsFrame) as ShortcutsFrame; if(shortcutsFrame.heldShortcuts.indexOf(""showEntitiesTooltips"") != -1 && !Kernel.getWorker().contains(EntitiesTooltipsFrame)) { Kernel.getWorker().addFrame(_entitiesTooltipsFrame); } } } private function onEntityAnimRendered(pEvent:TiphonEvent) : void { var ac:AnimatedCharacter = pEvent.currentTarget as AnimatedCharacter; ac.removeEventListener(TiphonEvent.RENDER_SUCCEED,this.onEntityAnimRendered); var tooltipData:Object = this._entityTooltipData[ac]; TooltipManager.show(tooltipData.data,ac.absoluteBounds,UiModuleManager.getInstance().getModule(""Ankama_Tooltips""),false,tooltipData.name,LocationEnum.POINT_BOTTOM,LocationEnum.POINT_TOP,tooltipData.tooltipOffset,true,tooltipData.tooltipMaker,null,null,tooltipData.cacheName,false,StrataEnum.STRATA_WORLD,this.sysApi.getCurrentZoom()); delete this._entityTooltipData[ac]; } private function displayCursor(type:int, pEnable:Boolean = true) : void { if(type == -1) { CursorSpriteManager.resetCursor(); return; } if(PlayedCharacterManager.getInstance().state != PlayerLifeStatusEnum.STATUS_ALIVE_AND_KICKING) { return; } var cursorSprite:Sprite = RoleplayInteractivesFrame.getCursor(type,pEnable); CursorSpriteManager.displaySpecificCursor(""interactiveCursor"" + type,cursorSprite); } private function onWhisperMessage(playerName:String) : void { KernelEventsManager.getInstance().processCallback(ChatHookList.ChatFocus,playerName); } private function onMerchantPlayerBuyClick(vendorId:Number, vendorCellId:uint) : void { var eohvrmsg:ExchangeOnHumanVendorRequestMessage = new ExchangeOnHumanVendorRequestMessage(); eohvrmsg.initExchangeOnHumanVendorRequestMessage(vendorId,vendorCellId); ConnectionsHandler.getConnection().send(eohvrmsg); } private function onInviteMenuClicked(playerName:String) : void { var invitemsg:PartyInvitationRequestMessage = new PartyInvitationRequestMessage(); var player_INVITEMSG:PlayerSearchCharacterNameInformation = new PlayerSearchCharacterNameInformation().initPlayerSearchCharacterNameInformation(playerName); invitemsg.initPartyInvitationRequestMessage(player_INVITEMSG); ConnectionsHandler.getConnection().send(invitemsg); } private function onMerchantHouseKickOff(cellId:uint) : void { var kickRequest:HouseKickIndoorMerchantRequestMessage = new HouseKickIndoorMerchantRequestMessage(); kickRequest.initHouseKickIndoorMerchantRequestMessage(cellId); ConnectionsHandler.getConnection().send(kickRequest); } private function onWindowDeactivate(pEvent:Event) : void { if(Kernel.getWorker().contains(EntitiesTooltipsFrame)) { Kernel.getWorker().removeFrame(_entitiesTooltipsFrame); } else if(this._fightPositionsVisible) { this.removeFightPositions(); } } } } ",16262,True,2831.0649297016216,median "CLASS zcl_abapgit_objects_program DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super. PUBLIC SECTION. TYPES: BEGIN OF ty_progdir, name TYPE progdir-name, state TYPE progdir-state, sqlx TYPE progdir-sqlx, edtx TYPE progdir-edtx, varcl TYPE progdir-varcl, dbapl TYPE progdir-dbapl, dbna TYPE progdir-dbna, clas TYPE progdir-clas, type TYPE progdir-type, occurs TYPE progdir-occurs, subc TYPE progdir-subc, appl TYPE progdir-appl, secu TYPE progdir-secu, cnam TYPE progdir-cnam, cdat TYPE progdir-cdat, unam TYPE progdir-unam, udat TYPE progdir-udat, vern TYPE progdir-vern, levl TYPE progdir-levl, rstat TYPE progdir-rstat, rmand TYPE progdir-rmand, rload TYPE progdir-rload, fixpt TYPE progdir-fixpt, sset TYPE progdir-sset, sdate TYPE progdir-sdate, stime TYPE progdir-stime, idate TYPE progdir-idate, itime TYPE progdir-itime, ldbname TYPE progdir-ldbname, uccheck TYPE progdir-uccheck, END OF ty_progdir. METHODS serialize_program IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_output OPTIONAL is_item TYPE zif_abapgit_definitions=>ty_item io_files TYPE REF TO zcl_abapgit_objects_files iv_program TYPE programm OPTIONAL iv_extra TYPE clike OPTIONAL RAISING zcx_abapgit_exception. METHODS read_progdir IMPORTING iv_program TYPE programm RETURNING VALUE(rs_progdir) TYPE ty_progdir. METHODS deserialize_program IMPORTING is_progdir TYPE ty_progdir it_source TYPE abaptxt255_tab it_tpool TYPE textpool_table iv_package TYPE devclass RAISING zcx_abapgit_exception. PROTECTED SECTION. TYPES: ty_spaces_tt TYPE STANDARD TABLE OF i WITH DEFAULT KEY . TYPES: BEGIN OF ty_dynpro, header TYPE rpy_dyhead, containers TYPE dycatt_tab, fields TYPE dyfatc_tab, flow_logic TYPE swydyflow, spaces TYPE ty_spaces_tt, END OF ty_dynpro . TYPES: ty_dynpro_tt TYPE STANDARD TABLE OF ty_dynpro WITH DEFAULT KEY . TYPES: BEGIN OF ty_cua, adm TYPE rsmpe_adm, sta TYPE STANDARD TABLE OF rsmpe_stat WITH DEFAULT KEY, fun TYPE STANDARD TABLE OF rsmpe_funt WITH DEFAULT KEY, men TYPE STANDARD TABLE OF rsmpe_men WITH DEFAULT KEY, mtx TYPE STANDARD TABLE OF rsmpe_mnlt WITH DEFAULT KEY, act TYPE STANDARD TABLE OF rsmpe_act WITH DEFAULT KEY, but TYPE STANDARD TABLE OF rsmpe_but WITH DEFAULT KEY, pfk TYPE STANDARD TABLE OF rsmpe_pfk WITH DEFAULT KEY, set TYPE STANDARD TABLE OF rsmpe_staf WITH DEFAULT KEY, doc TYPE STANDARD TABLE OF rsmpe_atrt WITH DEFAULT KEY, tit TYPE STANDARD TABLE OF rsmpe_titt WITH DEFAULT KEY, biv TYPE STANDARD TABLE OF rsmpe_buts WITH DEFAULT KEY, END OF ty_cua . METHODS serialize_dynpros IMPORTING !iv_program_name TYPE programm RETURNING VALUE(rt_dynpro) TYPE ty_dynpro_tt RAISING zcx_abapgit_exception . METHODS serialize_cua IMPORTING !iv_program_name TYPE programm RETURNING VALUE(rs_cua) TYPE ty_cua RAISING zcx_abapgit_exception . METHODS deserialize_dynpros IMPORTING !it_dynpros TYPE ty_dynpro_tt RAISING zcx_abapgit_exception . METHODS deserialize_textpool IMPORTING !iv_program TYPE programm !it_tpool TYPE textpool_table !iv_language TYPE langu OPTIONAL !iv_is_include TYPE abap_bool DEFAULT abap_false RAISING zcx_abapgit_exception . METHODS deserialize_cua IMPORTING !iv_program_name TYPE programm !is_cua TYPE ty_cua RAISING zcx_abapgit_exception . METHODS is_any_dynpro_locked IMPORTING !iv_program TYPE programm RETURNING VALUE(rv_is_any_dynpro_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_cua_locked IMPORTING !iv_program TYPE programm RETURNING VALUE(rv_is_cua_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_text_locked IMPORTING !iv_program TYPE programm RETURNING VALUE(rv_is_text_locked) TYPE abap_bool RAISING zcx_abapgit_exception . CLASS-METHODS add_tpool IMPORTING !it_tpool TYPE textpool_table RETURNING VALUE(rt_tpool) TYPE zif_abapgit_definitions=>ty_tpool_tt . CLASS-METHODS read_tpool IMPORTING !it_tpool TYPE zif_abapgit_definitions=>ty_tpool_tt RETURNING VALUE(rt_tpool) TYPE zif_abapgit_definitions=>ty_tpool_tt . PRIVATE SECTION. METHODS: condense_flow EXPORTING et_spaces TYPE ty_spaces_tt CHANGING ct_flow TYPE swydyflow, uncondense_flow IMPORTING it_flow TYPE swydyflow it_spaces TYPE ty_spaces_tt RETURNING VALUE(rt_flow) TYPE swydyflow. CLASS-METHODS auto_correct_cua_adm IMPORTING is_cua TYPE zcl_abapgit_objects_program=>ty_cua CHANGING cs_adm TYPE rsmpe_adm. ENDCLASS. CLASS ZCL_ABAPGIT_OBJECTS_PROGRAM IMPLEMENTATION. METHOD add_tpool. FIELD-SYMBOLS: LIKE LINE OF it_tpool, LIKE LINE OF rt_tpool. LOOP AT it_tpool ASSIGNING . APPEND INITIAL LINE TO rt_tpool ASSIGNING . MOVE-CORRESPONDING TO . IF -id = 'S'. -split = -entry. -entry = -entry+8. ENDIF. ENDLOOP. ENDMETHOD. METHOD auto_correct_cua_adm. "" issue #1807 automatic correction of CUA interfaces saved incorrectly in the past (ADM was not saved in the XML) CONSTANTS: lc_num_n_space TYPE string VALUE ' 0123456789', lc_num_only TYPE string VALUE '0123456789'. FIELD-SYMBOLS: TYPE rsmpe_pfk, TYPE rsmpe_act, TYPE rsmpe_men. IF cs_adm IS NOT INITIAL AND ( cs_adm-actcode CO lc_num_n_space AND cs_adm-mencode CO lc_num_n_space AND cs_adm-pfkcode CO lc_num_n_space ). ""Check performed in form check_adm of include LSMPIF03 RETURN. ENDIF. LOOP AT is_cua-act ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO lc_num_only. cs_adm-actcode = -code. ENDIF. ENDLOOP. LOOP AT is_cua-men ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO lc_num_only. cs_adm-mencode = -code. ENDIF. ENDLOOP. LOOP AT is_cua-pfk ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO lc_num_only. cs_adm-pfkcode = -code. ENDIF. ENDLOOP. ENDMETHOD. METHOD condense_flow. DATA: lv_spaces LIKE LINE OF et_spaces. FIELD-SYMBOLS: LIKE LINE OF ct_flow. CLEAR et_spaces. LOOP AT ct_flow ASSIGNING . lv_spaces = 0. WHILE NOT -line IS INITIAL AND -line(1) = space. lv_spaces = lv_spaces + 1. -line = -line+1. ENDWHILE. APPEND lv_spaces TO et_spaces. ENDLOOP. ENDMETHOD. METHOD deserialize_cua. DATA: ls_tr_key TYPE trkey, ls_adm TYPE rsmpe_adm. IF lines( is_cua-sta ) = 0 AND lines( is_cua-fun ) = 0 AND lines( is_cua-men ) = 0 AND lines( is_cua-mtx ) = 0 AND lines( is_cua-act ) = 0 AND lines( is_cua-but ) = 0 AND lines( is_cua-pfk ) = 0 AND lines( is_cua-set ) = 0 AND lines( is_cua-doc ) = 0 AND lines( is_cua-tit ) = 0 AND lines( is_cua-biv ) = 0. RETURN. ENDIF. SELECT SINGLE devclass INTO ls_tr_key-devclass FROM tadir WHERE pgmid = 'R3TR' AND object = ms_item-obj_type AND obj_name = ms_item-obj_name. ""#EC CI_GENBUFF IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'not found in tadir' ). ENDIF. ls_tr_key-obj_type = ms_item-obj_type. ls_tr_key-obj_name = ms_item-obj_name. ls_tr_key-sub_type = 'CUAD'. ls_tr_key-sub_name = iv_program_name. ls_adm = is_cua-adm. auto_correct_cua_adm( EXPORTING is_cua = is_cua CHANGING cs_adm = ls_adm ). sy-tcode = 'SE41' ##write_ok. "" evil hack, workaround to handle fixes in note 2159455 CALL FUNCTION 'RS_CUA_INTERNAL_WRITE' EXPORTING program = iv_program_name language = mv_language tr_key = ls_tr_key adm = ls_adm state = 'I' TABLES sta = is_cua-sta fun = is_cua-fun men = is_cua-men mtx = is_cua-mtx act = is_cua-act but = is_cua-but pfk = is_cua-pfk set = is_cua-set doc = is_cua-doc tit = is_cua-tit biv = is_cua-biv EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc <> 0. * if moving code from SAPlink, see https://github.com/larshp/abapGit/issues/562 zcx_abapgit_exception=>raise( |Error from RS_CUA_INTERNAL_WRITE. Subrc = { sy-subrc }| ). ENDIF. zcl_abapgit_objects_activation=>add( iv_type = 'CUAD' iv_name = iv_program_name ). ENDMETHOD. METHOD deserialize_dynpros. CONSTANTS lc_rpyty_force_off TYPE char01 VALUE '/' ##NO_TEXT. DATA: lv_name TYPE dwinactiv-obj_name, ls_dynpro LIKE LINE OF it_dynpros. FIELD-SYMBOLS: TYPE rpy_dyfatc. * ls_dynpro is changed by the function module, a field-symbol will cause * the program to dump since it_dynpros cannot be changed LOOP AT it_dynpros INTO ls_dynpro. ls_dynpro-flow_logic = uncondense_flow( it_flow = ls_dynpro-flow_logic it_spaces = ls_dynpro-spaces ). LOOP AT ls_dynpro-fields ASSIGNING . * if the DDIC element has a PARAMETER_ID and the flag ""from_dict"" is active * the import will enable the SET-/GET_PARAM flag. In this case: ""force off"" IF -param_id IS NOT INITIAL AND -from_dict = abap_true. IF -set_param IS INITIAL. -set_param = lc_rpyty_force_off. ENDIF. IF -get_param IS INITIAL. -get_param = lc_rpyty_force_off. ENDIF. ENDIF. * If the previous conditions are met the value 'F' will be taken over * during de-serialization potentially overlapping other fields in the screen, * we set the tag to the correct value 'X' IF -type = 'CHECK' AND -from_dict = abap_true AND -text IS INITIAL AND -modific IS INITIAL. -modific = 'X'. ENDIF. ""fix for issue #2747: IF -foreignkey IS INITIAL. -foreignkey = lc_rpyty_force_off. ENDIF. ENDLOOP. CALL FUNCTION 'RPY_DYNPRO_INSERT' EXPORTING header = ls_dynpro-header suppress_exist_checks = abap_true TABLES containers = ls_dynpro-containers fields_to_containers = ls_dynpro-fields flow_logic = ls_dynpro-flow_logic EXCEPTIONS cancelled = 1 already_exists = 2 program_not_exists = 3 not_executed = 4 missing_required_field = 5 illegal_field_value = 6 field_not_allowed = 7 not_generated = 8 illegal_field_position = 9 OTHERS = 10. IF sy-subrc <> 2 AND sy-subrc <> 0. zcx_abapgit_exception=>raise( |Error from RPY_DYNPRO_INSERT: { sy-subrc }| ). ENDIF. * todo, RPY_DYNPRO_UPDATE? CONCATENATE ls_dynpro-header-program ls_dynpro-header-screen INTO lv_name RESPECTING BLANKS. ASSERT NOT lv_name IS INITIAL. zcl_abapgit_objects_activation=>add( iv_type = 'DYNP' iv_name = lv_name ). ENDLOOP. ENDMETHOD. METHOD deserialize_program. DATA: lv_exists TYPE abap_bool, lv_progname TYPE reposrc-progname, ls_tpool LIKE LINE OF it_tpool, lv_title TYPE rglif-title, ls_progdir_new TYPE progdir. FIELD-SYMBOLS: TYPE any. CALL FUNCTION 'RS_CORR_INSERT' EXPORTING object = is_progdir-name object_class = 'ABAP' devclass = iv_package master_language = mv_language mode = 'I' suppress_dialog = abap_true EXCEPTIONS cancelled = 1 permission_failure = 2 unknown_objectclass = 3 OTHERS = 4. IF sy-subrc = 1. zcx_abapgit_exception=>raise( |Error from RS_CORR_INSERT, Cancelled, { sy-msgid }, { sy-msgno }| ). ELSEIF sy-subrc <> 0. zcx_abapgit_exception=>raise( |Error from RS_CORR_INSERT, { sy-msgid }, { sy-msgno }| ). ENDIF. READ TABLE it_tpool INTO ls_tpool WITH KEY id = 'R'. IF sy-subrc = 0. * there is a bug in RPY_PROGRAM_UPDATE, the header line of TTAB is not * cleared, so the title length might be inherited from a different program. ASSIGN ('(SAPLSIFP)TTAB') TO . IF sy-subrc = 0. CLEAR . ENDIF. lv_title = ls_tpool-entry. ENDIF. SELECT SINGLE progname FROM reposrc INTO lv_progname WHERE progname = is_progdir-name AND r3state = 'A'. IF sy-subrc = 0. lv_exists = abap_true. ELSE. lv_exists = abap_false. ENDIF. IF lv_exists = abap_true. zcl_abapgit_language=>set_current_language( mv_language ). CALL FUNCTION 'RPY_PROGRAM_UPDATE' EXPORTING program_name = is_progdir-name title_string = lv_title save_inactive = 'I' TABLES source_extended = it_source EXCEPTIONS cancelled = 1 permission_error = 2 not_found = 3 OTHERS = 4. IF sy-subrc <> 0. zcl_abapgit_language=>restore_login_language( ). IF sy-msgid = 'EU' AND sy-msgno = '510'. zcx_abapgit_exception=>raise( 'User is currently editing program' ). ELSE. zcx_abapgit_exception=>raise( |PROG { is_progdir-name }, updating error: { sy-msgid } { sy-msgno }| ). ENDIF. ENDIF. zcl_abapgit_language=>restore_login_language( ). ELSEIF strlen( is_progdir-name ) > 30. * function module RPY_PROGRAM_INSERT cannot handle function group includes "" special treatment for extensions "" if the program name exceeds 30 characters it is not a usual "" ABAP program but might be some extension, which requires the internal "" addition EXTENSION TYPE, see "" http://help.sap.com/abapdocu_751/en/abapinsert_report_internal.htm#!ABAP_ADDITION_1@1@ "" This e.g. occurs in case of transportable Code Inspector variants (ending with ===VC) INSERT REPORT is_progdir-name FROM it_source STATE 'I' EXTENSION TYPE is_progdir-name+30. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT REPORT .. EXTENSION TYPE' ). ENDIF. ELSE. INSERT REPORT is_progdir-name FROM it_source STATE 'I' PROGRAM TYPE is_progdir-subc. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT REPORT' ). ENDIF. ENDIF. IF NOT it_tpool[] IS INITIAL. INSERT TEXTPOOL is_progdir-name FROM it_tpool LANGUAGE mv_language STATE 'I'. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT TEXTPOOL' ). ENDIF. ENDIF. CALL FUNCTION 'READ_PROGDIR' EXPORTING i_progname = is_progdir-name i_state = 'I' IMPORTING e_progdir = ls_progdir_new EXCEPTIONS not_exists = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |not found in PROGDIR. Subrc = { sy-subrc }| ). ENDIF. * todo, package? ls_progdir_new-ldbname = is_progdir-ldbname. ls_progdir_new-dbna = is_progdir-dbna. ls_progdir_new-dbapl = is_progdir-dbapl. ls_progdir_new-rload = is_progdir-rload. ls_progdir_new-fixpt = is_progdir-fixpt. ls_progdir_new-varcl = is_progdir-varcl. ls_progdir_new-appl = is_progdir-appl. ls_progdir_new-rstat = is_progdir-rstat. CALL FUNCTION 'UPDATE_PROGDIR' EXPORTING i_progdir = ls_progdir_new i_progname = ls_progdir_new-name i_state = ls_progdir_new-state EXCEPTIONS not_executed = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |PROG, error inserting. Subrc = { sy-subrc }| ). ENDIF. SELECT SINGLE * FROM progdir INTO ls_progdir_new WHERE name = ls_progdir_new-name AND state = ls_progdir_new-state. IF sy-subrc = 0 AND is_progdir-varcl = space AND ls_progdir_new-varcl = abap_true. * function module UPDATE_PROGDIR does not update VARCL UPDATE progdir SET varcl = is_progdir-varcl WHERE name = ls_progdir_new-name AND state = ls_progdir_new-state. ""#EC CI_SUBRC ENDIF. zcl_abapgit_objects_activation=>add( iv_type = 'REPS' iv_name = is_progdir-name ). ENDMETHOD. METHOD deserialize_textpool. DATA lv_language TYPE langu. DATA lv_state TYPE c. DATA lv_delete TYPE abap_bool. IF iv_language IS INITIAL. lv_language = mv_language. ELSE. lv_language = iv_language. ENDIF. IF lv_language = mv_language. lv_state = 'I'. ""Textpool in master language needs to be activated ELSE. lv_state = 'A'. ""Translations are always active ENDIF. IF it_tpool IS INITIAL. IF iv_is_include = abap_false OR lv_state = 'A'. DELETE TEXTPOOL iv_program ""Remove initial description from textpool if LANGUAGE iv_program ""original program does not have a textpool STATE lv_state. lv_delete = abap_true. ELSE. INSERT TEXTPOOL iv_program ""In case of includes: Deletion of textpool in FROM it_tpool ""master language cannot be activated because LANGUAGE lv_language ""this woul activate the deletion of the textpool STATE lv_state. ""of the mail program -> insert empty textpool ENDIF. ELSE. IF lines( it_tpool ) = 1 AND lv_language = mv_language. READ TABLE it_tpool WITH KEY id = 'R' TRANSPORTING NO FIELDS. IF sy-subrc = 0. RETURN. ""No action because description in master language is already there ENDIF. ENDIF. INSERT TEXTPOOL iv_program FROM it_tpool LANGUAGE lv_language STATE lv_state. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT TEXTPOOL' ). ENDIF. ENDIF. IF lv_state = 'I'. ""Textpool in master language needs to be activated zcl_abapgit_objects_activation=>add( iv_type = 'REPT' iv_name = iv_program iv_delete = lv_delete ). ENDIF. ENDMETHOD. METHOD is_any_dynpro_locked. DATA: lt_dynpros TYPE zcl_abapgit_objects_program=>ty_dynpro_tt, lv_object TYPE seqg3-garg. FIELD-SYMBOLS: TYPE zcl_abapgit_objects_program=>ty_dynpro. lt_dynpros = serialize_dynpros( iv_program ). LOOP AT lt_dynpros ASSIGNING . lv_object = |{ -header-screen }{ -header-program }|. IF exists_a_lock_entry_for( iv_lock_object = 'ESCRP' iv_argument = lv_object ) = abap_true. rv_is_any_dynpro_locked = abap_true. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD is_cua_locked. DATA: lv_object TYPE eqegraarg. lv_object = |CU{ iv_program }|. OVERLAY lv_object WITH ' '. lv_object = lv_object && '*'. rv_is_cua_locked = exists_a_lock_entry_for( iv_lock_object = 'ESCUAPAINT' iv_argument = lv_object ). ENDMETHOD. METHOD is_text_locked. DATA: lv_object TYPE eqegraarg. lv_object = |*{ iv_program }|. rv_is_text_locked = exists_a_lock_entry_for( iv_lock_object = 'EABAPTEXTE' iv_argument = lv_object ). ENDMETHOD. METHOD read_progdir. DATA: ls_sapdir TYPE progdir. CALL FUNCTION 'READ_PROGDIR' EXPORTING i_progname = iv_program i_state = 'A' IMPORTING e_progdir = ls_sapdir. MOVE-CORRESPONDING ls_sapdir TO rs_progdir. CLEAR: rs_progdir-edtx, rs_progdir-cnam, rs_progdir-cdat, rs_progdir-unam, rs_progdir-udat, rs_progdir-levl, rs_progdir-vern, rs_progdir-rmand, rs_progdir-sdate, rs_progdir-stime, rs_progdir-idate, rs_progdir-itime, rs_progdir-varcl, rs_progdir-state. ENDMETHOD. METHOD read_tpool. FIELD-SYMBOLS: LIKE LINE OF it_tpool, LIKE LINE OF rt_tpool. LOOP AT it_tpool ASSIGNING . APPEND INITIAL LINE TO rt_tpool ASSIGNING . MOVE-CORRESPONDING TO . IF -id = 'S'. CONCATENATE -split -entry INTO -entry RESPECTING BLANKS. ENDIF. ENDLOOP. ENDMETHOD. METHOD serialize_cua. CALL FUNCTION 'RS_CUA_INTERNAL_FETCH' EXPORTING program = iv_program_name language = mv_language state = 'A' IMPORTING adm = rs_cua-adm TABLES sta = rs_cua-sta fun = rs_cua-fun men = rs_cua-men mtx = rs_cua-mtx act = rs_cua-act but = rs_cua-but pfk = rs_cua-pfk set = rs_cua-set doc = rs_cua-doc tit = rs_cua-tit biv = rs_cua-biv EXCEPTIONS not_found = 1 unknown_version = 2 OTHERS = 3. IF sy-subrc > 1. zcx_abapgit_exception=>raise( |Error from RS_CUA_INTERNAL_FETCH, { sy-subrc }| ). ENDIF. ENDMETHOD. METHOD serialize_dynpros. DATA: ls_header TYPE rpy_dyhead, lt_containers TYPE dycatt_tab, lt_fields_to_containers TYPE dyfatc_tab, lt_flow_logic TYPE swydyflow, lt_d020s TYPE TABLE OF d020s, lt_fieldlist_int TYPE TABLE OF d021s. ""internal format FIELD-SYMBOLS: LIKE LINE OF lt_d020s, TYPE scrpostyle, LIKE LINE OF lt_containers, LIKE LINE OF lt_fields_to_containers, LIKE LINE OF rt_dynpro, LIKE LINE OF lt_fieldlist_int. ""#2746: relevant flag values (taken from include MSEUSBIT) CONSTANTS: lc_flg1ddf TYPE x VALUE '20', lc_flg3fku TYPE x VALUE '08', lc_flg3for TYPE x VALUE '04', lc_flg3fdu TYPE x VALUE '02'. CALL FUNCTION 'RS_SCREEN_LIST' EXPORTING dynnr = '' progname = iv_program_name TABLES dynpros = lt_d020s EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc = 2. zcx_abapgit_exception=>raise( |Error from RS_SCREEN_LIST. Subrc = { sy-subrc }| ). ENDIF. SORT lt_d020s BY dnum ASCENDING. * loop dynpros and skip generated selection screens LOOP AT lt_d020s ASSIGNING WHERE type <> 'S' AND type <> 'W' AND type <> 'J' AND NOT dnum IS INITIAL. CALL FUNCTION 'RPY_DYNPRO_READ' EXPORTING progname = iv_program_name dynnr = -dnum IMPORTING header = ls_header TABLES containers = lt_containers fields_to_containers = lt_fields_to_containers flow_logic = lt_flow_logic EXCEPTIONS cancelled = 1 not_found = 2 permission_error = 3 OTHERS = 4. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |Error while reading dynpro: { sy-subrc }| ). ENDIF. ""#2746: we need the dynpro fields in internal format: FREE lt_fieldlist_int. CALL FUNCTION 'RPY_DYNPRO_READ_NATIVE' EXPORTING progname = iv_program_name dynnr = -dnum TABLES fieldlist = lt_fieldlist_int. LOOP AT lt_fields_to_containers ASSIGNING . * output style is a NUMC field, the XML conversion will fail if it contains invalid value * field does not exist in all versions ASSIGN COMPONENT 'OUTPUTSTYLE' OF STRUCTURE TO . IF sy-subrc = 0 AND = ' '. CLEAR . ENDIF. ""2746: we apply the same logic as in SAPLWBSCREEN ""for setting or unsetting the foreignkey field: UNASSIGN . READ TABLE lt_fieldlist_int ASSIGNING WITH KEY fnam = -name. IF IS ASSIGNED. IF -flg1 O lc_flg1ddf AND -flg3 O lc_flg3for AND -flg3 Z lc_flg3fdu AND -flg3 Z lc_flg3fku. -foreignkey = 'X'. ELSE. CLEAR -foreignkey. ENDIF. ENDIF. ENDLOOP. LOOP AT lt_containers ASSIGNING . IF -c_resize_v = abap_false. CLEAR -c_line_min. ENDIF. IF -c_resize_h = abap_false. CLEAR -c_coln_min. ENDIF. ENDLOOP. APPEND INITIAL LINE TO rt_dynpro ASSIGNING . -header = ls_header. -containers = lt_containers. -fields = lt_fields_to_containers. condense_flow( IMPORTING et_spaces = -spaces CHANGING ct_flow = lt_flow_logic ). -flow_logic = lt_flow_logic. ENDLOOP. ENDMETHOD. METHOD serialize_program. DATA: ls_progdir TYPE ty_progdir, lv_program_name TYPE programm, lt_dynpros TYPE ty_dynpro_tt, ls_cua TYPE ty_cua, lt_source TYPE TABLE OF abaptxt255, lt_tpool TYPE textpool_table, ls_tpool LIKE LINE OF lt_tpool, lo_xml TYPE REF TO zcl_abapgit_xml_output. IF iv_program IS INITIAL. lv_program_name = is_item-obj_name. ELSE. lv_program_name = iv_program. ENDIF. zcl_abapgit_language=>set_current_language( mv_language ). CALL FUNCTION 'RPY_PROGRAM_READ' EXPORTING program_name = lv_program_name with_lowercase = abap_true TABLES source_extended = lt_source textelements = lt_tpool EXCEPTIONS cancelled = 1 not_found = 2 permission_error = 3 OTHERS = 4. IF sy-subrc = 2. zcl_abapgit_language=>restore_login_language( ). RETURN. ELSEIF sy-subrc <> 0. zcl_abapgit_language=>restore_login_language( ). zcx_abapgit_exception=>raise( |Error reading program with RPY_PROGRAM_READ. Subrc = { sy-subrc }| ). ENDIF. zcl_abapgit_language=>restore_login_language( ). ls_progdir = read_progdir( lv_program_name ). IF io_xml IS BOUND. lo_xml = io_xml. ELSE. CREATE OBJECT lo_xml. ENDIF. lo_xml->add( iv_name = 'PROGDIR' ig_data = ls_progdir ). IF ls_progdir-subc = '1' OR ls_progdir-subc = 'M'. lt_dynpros = serialize_dynpros( lv_program_name ). lo_xml->add( iv_name = 'DYNPROS' ig_data = lt_dynpros ). ls_cua = serialize_cua( lv_program_name ). IF NOT ls_cua IS INITIAL. lo_xml->add( iv_name = 'CUA' ig_data = ls_cua ). ENDIF. ENDIF. READ TABLE lt_tpool WITH KEY id = 'R' INTO ls_tpool. IF sy-subrc = 0 AND ls_tpool-key = '' AND ls_tpool-length = 0. DELETE lt_tpool INDEX sy-tabix. ENDIF. lo_xml->add( iv_name = 'TPOOL' ig_data = add_tpool( lt_tpool ) ). IF NOT io_xml IS BOUND. io_files->add_xml( iv_extra = iv_extra io_xml = lo_xml ). ENDIF. io_files->add_abap( iv_extra = iv_extra it_abap = lt_source ). ENDMETHOD. METHOD uncondense_flow. DATA: lv_spaces LIKE LINE OF it_spaces. FIELD-SYMBOLS: LIKE LINE OF it_flow, LIKE LINE OF rt_flow. LOOP AT it_flow ASSIGNING . APPEND INITIAL LINE TO rt_flow ASSIGNING . -line = -line. READ TABLE it_spaces INDEX sy-tabix INTO lv_spaces. IF sy-subrc = 0. SHIFT -line RIGHT BY lv_spaces PLACES IN CHARACTER MODE. ENDIF. ENDLOOP. ENDMETHOD. ENDCLASS. ",8198,False,1673.7352926476171,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.controls { import flash.display.DisplayObject; import flash.events.Event; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.text.TextLineMetrics; import flash.ui.Keyboard; import mx.collections.ArrayCollection; import mx.collections.CursorBookmark; import mx.controls.dataGridClasses.DataGridListData; import mx.controls.listClasses.BaseListData; import mx.controls.listClasses.IDropInListItemRenderer; import mx.controls.listClasses.IListItemRenderer; import mx.controls.listClasses.ListBase; import mx.controls.listClasses.ListData; import mx.core.ClassFactory; import mx.core.EdgeMetrics; import mx.core.IDataRenderer; import mx.core.IFactory; import mx.core.LayoutDirection; import mx.core.ScrollPolicy; import mx.core.UIComponent; import mx.core.UIComponentGlobals; import mx.core.mx_internal; import mx.effects.Tween; import mx.events.CollectionEvent; import mx.events.CollectionEventKind; import mx.events.DropdownEvent; import mx.events.FlexEvent; import mx.events.FlexMouseEvent; import mx.events.InterManagerRequest; import mx.events.ListEvent; import mx.events.SandboxMouseEvent; import mx.events.ScrollEvent; import mx.events.ScrollEventDetail; import mx.managers.ISystemManager; import mx.managers.PopUpManager; import mx.styles.CSSStyleDeclaration; import mx.utils.MatrixUtil; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched when the ComboBox contents changes as a result of user * interaction, when the selectedIndex or * selectedItem property changes, and, if the ComboBox control * is editable, each time a keystroke is entered in the box. * * @eventType mx.events.ListEvent.CHANGE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""change"", type=""mx.events.ListEvent"")] /** * Dispatched when the drop-down list is dismissed for any reason such when * the user: *
      *
    • selects an item in the drop-down list
    • *
    • clicks outside of the drop-down list
    • *
    • clicks the drop-down button while the drop-down list is * displayed
    • *
    • presses the ESC key while the drop-down list is displayed
    • *
    * * @eventType mx.events.DropdownEvent.CLOSE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""close"", type=""mx.events.DropdownEvent"")] /** * Dispatched when the data property changes. * *

    When you use a component as an item renderer, * the data property contains an item from the * dataProvider. * You can listen for this event and update the component * when the data property changes.

    * * @eventType mx.events.FlexEvent.DATA_CHANGE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dataChange"", type=""mx.events.FlexEvent"")] /** * Dispatched if the editable property * is set to true and the user presses the Enter key * while typing in the editable text field. * * @eventType mx.events.FlexEvent.ENTER * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""enter"", type=""mx.events.FlexEvent"")] /** * Dispatched when user rolls the mouse out of a drop-down list item. * The event object's target property contains a reference * to the ComboBox and not the drop-down list. * * @eventType mx.events.ListEvent.ITEM_ROLL_OUT * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""itemRollOut"", type=""mx.events.ListEvent"")] /** * Dispatched when the user rolls the mouse over a drop-down list item. * The event object's target property contains a reference * to the ComboBox and not the drop-down list. * * @eventType mx.events.ListEvent.ITEM_ROLL_OVER * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""itemRollOver"", type=""mx.events.ListEvent"")] /** * Dispatched when the user clicks the drop-down button * to display the drop-down list. It is also dispatched if the user * uses the keyboard and types Ctrl-Down to open the drop-down. * * @eventType mx.events.DropdownEvent.OPEN * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""open"", type=""mx.events.DropdownEvent"")] /** * Dispatched when the user scrolls the ComboBox control's drop-down list. * * @eventType mx.events.ScrollEvent.SCROLL * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""scroll"", type=""mx.events.ScrollEvent"")] //-------------------------------------- // Styles //-------------------------------------- include ""../styles/metadata/FocusStyles.as"" include ""../styles/metadata/IconColorStyles.as"" include ""../styles/metadata/LeadingStyle.as"" include ""../styles/metadata/PaddingStyles.as"" include ""../styles/metadata/SkinStyles.as"" include ""../styles/metadata/TextStyles.as"" /** * The set of BackgroundColors for drop-down list rows in an alternating * pattern. * Value can be an Array of two of more colors. * If undefined then the rows will use the drop-down list's * backgroundColor style. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""alternatingItemColors"", type=""Array"", arrayType=""uint"", format=""Color"", inherit=""yes"")] /** * Width of the arrow button in pixels. * * The default value for the Halo theme is 22. * The default value for the Spark theme is 18. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""arrowButtonWidth"", type=""Number"", format=""Length"", inherit=""no"")] /** * The thickness of the border of the drop-down list, in pixels. * This value is overridden if you define * borderThickness when setting the * dropdownStyleName CSSStyleDeclaration. * * @default 1 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""borderThickness"", type=""Number"", format=""Length"", inherit=""no"")] /** * The length of the transition when the drop-down list closes, in milliseconds. * The default transition has the drop-down slide up into the ComboBox. * * The default value for the Halo theme is 250. * The default value for the Spark theme is 50. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""closeDuration"", type=""Number"", format=""Time"", inherit=""no"")] /** * An easing function to control the close transition. Easing functions can * be used to control the acceleration and deceleration of the transition. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""closeEasingFunction"", type=""Function"", inherit=""no"")] /** * The color of the border of the ComboBox. If undefined * the drop-down list will use its normal borderColor style. This style * is used by the validators to show the ComboBox in an error state. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dropdownBorderColor"", type=""uint"", format=""Color"", inherit=""yes"", theme=""halo"")] /** * The name of a CSSStyleDeclaration to be used by the drop-down list. This * allows you to control the appearance of the drop-down list or its item * renderers. * * [deprecated] * * @default ""comboDropDown"" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dropDownStyleName"", type=""String"", inherit=""no"", deprecatedReplacement=""dropdownStyleName"")] /** * The name of a CSSStyleDeclaration to be used by the drop-down list. This * allows you to control the appearance of the drop-down list or its item * renderers. * * @default ""comboDropdown"" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dropdownStyleName"", type=""String"", inherit=""no"")] /** * Length of the transition when the drop-down list opens, in milliseconds. * The default transition has the drop-down slide down from the ComboBox. * * The default value for the Halo theme is 250. * The default value for the Spark theme is 0. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""openDuration"", type=""Number"", format=""Time"", inherit=""no"")] /** * An easing function to control the open transition. Easing functions can * be used to control the acceleration and deceleration of the transition. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""openEasingFunction"", type=""Function"", inherit=""no"")] /** * Number of pixels between the control's bottom border * and the bottom of its content area. * When the editable property is true, * paddingTop and paddingBottom affect the size * of the ComboBox control, but do not affect the position of the editable text field. * * The default value for the Halo theme is 0. * The default value for the Spark theme is -2. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""paddingBottom"", type=""Number"", format=""Length"", inherit=""no"")] /** * Number of pixels between the control's top border * and the top of its content area. * When the editable property is true, * paddingTop and paddingBottom affect the size * of the ComboBox control, but do not affect the position of the editable text field. * * The default value for the Halo theme is 0. * The default value for the Spark theme is -1. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""paddingTop"", type=""Number"", format=""Length"", inherit=""no"")] /** * The rollOverColor of the drop-down list. * * The default value for the Halo theme is 0xB2E1FF. * The default value for the Spark theme is 0xCEDBEF. * * @see mx.controls.List * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""rollOverColor"", type=""uint"", format=""Color"", inherit=""yes"")] /** * The selectionColor of the drop-down list. * * The default value for the Halo theme is 0x7FCEFF. * The default value for the Spark theme is 0xA8C6EE. * * @see mx.controls.List * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""selectionColor"", type=""uint"", format=""Color"", inherit=""yes"")] /** * The selectionDuration of the drop-down list. * * @default 250 * * @see mx.controls.List * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""selectionDuration"", type=""uint"", format=""Time"", inherit=""no"")] /** * The selectionEasingFunction of the drop-down list. * * @default undefined * * @see mx.controls.List * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""selectionEasingFunction"", type=""Function"", inherit=""no"")] /** * The textRollOverColor of the drop-down list. * * The default value for the Halo theme is 0x2B333C. * The default value for the Spark theme is 0x000000. * * @see mx.controls.List * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""textRollOverColor"", type=""uint"", format=""Color"", inherit=""yes"")] /** * The textSelectedColor of the drop-down list. * * The default value for the Halo theme is 0x2B333C. * The default value for the Spark theme is 0x000000. * * @see mx.controls.List * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""textSelectedColor"", type=""uint"", format=""Color"", inherit=""yes"")] //-------------------------------------- // Other metadata //-------------------------------------- [AccessibilityClass(implementation=""mx.accessibility.ComboBoxAccImpl"")] [DataBindingInfo(""acceptedTypes"", ""{ dataProvider: { label: "String" } }"")] [DefaultBindingProperty(source=""selectedItem"", destination=""dataProvider"")] [DefaultProperty(""dataProvider"")] [DefaultTriggerEvent(""change"")] [IconFile(""ComboBox.png"")] [Alternative(replacement=""spark.components.DropDownList"", since=""4.0"")] [Alternative(replacement=""spark.components.ComboBox"", since=""4.0"")] /** * The ComboBox control contains a drop-down list * from which the user can select a single value. * Its functionality is very similar to that of the * SELECT form element in HTML. * The ComboBox can be editable, in which case * the user can type entries into the TextInput portion * of the ComboBox that are not in the list. * *

    The ComboBox control has the following default sizing * characteristics:

    * * * * * * * * * * * * * * * * * * * * * * * * * *
    CharacteristicDescription
    Default sizeWide enough to accommodate the longest entry in the * drop-down list in the display area of the main * control, plus the drop-down button. When the * drop-down list is not visible, the default height * is based on the label text size. * *

    The default drop-down list height is five rows, or * the number of entries in the drop-down list, whichever * is smaller. The default height of each entry in the * drop-down list is 22 pixels.

    Minimum size0 pixels.
    Maximum size5000 by 5000.
    dropdownWidthThe width of the ComboBox control.
    rowCount5 rows.
    * * @mxml * *

    The <mx:ComboBox> tag inherits all the tag attributes * of its superclass, and adds the following tag attributes:

    * *
     *  <mx:ComboBox
     *    Properties
     *    dataProvider=""null""
     *    dropdownFactory=""ClassFactory that creates an mx.controls.List""
     *    dropdownWidth=""100 or width of the longest text in the dataProvider""
     *    itemRenderer=""null""
     *    labelField=""label""
     *    labelFunction=""null""
     *    prompt=""null""
     *    rowCount=""5""
     *    selectedIndex=""-1""
     *    selectedItem=""null""
     *    
     *    Styles
     *    alternatingItemColors=""undefined""
     *    arrowButtonWidth=""22""
     *    borderColor=""0xB7BABC""
     *    borderThickness=""1""
     *    closeDuration=""250""
     *    closeEasingFunction=""undefined""
     *    color=""0x0B333C""
     *    cornerRadius=""0""
     *    disabledColor=""0xAAB3B3""
     *    disabledIconColor=""0x919999""
     *    dropdownBorderColor=""undefined""
     *    dropdownStyleName=""comboDropdown""
     *    fillAlphas=""[0.6,0.4]""
     *    fillColors=""[0xFFFFFF, 0xCCCCCC]""
     *    focusAlpha=""0.4""
     *    focusRoundedCorners=""tl tr bl br""
     *    fontAntiAliasType=""advanced|normal""
     *    fontFamily=""Verdana""
     *    fontGridFitType=""pixel|none|subpixel""
     *    fontSharpness=""0""
     *    fontSize=""10""
     *    fontStyle=""normal|italic""
     *    fontThickness=""0""
     *    fontWeight=""normal|bold""
     *    highlightAlphas=""[0.3,0.0]""
     *    iconColor=""0x111111""
     *    leading=""0""
     *    openDuration=""250""
     *    openEasingFunction=""undefined""
     *    paddingTop=""0""
     *    paddingBottom=""0""
     *    paddingLeft=""5""
     *    paddingRight=""5""
     *    rollOverColor=""Depends on theme color""
     *    selectionColor=""Depends on theme color""
     *    selectionDuration=""250""
     *    selectionEasingFunction=""undefined""
     *    textAlign=""left|center|right""
     *    textDecoration=""none|underline""
     *    textIndent=""0""
     *    textRollOverColor=""0x2B333C""
     *    textSelectedColor=""0x2B333C""
     *    
     *    Events
     *    change=""No default""
     *    close=""No default""
     *    dataChange=""No default""
     *    enter=""No default""
     *    itemRollOut=""No default""
     *    itemRollOver=""No default""
     *    open=""No default""
     *    scroll=""No default""
     *  />
     *  
    * * @includeExample examples/SimpleComboBox.mxml * * @see mx.controls.List * @see mx.effects.Tween * @see mx.managers.PopUpManager * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class ComboBox extends ComboBase implements IDataRenderer, IDropInListItemRenderer, IListItemRenderer { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class mixins // //-------------------------------------------------------------------------- /** * @private * Placeholder for mixin by ComboBoxAccImpl. */ mx_internal static var createAccessibilityImplementation:Function; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function ComboBox() { super(); // It it better to start out with an empty data provider rather than // an undefined one. Otherwise, code in getDropdown() sets it to [] // later, but via setDataProvider(). This API has side effects like // setting selectionChanged, which causes the text in an editable // ComboBox to be lost. dataProvider = new ArrayCollection(); useFullDropdownSkin = true; wrapDownArrowButton = false; addEventListener(""unload"", unloadHandler); addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * A reference to the internal List that pops up to display a row * for each dataProvider item. */ private var _dropdown:ListBase; /** * @private * A int to track the oldIndex, used when the dropdown is dismissed using the ESC key. */ private var _oldIndex:int; /** * @private * The tween used for showing and hiding the drop-down list. */ private var tween:Tween = null; /** * @private * A flag to track whether the dropDown tweened up or down. */ private var tweenUp:Boolean = false; /** * @private */ private var preferredDropdownWidth:Number; /** * @private */ private var dropdownBorderStyle:String = ""solid""; /** * @private * Is the dropdown list currently shown? */ private var _showingDropdown:Boolean = false; /** * @private */ private var _selectedIndexOnDropdown:int = -1; /** * @private */ private var bRemoveDropdown:Boolean = true; /** * @private */ private var inTween:Boolean = false; /** * @private */ private var bInKeyDown:Boolean = false; /** * @private * Flag that will block default data/listData behavior */ private var selectedItemSet:Boolean; /** * @private * Event that is causing the dropDown to open or close. */ private var triggerEvent:Event; /** * @private * Whether the text property was explicitly set or not */ private var explicitText:Boolean; //-------------------------------------------------------------------------- // // Overridden properties // //-------------------------------------------------------------------------- //---------------------------------- // data //---------------------------------- /** * @private * Storage for the data property. */ private var _data:Object; [Bindable(""dataChange"")] [Inspectable(environment=""none"")] /** * The data property lets you pass a value * to the component when you use it in an item renderer or item editor. * You typically use data binding to bind a field of the data * property to a property of this component. * *

    The ComboBox control uses the listData property and the * data property as follows. If the ComboBox is in a * DataGrid control, it expects the dataField property of the * column to map to a property in the data and sets * selectedItem to that property. If the ComboBox control is * in a List control, it expects the labelField of the list * to map to a property in the data and sets selectedItem to * that property. * Otherwise, it sets selectedItem to the data itself.

    * *

    You do not set this property in MXML.

    * * @see mx.core.IDataRenderer * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get data():Object { return _data; } /** * @private */ public function set data(value:Object):void { var newSelectedItem:*; _data = value; if (_listData && _listData is DataGridListData) newSelectedItem = _data[DataGridListData(_listData).dataField]; else if (_listData is ListData && ListData(_listData).labelField in _data) newSelectedItem = _data[ListData(_listData).labelField]; else newSelectedItem = _data; if (newSelectedItem !== undefined && !selectedItemSet) { selectedItem = newSelectedItem; selectedItemSet = false; } dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE)); } //---------------------------------- // listData //---------------------------------- /** * @private * Storage for the listData property. */ private var _listData:BaseListData; [Bindable(""dataChange"")] [Inspectable(environment=""none"")] /** * When a component is used as a drop-in item renderer or drop-in item * editor, Flex initializes the listData property of the * component with the appropriate data from the List control. The * component can then use the listData property and the * data property to display the appropriate information * as a drop-in item renderer or drop-in item editor. * *

    You do not set this property in MXML or ActionScript; Flex sets it * when the component * is used as a drop-in item renderer or drop-in item editor.

    * * @see mx.controls.listClasses.IDropInListItemRenderer * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get listData():BaseListData { return _listData; } /** * @private */ public function set listData(value:BaseListData):void { _listData = value; } //---------------------------------- // dataProvider //---------------------------------- /** * @private */ private var collectionChanged:Boolean = false; [Bindable(""collectionChange"")] [Inspectable(category=""Data"", arrayType=""Object"")] /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function set dataProvider(value:Object):void { selectionChanged = true; super.dataProvider = value; destroyDropdown(); invalidateProperties(); invalidateSize(); } //---------------------------------- // itemRenderer //---------------------------------- /** * @private * Storage for itemRenderer property. */ private var _itemRenderer:IFactory; [Inspectable(category=""Data"")] /** * IFactory that generates the instances that displays the data for the * drop-down list of the control. You can use this property to specify * a custom item renderer for the drop-down list. * *

    The control uses a List control internally to create the drop-down * list. * The default item renderer for the List control is the ListItemRenderer * class, which draws the text associated with each item in the list, * and an optional icon.

    * * @see mx.controls.List * @see mx.controls.listClasses.ListItemRenderer * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get itemRenderer():IFactory { return _itemRenderer; } /** * @private */ public function set itemRenderer(value:IFactory):void { _itemRenderer = value; if (_dropdown) _dropdown.itemRenderer = value; invalidateSize(); invalidateDisplayList(); dispatchEvent(new Event(""itemRendererChanged"")); } //---------------------------------- // selectedIndex //---------------------------------- [Bindable(""change"")] [Bindable(""collectionChange"")] [Bindable(""valueCommit"")] [Inspectable(category=""General"", defaultValue=""0"")] /** * Index of the selected item in the drop-down list. * Setting this property sets the current index and displays * the associated label in the TextInput portion. *

    The default value is -1, but it set to 0 * when a dataProvider is assigned, unless there is a prompt. * If the control is editable, and the user types in the TextInput portion, * the value of the selectedIndex property becomes * -1. If the value of the selectedIndex * property is out of range, the selectedIndex property is set to the last * item in the dataProvider.

    * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function set selectedIndex(value:int):void { super.selectedIndex = value; if (value >= 0) selectionChanged = true; implicitSelectedIndex = false; invalidateDisplayList(); // value committed event needs the text to be set if (textInput && !textChanged && value >= 0) textInput.text = selectedLabel; else if (textInput && prompt) textInput.text = prompt; // [Matt] setting the text of the textInput should take care of this now // Send a valueCommit event, which is used by the data model //dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); } //---------------------------------- // selectedItem //---------------------------------- [Bindable(""change"")] [Bindable(""collectionChange"")] [Bindable(""valueCommit"")] /** * Contains a reference to the selected item in the * dataProvider. * If the data is an object or class instance, modifying * properties in the object or instance modifies the dataProvider * and thus its views. Setting the selectedItem itself causes the * ComboBox to select that item (display it in the TextInput portion and set * the selectedIndex) if it exists in the dataProvider. *

    If the ComboBox control is editable, the selectedItem * property is null if the user types any text * into the TextInput. * It has a value only if the user selects an item from the drop-down * list, or if it is set programmatically.

    * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override public function set selectedItem(value:Object):void { selectedItemSet = true; // We do not want to apply an implicit default index in this case. implicitSelectedIndex = false; super.selectedItem = value; } //---------------------------------- // showInAutomationHierarchy //---------------------------------- /** * @private */ override public function set showInAutomationHierarchy(value:Boolean):void { //do not allow value changes } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // dropdown //---------------------------------- /** * A reference to the List control that acts as the drop-down in the ComboBox. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get dropdown():ListBase { return getDropdown(); } //---------------------------------- // dropdownFactory //---------------------------------- /** * @private * Storage for the dropdownFactory property. */ private var _dropdownFactory:IFactory = new ClassFactory(List); [Bindable(""dropdownFactoryChanged"")] /** * The IFactory that creates a ListBase-derived instance to use * as the drop-down. * The default value is an IFactory for List * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get dropdownFactory():IFactory { return _dropdownFactory; } /** * @private */ public function set dropdownFactory(value:IFactory):void { _dropdownFactory = value; dispatchEvent(new Event(""dropdownFactoryChanged"")); } //---------------------------------- // dropDownStyleFilters //---------------------------------- /** * The set of styles to pass from the ComboBox to the dropDown. * Styles in the dropDownStyleName style will override these styles. * @see mx.styles.StyleProxy * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function get dropDownStyleFilters():Object { return null; } //---------------------------------- // dropdownWidth //---------------------------------- /** * @private * Storage for the dropdownWidth property. */ private var _dropdownWidth:Number = 100; [Bindable(""dropdownWidthChanged"")] [Inspectable(category=""Size"", defaultValue=""100"")] /** * Width of the drop-down list, in pixels. *

    The default value is 100 or the width of the longest text * in the dataProvider, whichever is greater.

    * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get dropdownWidth():Number { return _dropdownWidth; } /** * @private */ public function set dropdownWidth(value:Number):void { _dropdownWidth = value; preferredDropdownWidth = value; if (_dropdown) _dropdown.setActualSize(value, _dropdown.height); dispatchEvent(new Event(""dropdownWidthChanged"")); } //---------------------------------- // labelField //---------------------------------- /** * @private * Storage for the labelField property. */ private var _labelField:String = ""label""; /** * @private */ private var labelFieldChanged:Boolean; [Bindable(""labelFieldChanged"")] [Inspectable(category=""Data"", defaultValue=""label"")] /** * Name of the field in the items in the dataProvider * Array to display as the label in the TextInput portion and drop-down list. * By default, the control uses a property named label * on each Array object and displays it. *

    However, if the dataProvider items do not contain * a label property, you can set the labelField * property to use a different property.

    * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get labelField():String { return _labelField; } /** * @private */ public function set labelField(value:String):void { _labelField = value; labelFieldChanged = true; invalidateDisplayList(); dispatchEvent(new Event(""labelFieldChanged"")); } //---------------------------------- // labelFunction //---------------------------------- /** * @private * Storage for the labelFunction property. */ private var _labelFunction:Function; /** * @private */ private var labelFunctionChanged:Boolean; [Bindable(""labelFunctionChanged"")] [Inspectable(category=""Data"")] /** * User-supplied function to run on each item to determine its label. * By default the control uses a property named label * on each dataProvider item to determine its label. * However, some data sets do not have a label property, * or do not have another property that can be used for displaying * as a label. *

    An example is a data set that has lastName and * firstName fields but you want to display full names. * You use labelFunction to specify a callback function * that uses the appropriate fields and return a displayable String.

    * *

    The labelFunction takes a single argument which is the item * in the dataProvider and returns a String:

    *
         *  myLabelFunction(item:Object):String
         *  
    * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get labelFunction():Function { return _labelFunction; } /** * @private */ public function set labelFunction(value:Function):void { _labelFunction = value; labelFunctionChanged = true; invalidateDisplayList(); dispatchEvent(new Event(""labelFunctionChanged"")); } //---------------------------------- // prompt //---------------------------------- private var promptChanged:Boolean = false; /** * @private * Storage for the prompt property. */ private var _prompt:String; [Inspectable(category=""General"")] /** * The prompt for the ComboBox control. A prompt is * a String that is displayed in the TextInput portion of the * ComboBox when selectedIndex = -1. It is usually * a String like ""Select one..."". If there is no * prompt, the ComboBox control sets selectedIndex to 0 * and displays the first item in the dataProvider. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get prompt():String { return _prompt; } /** * @private */ public function set prompt(value:String):void { _prompt = value; promptChanged = true; invalidateProperties(); } //---------------------------------- // rowCount //---------------------------------- /** * @private * Storage for the rowCount property. */ private var _rowCount:int = 5; [Bindable(""resize"")] [Inspectable(category=""General"", defaultValue=""5"")] /** * Maximum number of rows visible in the ComboBox control list. * If there are fewer items in the * dataProvider, the ComboBox shows only as many items as * there are in the dataProvider. * * @default 5 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get rowCount():int { return Math.max(1, Math.min(collection.length, _rowCount)); } /** * @private */ public function set rowCount(value:int):void { _rowCount = value; if (_dropdown) _dropdown.rowCount = value; } //---------------------------------- // selectedLabel //---------------------------------- /** * The String displayed in the TextInput portion of the ComboBox. It * is calculated from the data by using the labelField * or labelFunction. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectedLabel():String { var item:Object = selectedItem; return itemToLabel(item); } //-------------------------------------------------------------------------- // // Overridden methods: UIComponent // //-------------------------------------------------------------------------- /** * @private */ override protected function initializeAccessibility():void { if (ComboBox.createAccessibilityImplementation != null) ComboBox.createAccessibilityImplementation(this); } /** * @private */ override public function styleChanged(styleProp:String):void { destroyDropdown(); super.styleChanged(styleProp); } /** * Makes sure the control is at least 40 pixels wide, * and tall enough to fit one line of text * in the TextInput portion of the control but at least * 22 pixels high. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override protected function measure():void { super.measure(); // Make sure we're not too small measuredMinWidth = Math.max(measuredWidth, DEFAULT_MEASURED_MIN_WIDTH); // Make sure we're tall enough to hold our text. // Text field height is text height + 4 pixels top/bottom var textHeight:Number = measureText(""M"").height + 6; var bm:EdgeMetrics = borderMetrics; measuredMinHeight = measuredHeight = Math.max(textHeight + bm.top + bm.bottom, DEFAULT_MEASURED_MIN_HEIGHT); measuredMinHeight = measuredHeight += getStyle(""paddingTop"") + getStyle(""paddingBottom""); } /** * @private * Make sure the drop-down width is the same as the rest of the ComboBox */ override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); // we toss the dropdown when resized // except if we're opening the dropdown // then we assume the updateDisplayList() call is spurious // and will not affect the dropdown size if (_dropdown && !inTween) { // We will not destroy our dropdown if user is actively // interacting with it, this has been legacy behavior since // Flex 3.0. if (!_showingDropdown) destroyDropdown(); } else if (_showingDropdown) { bRemoveDropdown = false; } var ddw:Number = preferredDropdownWidth; if (isNaN(ddw)) ddw = _dropdownWidth = unscaledWidth; if (labelFieldChanged) { if (_dropdown) _dropdown.labelField = _labelField; selectionChanged = true; if (!explicitText) textInput.text = selectedLabel; labelFieldChanged = false; } if (labelFunctionChanged) { selectionChanged = true; if (!explicitText) textInput.text = selectedLabel; labelFunctionChanged = false; } if (selectionChanged) { if (!textChanged) { if (selectedIndex == -1 && prompt) textInput.text = prompt; else if (!explicitText) textInput.text = selectedLabel; } textInput.invalidateDisplayList(); textInput.validateNow(); if (editable) { textInput.selectRange(0, textInput.text.length); textInput.horizontalScrollPosition = 0; } if (_dropdown) _dropdown.selectedIndex = selectedIndex; selectionChanged = false; } // We might need to decrease the number of rows. if (_dropdown && _dropdown.rowCount != rowCount) _dropdown.rowCount = rowCount; } /** * @private */ override protected function commitProperties():void { explicitText = textChanged; super.commitProperties(); if (collectionChanged) { if (selectedIndex == -1 && implicitSelectedIndex && _prompt == null) selectedIndex = 0; selectedIndexChanged = true; collectionChanged = false; } if (promptChanged && prompt != null && selectedIndex == -1) { promptChanged = false; textInput.text = prompt; } } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Returns a string representing the item parameter. * *

    This method checks in the following order to find a value to return:

    * *
      *
    1. If you have specified a labelFunction property, * returns the result of passing the item to the function.
    2. *
    3. If the item is a String, Number, Boolean, or Function, returns * the item.
    4. *
    5. If the item has a property with the name specified by the control's * labelField property, returns the contents of the property.
    6. *
    7. If the item has a label property, returns its value.
    8. *
    * * @param item The object that contains the value to convert to a label. * If the item is null, this method returns the empty string. * * @return A string representing the item parameter. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function itemToLabel(item:Object, ...rest):String { // rest args are needed in case dropdown is some other thing like DataGrid // that has multiple arguments to labelFunction // we need to check for null explicitly otherwise // a numeric zero will not get properly converted to a string. // (do not use !item) if (item == null) return """"; if (labelFunction != null) return labelFunction(item); if (typeof(item) == ""object"") { try { if (item[labelField] != null) item = item[labelField]; } catch(e:Error) { } } else if (typeof(item) == ""xml"") { try { if (item[labelField].length() != 0) item = item[labelField]; } catch(e:Error) { } } if (typeof(item) == ""string"") return String(item); try { return item.toString(); } catch(e:Error) { } return "" ""; } /** * Displays the drop-down list. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function open():void { displayDropdown(true); } /** * Hides the drop-down list. * * @param trigger The event to dispatch when the * drop-down list closes. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function close(trigger:Event = null):void { if (_showingDropdown) { if (_dropdown && selectedIndex != _dropdown.selectedIndex) selectedIndex = _dropdown.selectedIndex; displayDropdown(false, trigger); dispatchChangeEvent(new Event(""dummy""), _selectedIndexOnDropdown, selectedIndex); } } /** * @private */ mx_internal function hasDropdown():Boolean { return _dropdown != null; } /** * @private */ private function getDropdown():ListBase { if (!initialized) return null; if (!hasDropdown()) { var dropDownStyleName:String = getStyle(""dropDownStyleName""); if (dropDownStyleName == null ) dropDownStyleName = getStyle(""dropdownStyleName""); _dropdown = dropdownFactory.newInstance(); _dropdown.visible = false; _dropdown.focusEnabled = false; _dropdown.owner = this; if (itemRenderer) _dropdown.itemRenderer = itemRenderer; if (dropDownStyleName) _dropdown.styleName = dropDownStyleName; PopUpManager.addPopUp(_dropdown, this); // Don't display a tween when the selection changes. // The dropdown menu is about to appear anyway, // and other processing can make the tween look choppy. _dropdown.setStyle(""selectionDuration"", 0); // Set up a data provider in case one doesn't yet exist, // so we can share it with the dropdown listbox. if (!dataProvider) dataProvider = new ArrayCollection(); _dropdown.dataProvider = dataProvider; _dropdown.rowCount = rowCount; _dropdown.width = _dropdownWidth; _dropdown.selectedIndex = selectedIndex; _oldIndex = selectedIndex; _dropdown.verticalScrollPolicy = ScrollPolicy.AUTO; _dropdown.labelField = _labelField; _dropdown.labelFunction = itemToLabel; _dropdown.allowDragSelection = true; _dropdown.addEventListener(""change"", dropdown_changeHandler); _dropdown.addEventListener(ScrollEvent.SCROLL, dropdown_scrollHandler); _dropdown.addEventListener(ListEvent.ITEM_ROLL_OVER, dropdown_itemRollOverHandler); _dropdown.addEventListener(ListEvent.ITEM_ROLL_OUT, dropdown_itemRollOutHandler); // the drop down should close if the user clicks on any item. // add a handler to detect a click in the list _dropdown.addEventListener(ListEvent.ITEM_CLICK, dropdown_itemClickHandler); UIComponentGlobals.layoutManager.validateClient(_dropdown, true); _dropdown.setActualSize(_dropdownWidth, _dropdown.getExplicitOrMeasuredHeight()); _dropdown.validateDisplayList(); _dropdown.cacheAsBitmap = true; // weak reference to stage systemManager.addEventListener(Event.RESIZE, stage_resizeHandler, false, 0, true); } var m:Matrix = MatrixUtil.getConcatenatedMatrix(this, systemManager.getSandboxRoot()); _dropdown.scaleX = m.a; //scale x _dropdown.scaleY = m.d; //scale y return _dropdown; } /** * @private */ private function displayDropdown(show:Boolean, trigger:Event = null, playEffect:Boolean = true):void { if (!initialized || show == _showingDropdown) return; if (inTween && tween) tween.endTween(); // Subclasses may extend to do pre-processing // before the dropdown is displayed // or override to implement special display behavior // Show or hide the dropdown var initY:Number; var endY:Number; var duration:Number; var easingFunction:Function; var point:Point = new Point(0, unscaledHeight); point = localToGlobal(point); var sm:ISystemManager = systemManager.topLevelSystemManager; var screen:Rectangle = sm.getVisibleApplicationRect(null, true); //opening the dropdown if (show) { // Store the selectedIndex temporarily so we can tell // if the value changed when the dropdown is closed _selectedIndexOnDropdown = selectedIndex; getDropdown(); _dropdown.addEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE, dropdown_mouseOutsideHandler); _dropdown.addEventListener(FlexMouseEvent.MOUSE_WHEEL_OUTSIDE, dropdown_mouseOutsideHandler); _dropdown.addEventListener(SandboxMouseEvent.MOUSE_DOWN_SOMEWHERE, dropdown_mouseOutsideHandler); _dropdown.addEventListener(SandboxMouseEvent.MOUSE_WHEEL_SOMEWHERE, dropdown_mouseOutsideHandler); if (_dropdown.parent == null) // was popped up then closed PopUpManager.addPopUp(_dropdown, this); else PopUpManager.bringToFront(_dropdown); // if we donot have enough space in the bottom display the dropdown // at the top. But if the space there is also less than required // display it below. if (point.y + _dropdown.height > screen.bottom && point.y > screen.top + _dropdown.height) { // Dropdown will go below the bottom of the stage // and be clipped. Instead, have it grow up. point.y -= (unscaledHeight + _dropdown.height); initY = -_dropdown.height; tweenUp = true; } else { initY = _dropdown.height; tweenUp = false; } point = _dropdown.parent.globalToLocal(point); // If the combobox's layout is mirrored then the the dropdown's // will be too. That also means that (stage coordinate) point.x is // currently the right edge of the dropdown. Fix that: if (layoutDirection == LayoutDirection.RTL) point.x -= _dropdown.width; var sel:int = _dropdown.selectedIndex; if (sel == -1) sel = 0; var pos:Number = _dropdown.verticalScrollPosition; // try to set the verticalScrollPosition one above the selected index so // it looks better when the dropdown is displayed pos = sel - 1; pos = Math.min(Math.max(pos, 0), _dropdown.maxVerticalScrollPosition); _dropdown.verticalScrollPosition = pos; if (_dropdown.x != point.x || _dropdown.y != point.y) _dropdown.move(point.x, point.y); _dropdown.scrollRect = new Rectangle(0, initY, _dropdown.width, _dropdown.height); if (!_dropdown.visible) _dropdown.visible = true; // Make sure we don't remove the dropdown at the end of the tween bRemoveDropdown = false; // Set up the tween and relevant variables. _showingDropdown = show; duration = getStyle(""openDuration""); endY = 0; easingFunction = getStyle(""openEasingFunction"") as Function; } // closing the dropdown else if (_dropdown) { // Set up the tween and relevant variables. endY = (point.y + _dropdown.height > screen.bottom || tweenUp ? -_dropdown.height : _dropdown.height); _showingDropdown = show; initY = 0; duration = getStyle(""closeDuration""); easingFunction = getStyle(""closeEasingFunction"") as Function; _dropdown.resetDragScrolling(); } inTween = true; // only force validation if we're about to show // or closing with effect. Otherwise, if the iterator // is out of sync in the dropdown, we'll get an RTE // when closing if (playEffect || show) UIComponentGlobals.layoutManager.validateNow(); // Block all layout, responses from web service, and other background // processing until the tween finishes executing. UIComponent.suspendBackgroundProcessing(); // Disable the dropdown during the tween. if (_dropdown) _dropdown.enabled = false; duration = Math.max(1, duration); if (!playEffect) duration = 1; tween = new Tween(this, initY, endY, duration); if (easingFunction != null && tween) tween.easingFunction = easingFunction; triggerEvent = trigger; } /** * @private */ private function dispatchChangeEvent(oldEvent:Event, prevValue:int, newValue:int):void { if (prevValue != newValue) { var newEvent:Event = oldEvent is ListEvent ? oldEvent : new ListEvent(""change""); dispatchEvent(newEvent); } } /** * @private */ private function destroyDropdown():void { if (inTween && tween) tween.endTween(); displayDropdown(false, null, false); } //-------------------------------------------------------------------------- // // Overridden event handlers // //-------------------------------------------------------------------------- private var implicitSelectedIndex:Boolean = false; /** * @private */ override protected function collectionChangeHandler(event:Event):void { // Save a copy of the selectedIndex var curSelectedIndex:int = selectedIndex; super.collectionChangeHandler(event); if (event is CollectionEvent) { // trace(""ListBase collectionEvent""); var ce:CollectionEvent = CollectionEvent(event); if (collection.length == 0) { // Special case: Empty dataProvider. if (!selectedIndexChanged && !selectedItemChanged) { if (super.selectedIndex != -1) super.selectedIndex = -1; implicitSelectedIndex = true; invalidateDisplayList(); } // if the combobox is non-editable remove the text // we don't want to remove the text if it is editable as user might // have typed something. if (textInput && !editable) textInput.text = """"; } else if (ce.kind == CollectionEventKind.ADD) { if (collection.length == ce.items.length) { // Special case: Adding the first item(s). Select item 0 // if there is no prompt if (selectedIndex == -1 && _prompt == null) selectedIndex = 0; } else { // we dont want to destroy the dropdown just // because data got added. Especially true // for paged data. return; } } else if (ce.kind == CollectionEventKind.UPDATE) { if (ce.location == selectedIndex || ce.items[0].source == selectedItem) // unsorted lists don't have a valid location // Force an update of the text input selectionChanged = true; } else if (ce.kind == CollectionEventKind.REPLACE) { // bail on a replace, no need to change anything, // especially for paged data return; } else if (ce.kind == CollectionEventKind.RESET) { collectionChanged = true; if (!selectedIndexChanged && !selectedItemChanged) selectedIndex = prompt ? -1 : 0; invalidateProperties(); } invalidateDisplayList(); destroyDropdown(); } } /** * @private */ override protected function textInput_changeHandler(event:Event):void { super.textInput_changeHandler(event); // Force a change event to be dispatched dispatchChangeEvent(event, -1, -2); } /** * @private */ override protected function downArrowButton_buttonDownHandler( event:FlexEvent):void { // The down arrow should always toggle the visibility of the dropdown. if (_showingDropdown) { close(event); } else { displayDropdown(true, event); } } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function dropdown_mouseOutsideHandler(event:Event):void { // trace(""dropdown_mouseOutsideHandler: "" + event); if (event is MouseEvent) { var mouseEvent:MouseEvent = MouseEvent(event); if (mouseEvent.target != _dropdown) // the dropdown's items can dispatch a mouseDownOutside // event which then bubbles up to us return; if (!hitTestPoint(mouseEvent.stageX, mouseEvent.stageY, true)) { close(event); } } else if (event is SandboxMouseEvent) { close(event); } } /** * @private */ private function dropdown_itemClickHandler(event:ListEvent):void { if (_showingDropdown) { close(); } } /** * @private */ override protected function focusOutHandler(event:FocusEvent):void { // Note: event.relatedObject is the object getting focus. // It can be null in some cases, such as when you open // the dropdown and then click outside the application. // If the dropdown is open... if (_showingDropdown && _dropdown && this.contains(DisplayObject(event.target))) { // If focus is moving outside the dropdown... if (!event.relatedObject || !_dropdown.contains(event.relatedObject)) { // Close the dropdown. close(); } } super.focusOutHandler(event); } private function stage_resizeHandler(event:Event):void { destroyDropdown(); } /** * @private */ private function dropdown_scrollHandler(event:Event):void { // TextField.scroll bubbles so you might see it here if (event is ScrollEvent) { var se:ScrollEvent = ScrollEvent(event); if (se.detail == ScrollEventDetail.THUMB_TRACK || se.detail == ScrollEventDetail.THUMB_POSITION || se.detail == ScrollEventDetail.LINE_UP || se.detail == ScrollEventDetail.LINE_DOWN) dispatchEvent(se); } } /** * @private */ private function dropdown_itemRollOverHandler(event:Event):void { dispatchEvent(event); } /** * @private */ private function dropdown_itemRollOutHandler(event:Event):void { dispatchEvent(event); } /** * @private */ private function dropdown_changeHandler(event:Event):void { var prevValue:int = selectedIndex; // This assignment will also assign the label to the text field. // See setSelectedIndex(). if (_dropdown) selectedIndex = _dropdown.selectedIndex; // If this was generated by the dropdown as a result of a keystroke, it is // likely a Page-Up or Page-Down, or Arrow-Up or Arrow-Down. // If the selection changes due to a keystroke, // we leave the dropdown displayed. // If it changes as a result of a mouse selection, // we close the dropdown. if (!_showingDropdown) dispatchChangeEvent(event, prevValue, selectedIndex); else if (!bInKeyDown) { // this will also send a change event if needed close(); } } /** * @private */ override protected function keyDownHandler(event:KeyboardEvent):void { // If the combo box is disabled, don't do anything if (!enabled) return; // If a the editable field currently has focus, it is handling // all arrow keys. We shouldn't also scroll this selection. if (event.target == textInput) return; if (event.ctrlKey && event.keyCode == Keyboard.DOWN) { displayDropdown(true, event); event.stopPropagation(); } else if (event.ctrlKey && event.keyCode == Keyboard.UP) { close(event); event.stopPropagation(); } else if (event.keyCode == Keyboard.ESCAPE) { if (_showingDropdown) { if (_oldIndex != _dropdown.selectedIndex) selectedIndex = _oldIndex; displayDropdown(false); event.stopPropagation(); } } else if (event.keyCode == Keyboard.ENTER) { if (_showingDropdown) { close(); event.stopPropagation(); } } else { if (!editable || event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN || event.keyCode == Keyboard.PAGE_UP || event.keyCode == Keyboard.PAGE_DOWN) { var oldIndex:int = selectedIndex; // Make sure we know we are handling a keyDown, // so if the dropdown sends out a ""change"" event // (like when an up-arrow or down-arrow changes // the selection) we know not to close the dropdown. bInKeyDown = _showingDropdown; // Redispatch the event to the dropdown // and let its keyDownHandler() handle it. dropdown.dispatchEvent(event.clone()); event.stopPropagation(); bInKeyDown = false; } } } /** * @private * This acts as the destructor. */ private function unloadHandler(event:Event):void { if (inTween) { UIComponent.resumeBackgroundProcessing(); inTween = false; } if (_dropdown) _dropdown.parent.removeChild(_dropdown); } /** * @private */ private function removedFromStageHandler(event:Event):void { // Ensure we've unregistered ourselves from PopupManager, else // we'll be leaked. destroyDropdown(); } //-------------------------------------------------------------------------- // // Tween handlers // //-------------------------------------------------------------------------- /** * @private */ mx_internal function onTweenUpdate(value:Number):void { if (_dropdown) { _dropdown.scrollRect = new Rectangle(0, value, _dropdown.width, _dropdown.height); } } /** * @private */ mx_internal function onTweenEnd(value:Number):void { if (_dropdown) { // Clear the scrollRect here. This way if drop shadows are // assigned to the dropdown they show up correctly _dropdown.scrollRect = null; inTween = false; _dropdown.enabled = true; _dropdown.visible = _showingDropdown; if (bRemoveDropdown) { _dropdown.removeEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE, dropdown_mouseOutsideHandler); _dropdown.removeEventListener(FlexMouseEvent.MOUSE_WHEEL_OUTSIDE, dropdown_mouseOutsideHandler); _dropdown.removeEventListener(SandboxMouseEvent.MOUSE_DOWN_SOMEWHERE, dropdown_mouseOutsideHandler); _dropdown.removeEventListener(SandboxMouseEvent.MOUSE_WHEEL_SOMEWHERE, dropdown_mouseOutsideHandler); PopUpManager.removePopUp(_dropdown); _dropdown = null; } } bRemoveDropdown = true; UIComponent.resumeBackgroundProcessing(); var cbdEvent:DropdownEvent = new DropdownEvent(_showingDropdown ? DropdownEvent.OPEN : DropdownEvent.CLOSE); cbdEvent.triggerEvent = triggerEvent; dispatchEvent(cbdEvent); } /** * Determines default values of the height and width to use for each * entry in the drop-down list, based on the maximum size of the label * text in the first numItems items in the data provider. * * @param count The number of items to check to determine the value. * * @return An Object containing two properties: width and height. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ override protected function calculatePreferredSizeFromData(count:int):Object { var maxW:Number = 0; var maxH:Number = 0; var bookmark:CursorBookmark = iterator ? iterator.bookmark : null; iterator.seek(CursorBookmark.FIRST, 0); var more:Boolean = iterator != null; var lineMetrics:TextLineMetrics; for (var i:int = 0; i < count; i++) { var data:Object; if (more) data = iterator ? iterator.current : null; else data = null; var txt:String = itemToLabel(data); lineMetrics = measureText(txt); maxW = Math.max(maxW, lineMetrics.width); maxH = Math.max(maxH, lineMetrics.height); if (iterator) iterator.moveNext(); } if (prompt) { lineMetrics = measureText(prompt); maxW = Math.max(maxW, lineMetrics.width); maxH = Math.max(maxH, lineMetrics.height); } maxW += getStyle(""paddingLeft"") + getStyle(""paddingRight""); if (iterator) iterator.seek(bookmark, 0); return { width: maxW, height: maxH }; } /** * @private */ mx_internal function get isShowingDropdown():Boolean { return _showingDropdown; } } } ",16290,True,2838.032305652634,median "package SJ.Game.bag { import SJ.Common.Constants.ConstBag; import SJ.Common.Constants.ConstCurrency; import SJ.Common.Constants.ConstHero; import SJ.Common.Constants.ConstItem; import SJ.Common.Constants.ConstTextFormat; import SJ.Common.global.textRender; import SJ.Game.controls.CJBattleEffectUtil; import SJ.Game.controls.CJItemUtil; import SJ.Game.controls.CJTextFormatUtil; import SJ.Game.data.CJDataManager; import SJ.Game.data.CJDataOfBag; import SJ.Game.data.CJDataOfEquipmentbar; import SJ.Game.data.CJDataOfItem; import SJ.Game.data.config.CJDataOfItemEquipProperty; import SJ.Game.data.config.CJDataOfItemJewelProperty; import SJ.Game.data.config.CJDataOfItemPackageProperty; import SJ.Game.data.config.CJDataOfItemProperty; import SJ.Game.data.json.Json_item_equip_config; import SJ.Game.data.json.Json_item_jewel_config; import SJ.Game.data.json.Json_item_setting; import SJ.Game.jewelCombine.CJJewelCombineUtil; import SJ.Game.lang.CJLang; import SJ.Game.layer.CJLayerManager; import engine_starling.SApplication; import engine_starling.display.SImage; import engine_starling.display.SLayer; import engine_starling.feathersextends.TextFieldTextRendererEx; import engine_starling.utils.SManufacturerUtils; import feathers.controls.Button; import feathers.controls.Label; import feathers.controls.text.TextFieldTextRenderer; import feathers.core.ITextRenderer; import feathers.display.Scale3Image; import feathers.display.Scale9Image; import feathers.textures.Scale9Textures; import flash.geom.Rectangle; import flash.text.TextFormat; import flash.text.TextFormatAlign; import lib.engine.utils.CObjectUtils; import lib.engine.utils.functions.Assert; import starling.textures.Texture; /** * 道具tooltip层 * 需预先加载配置文件: * 道具模板配置 : ConstResource.sResItemSetting * 装备道具模板配置 : ConstResource.sResJsonItemEquipConfig * 宝石道具模板配置 : ConstResource.sResJsonItemJewelConfig * 战斗力系数配置 : ConstResource.sResBattleEffectSetting * @author sangxu * */ public class CJItemTooltipBase extends SLayer { public function CJItemTooltipBase() { super(); } /** 道具id */ protected var _itemId:String = """"; /** 道具容器类型 */ protected var _containerType:int = ConstBag.CONTAINER_TYPE_BAG; /** 道具数据 */ protected var _itemData:CJDataOfItem; /** 道具模板 */ protected var _itemTemplate:Json_item_setting; /** 装备模板 */ protected var _equipTemplate:Json_item_equip_config; /** 宝石模板 */ protected var _jewelTemplate:Json_item_jewel_config; /** 背包数据 */ protected var _bagData:CJDataOfBag; /** 装备栏数据 */ protected var _equipData:CJDataOfEquipmentbar; protected var _itemTemplateSetting:CJDataOfItemProperty; protected var _jewelTemplateProperty:CJDataOfItemJewelProperty; protected var _packageTemplateProperty:CJDataOfItemPackageProperty; /** 文字颜色 */ /** 文字颜色 - 标题 */ private const TEXT_COLOR_TITLE:Object = 0xFFFFCC; /** 文字颜色 - 内容 */ private const TEXT_COLOR_CONTANT:Object = 0x97F2A1; /** 文字颜色 - 战斗力 */ private const TEXT_COLOR_ZHANDOULI:Object = 0x4189FF; /** 文字大小 */ private const TEXT_SIZE_NORMAL:int = 9; private const LABEL_HEIGHT_NORMAL:int = 10; private const LABEL_TITEL_INIT_X:int = 10; private const SIGN_ADD:String = ""+""; /** y坐标 */ protected var currentY:int = 0; /** tooltip显示高度 */ protected var bgHeight:int = 0; /** 字体 */ /** 字体 - 道具名 */ private const _tfName:TextFormat = new TextFormat(ConstTextFormat.FONT_FAMILY_HEITI, 13, 0xCCB89B); /** 字体 - 标题 */ private const _tfTitle:TextFormat = new TextFormat(ConstTextFormat.FONT_FAMILY_HEITI, TEXT_SIZE_NORMAL, TEXT_COLOR_TITLE); /** 字体 - 内容 */ private const _tfCont:TextFormat = new TextFormat(ConstTextFormat.FONT_FAMILY_HEITI, TEXT_SIZE_NORMAL, TEXT_COLOR_CONTANT); protected var _layerEquip:CJBagItem; protected var _infoLayer:SLayer; /** 是否有按钮 - 用于控制面板高度 */ private var _hasButton:Boolean = false; private var _btnHeight:int = 0; /** tooltip类型,0:根据道具id; 1:根据道具模板id */ private var _type:int = 0; /** tooltip类型 - 根据道具模板id */ private static const TOOLTIP_TYPE_ITEMID:int = 0; /** tooltip类型 - 根据道具模板id */ private static const TOOLTIP_TYPE_ITEMTEMPLATEID:int = 1; /** tooltip类型 - 根据其他人道具模板id */ private static const TOOLTIP_TYPE_OTHERITEMID:int = 2; /** 其他人(好友)数据, 从服务器传来的数据 */ private var _otherData:Object; /** 关闭回调 */ private var _funcCloseCallback:Function; /** 是否显示出售价格 */ private var _showSellPrice:Boolean = true; /** 按钮 */ private var _arrayBtns:Array = new Array(); /** 刷新是否使用当前按钮(不必再重新加载按钮,目前武将界面装备显示用) */ private var _useCurBtns:Boolean = false; /** 最小高度 */ private var _heightMin:int = 0; override protected function initialize():void { super.initialize(); if (this._type == TOOLTIP_TYPE_ITEMID) { this._initData(); } else if (this._type == TOOLTIP_TYPE_ITEMTEMPLATEID) { this._initTemplateData(this._itemData.templateid); } else if (this._type == TOOLTIP_TYPE_OTHERITEMID) { // if (this._otherData != null) // { // this._initOtherItemData(this._otherData, ); // } } // this._initControls(); this._addListener(); } private function _refreshItemInfo():void { this._initData(); this._initControls(); } /** * 初始化数据 * */ protected function _initData():void { this._bagData = CJDataManager.o.getData(""CJDataOfBag""); this._equipData = CJDataManager.o.getData(""CJDataOfEquipmentbar""); if (this.containerType == ConstBag.CONTAINER_TYPE_BAG) { this._itemData = this._bagData.getItemByItemId(this._itemId); } else if (this.containerType == ConstBag.CONTAINER_TYPE_EQUIP) { this._itemData = this._equipData.getEquipbarItem(this._itemId); } else if (this.containerType == ConstBag.CONTAINER_TYPE_HOLE) { this._itemData = this._equipData.getHoleItem(this._itemId); } Assert(this._itemData != null, ""CJItemTooltip item data is null!!! Item id is:"" + this._itemId + "", container type is:"" + this.containerType); var templateId:int = this._itemData.templateid; this._itemTemplateSetting = CJDataOfItemProperty.o; this._jewelTemplateProperty = CJDataOfItemJewelProperty.o; this._packageTemplateProperty = CJDataOfItemPackageProperty.o; this._itemTemplate = this._itemTemplateSetting.getTemplate(templateId); if (parseInt(this._itemTemplate.type) == ConstItem.SCONST_ITEM_TYPE_EQUIP) { var itemEquipProperty:CJDataOfItemEquipProperty = CJDataOfItemEquipProperty.o; this._equipTemplate = itemEquipProperty.getItemEquipConfigById(templateId); } else if (parseInt(this._itemTemplate.type) == ConstItem.SCONST_ITEM_TYPE_JEWEL) { var itemJewelProperty:CJDataOfItemJewelProperty = CJDataOfItemJewelProperty.o; this._jewelTemplate = itemJewelProperty.getItemJewelConfigById(templateId); } } protected function _initControls():void { // this.x = 127; // this.y = 35; var labTemp:Label; var imgLine:Scale3Image; var imgTemp:SImage; var imgLineNew:SImage; this.bgHeight = 72; if (this._infoLayer == null) { this._infoLayer = new SLayer(); } else { _infoLayer.removeChildren(0); this.currentY = 0; this.bgHeight = 70; } this._infoLayer.width = 226; // 道具图标 if (this._layerEquip == null) { this._layerEquip = new CJBagItem(ConstBag.FrameCreateStateUnlock); this._layerEquip.x = 160; this._layerEquip.y = 8; this._layerEquip.width = 50; this._layerEquip.height = 50; this._infoLayer.addChild(_layerEquip); } this._layerEquip.setBagGoodsItem(this._itemTemplate.picture); // 文字 - 装备名 labTemp = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfName); labTemp.textRendererProperties.textFormat.color = CJTextFormatUtil._getTextColor(parseInt(this._itemTemplate.quality)); labTemp.text = CJLang(this._itemTemplate.itemname); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY + 5; labTemp.width = 155; labTemp.height = 12; this._infoLayer.addChild(labTemp); // 分割线 var textureLine:Texture = SApplication.assets.getTexture(""common_fengexian""); imgLineNew = new SImage(textureLine); imgLineNew.x = 18; imgLineNew.y = 62; imgLineNew.width = 138; imgLineNew.height = 2; this._infoLayer.addChild(imgLineNew); // 装备 if (parseInt(this._itemTemplate.type) == ConstItem.SCONST_ITEM_TYPE_EQUIP) { // 装备基本信息 this._initEquipInfo(); this.currentY += 63; // 装备基础属性 this._initEquipBaseProp(); // 装备洗练属性 this._initEquipXilianProp(); // 镶嵌宝石孔属性 // this._initEquipJewelProp(); } // 道具 else if (parseInt(this._itemTemplate.type) == ConstItem.SCONST_ITEM_TYPE_USE) { // 礼包 var subType:int = parseInt(this._itemTemplate.subtype) if (subType == ConstItem.SCONST_ITEM_SUBTYPE_USE_PACKAGE || subType == ConstItem.SCONST_ITEM_SUBTYPE_USE_LVPACKAGE) { this._initPackageItemInfo(); } this.currentY += 63; } else { this.currentY += 63; } // 宝石 if (parseInt(this._itemTemplate.type) == ConstItem.SCONST_ITEM_TYPE_JEWEL) { this._initJewelInfo(); } this.addChild(this._infoLayer); // 功能描述 this._initDescription(); // 出售价格 this._initSellPrice(); // 增加按钮 this.initButtons(); // 背景 if (_bgImage == null) { var texture:Texture = SApplication.assets.getTexture(""common_tankuangdi""); var bgScaleRange:Rectangle = new Rectangle(19,19,1,1); var bgTexture:Scale9Textures = new Scale9Textures(texture, bgScaleRange); this._bgImage = new Scale9Image(bgTexture); bgImage.width = 226; // bgImage.height = this.bgHeight; this._infoLayer.addChildAt(bgImage, 0); //aaaaaaaaaaaaaa } this.bgImage.height = this.bgHeight; this._infoLayer.height = this.bgHeight; // 重新绘制高度 _resetHeight(); _refreshAllButtonY(); } /** * 重新绘制按钮 * */ protected function _refreshButtons():void { if (false == _useCurBtns) { // 不使用已有按钮 _arrayBtns = null; } else { // 使用已有按钮 for each (var btn:Button in _arrayBtns) { btn.y = 0; this._addButton(btn, false); } } } /** * 添加监听事件 * */ protected function _addListener():void { } private function _initPackageItemInfo():void { var htmlLab:Label = new Label(); htmlLab.textRendererFactory = _getPackageInfoRender; var tf:TextFormat = new TextFormat(ConstTextFormat.FONT_FAMILY_HEITI, TEXT_SIZE_NORMAL); // htmlLab.textRendererProperties.wordWrap = true; // htmlLab.textRendererProperties.textFormat = tf; htmlLab.text = CJItemUtil.getPackageItemsDescHtml(this._itemTemplate.id); htmlLab.x = LABEL_TITEL_INIT_X; htmlLab.y = this.currentY + 20; htmlLab.width = 145; htmlLab.height = 90; htmlLab.textRendererProperties.wordWrap = true; if(SManufacturerUtils.getManufacturerType() == SManufacturerUtils.TYPE_IOS) { // iOS htmlLab.textRendererProperties.textFormat = tf; htmlLab.textRendererProperties.wordWrap = true; htmlLab.textRendererFactory = textRender.htmlTextRender; } else { // 其他设备 htmlLab.textRendererFactory = function():ITextRenderer { var tr:TextFieldTextRenderer = new TextFieldTextRenderer(); tr.width = 170; tr.wordWrap = true; tr.maxWidth = 170; tr.isHTML = true; var tf:TextFormat = new TextFormat(); tf.align = TextFormatAlign.LEFT; tf.color = 0xffffff; tf.size = TEXT_SIZE_NORMAL; tf.font = ConstTextFormat.FONT_FAMILY_HEITI; tr.textFormat = tf; return tr; }; } this._infoLayer.addChild(htmlLab); } private function _getPackageInfoRender():ITextRenderer { var htmltextRender:TextFieldTextRendererEx; htmltextRender = new TextFieldTextRendererEx() htmltextRender.isHTML = true; return htmltextRender; } /** * 装备基础信息 * */ private function _initEquipInfo():void { var labTemp:Label; // 文字 - 战斗力数字 labTemp = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfName); labTemp.textRendererProperties.textFormat.color = TEXT_COLOR_ZHANDOULI; labTemp.text = String(this._getBattleEffectValue()) + CJLang(""ITEM_TOOLTIP_ZHANDOULI""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY + 20; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 战斗力 // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfTitle; // labTemp.textRendererProperties.textFormat.color = TEXT_COLOR_ZHANDOULI; // labTemp.text = CJLang(""ITEM_TOOLTIP_ZHANDOULI""); // labTemp.x = 43; // labTemp.y = this.currentY + 24; // this.addChild(labTemp); // 文字 - 需要等级 labTemp = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); labTemp.text = CJLang(""ITEM_TOOLTIP_NEEDLV""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY + 38; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 需要等级数字 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfCont; labTemp.text = this._itemTemplate.level; labTemp.x = 49; labTemp.y = this.currentY + 38; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 需要职业 labTemp = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); labTemp.text = CJLang(""ITEM_TOOLTIP_NEEDOCCUPATION""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY + 49; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 需要职业内容 var needJob:String = """"; var needoccupation:int = parseInt(this._itemTemplate.needoccupation); if (needoccupation & ConstHero.constHeroJobFighter) { needJob += CJLang(""JOB_NAME_1"") + "" ""; } if (needoccupation & ConstHero.constHeroJobWizard) { needJob += CJLang(""JOB_NAME_2"") + "" ""; } if (needoccupation & ConstHero.constHeroJobPastor) { needJob += CJLang(""JOB_NAME_4"") + "" ""; } if (needoccupation & ConstHero.constHeroJobArcher) { needJob += CJLang(""JOB_NAME_8"") + "" ""; } labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfCont; labTemp.text = needJob; labTemp.x = 49; labTemp.y = this.currentY + 49; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); } /** * 装备基础属性 * @param elmArray * */ private function _initEquipBaseProp():void { var labTemp:Label; var equipPropCount:int = 0; var posY:int = 0; if (parseInt(this._equipTemplate.shengmingadd) > 0) { // 文字 - 基础生命 labTemp = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); labTemp.text = CJLang(""ITEM_TOOLTIP_JICHUSHENGMING""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 基础生命内容 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfCont; labTemp.text = this._equipTemplate.shengmingadd; labTemp.x = 49; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); equipPropCount++; posY += 11; } if (parseInt(this._equipTemplate.wugongadd) > 0) { // 文字 - 基础物攻 labTemp = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); labTemp.text = CJLang(""ITEM_TOOLTIP_JICHUWUGONG""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 基础物攻内容 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfCont; labTemp.text = this._equipTemplate.wugongadd; labTemp.x = 49; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); equipPropCount++; posY += 11; } if (parseInt(this._equipTemplate.wufangadd) > 0) { // 文字 - 基础物防 labTemp = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); labTemp.text = CJLang(""ITEM_TOOLTIP_JICHUWUFANG""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 基础物攻内容 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfCont; labTemp.text = this._equipTemplate.wufangadd; labTemp.x = 49; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); equipPropCount++; posY += 11; } if (parseInt(this._equipTemplate.fagongadd) > 0) { // 文字 - 基础法攻 labTemp = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); labTemp.text = CJLang(""ITEM_TOOLTIP_JICHUFAGONG""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 基础法攻内容 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfCont; labTemp.text = this._equipTemplate.fagongadd; labTemp.x = 49; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); equipPropCount++; posY += 11; } if (parseInt(this._equipTemplate.fafangadd) > 0) { // 文字 - 基础法防 labTemp = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); labTemp.text = CJLang(""ITEM_TOOLTIP_JICHUFAFANG""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 基础法攻内容 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfCont; labTemp.text = this._equipTemplate.fafangadd; labTemp.x = 49; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); equipPropCount++; posY += 11; } if (equipPropCount > 0) { // var textureLine:Texture = SApplication.assets.getTexture(""common_fengexian""); // var lineTexture:Scale3Textures = new Scale3Textures(textureLine, textureLine.width/2-1, 1); // var imgLine:Scale3Image = new Scale3Image(lineTexture); // imgLine.x = 18; // imgLine.y = this.currentY + posY; // imgLine.width = 205; // imgLine.height = 5; // this._infoLayer.addChild(imgLine); this._addLine(this.currentY + posY); posY += 5; } this.currentY += posY; this.bgHeight += posY; } /** * 增加装备洗练属性 * @param elmArray * */ private function _initEquipXilianProp():void { if (this._itemData.addattrjin > 0 || this._itemData.addattrmu > 0 || this._itemData.addattrshui > 0 || this._itemData.addattrhuo > 0 || this._itemData.addattrtu > 0 || this._itemData.addattrbaoji > 0 || this._itemData.addattrrenxing > 0 || this._itemData.addattrshanbi > 0 || this._itemData.addattrmingzhong > 0 || this._itemData.addattrzhiliao > 0 || this._itemData.addattrjianshang > 0 || this._itemData.addattrxixue > 0 || this._itemData.addattrshanghai > 0) { // 文字 - 洗练属性 labTemp = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); labTemp.text = CJLang(""ITEM_TOOLTIP_XILIANSHUXING""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); } else { return; } var labTemp:Label; var posY:int = 11; var isLeft:Boolean = true; // 金 if (this._itemData.addattrjin > 0) { // 文字 - 金 _addXilianTitle(CJLang(""PROP_TYPE_GOLD""), ConstTextFormat.TEXT_COLOR_WUXING_JIN, isLeft, posY); // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); // labTemp.textRendererProperties.textFormat.color = ConstTextFormat.TEXT_COLOR_WUXING_JIN; // labTemp.text = CJLang(""PROP_TYPE_GOLD""); // labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // this._infoLayer.addChild(labTemp); // 文字 - 金内容 _addXilianCont(String(this._itemData.addattrjin), isLeft, posY); // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfCont; // labTemp.text = SIGN_ADD + String(this._itemData.addattrjin); // labTemp.x = 49 + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // this._infoLayer.addChild(labTemp); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 木 if (this._itemData.addattrmu > 0) { // 文字 - 木 _addXilianTitle(CJLang(""PROP_TYPE_WOOD""), ConstTextFormat.TEXT_COLOR_WUXING_MU, isLeft, posY); // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); // labTemp.textRendererProperties.textFormat.color = ConstTextFormat.TEXT_COLOR_WUXING_MU; // labTemp.text = CJLang(""PROP_TYPE_WOOD""); // labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // this._infoLayer.addChild(labTemp); // 文字 - 木内容 _addXilianCont(String(this._itemData.addattrmu), isLeft, posY); // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfCont; // labTemp.text = SIGN_ADD + String(this._itemData.addattrmu); // labTemp.x = 49 + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // this._infoLayer.addChild(labTemp); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 水 if (this._itemData.addattrshui > 0) { // 文字 - 水 _addXilianTitle(CJLang(""PROP_TYPE_WATER""), ConstTextFormat.TEXT_COLOR_WUXING_SHUI, isLeft, posY); // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); // labTemp.textRendererProperties.textFormat.color = ConstTextFormat.TEXT_COLOR_WUXING_SHUI; // labTemp.text = CJLang(""PROP_TYPE_WATER""); // labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // this._infoLayer.addChild(labTemp); // 文字 - 水内容 _addXilianCont(String(this._itemData.addattrshui), isLeft, posY); // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfCont; // labTemp.text = SIGN_ADD + String(this._itemData.addattrshui); // labTemp.x = 49 + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // this._infoLayer.addChild(labTemp); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 火 if (this._itemData.addattrhuo > 0) { // 文字 - 火 _addXilianTitle(CJLang(""PROP_TYPE_FIRE""), ConstTextFormat.TEXT_COLOR_WUXING_HUO, isLeft, posY); // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); // labTemp.textRendererProperties.textFormat.color = ConstTextFormat.TEXT_COLOR_WUXING_HUO; // labTemp.text = CJLang(""PROP_TYPE_FIRE""); // labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // this._infoLayer.addChild(labTemp); // 文字 - 火内容 _addXilianCont(String(this._itemData.addattrhuo), isLeft, posY); // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfCont; // labTemp.text = SIGN_ADD + String(this._itemData.addattrhuo); // labTemp.x = 49 + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // this._infoLayer.addChild(labTemp); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 土 if (this._itemData.addattrtu > 0) { // 文字 - 土 _addXilianTitle(CJLang(""PROP_TYPE_EARTH""), ConstTextFormat.TEXT_COLOR_WUXING_TU, isLeft, posY); // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); // labTemp.textRendererProperties.textFormat.color = ConstTextFormat.TEXT_COLOR_WUXING_TU; // labTemp.text = CJLang(""PROP_TYPE_EARTH""); // labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // this._infoLayer.addChild(labTemp); // 文字 - 土内容 _addXilianCont(String(this._itemData.addattrtu), isLeft, posY); // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfCont; // labTemp.text = SIGN_ADD + String(this._itemData.addattrtu); // labTemp.x = 49 + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // this._infoLayer.addChild(labTemp); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 暴击 if (this._itemData.addattrbaoji > 0) { _addXilianTitle(CJLang(""HERO_UI_CRIT""), TEXT_COLOR_TITLE, isLeft, posY); _addXilianCont(String(this._itemData.addattrbaoji), isLeft, posY); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 韧性 if (this._itemData.addattrrenxing > 0) { _addXilianTitle(CJLang(""HERO_UI_TOUGHNESS""), TEXT_COLOR_TITLE, isLeft, posY); _addXilianCont(String(this._itemData.addattrrenxing), isLeft, posY); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 闪避 if (this._itemData.addattrshanbi > 0) { _addXilianTitle(CJLang(""HERO_UI_DODGE""), TEXT_COLOR_TITLE, isLeft, posY); _addXilianCont(String(this._itemData.addattrshanbi), isLeft, posY); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 命中 if (this._itemData.addattrmingzhong > 0) { _addXilianTitle(CJLang(""HERO_UI_HIT""), TEXT_COLOR_TITLE, isLeft, posY); _addXilianCont(String(this._itemData.addattrmingzhong), isLeft, posY); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 治疗 if (this._itemData.addattrzhiliao > 0) { _addXilianTitle(CJLang(""HERO_UI_CURE""), TEXT_COLOR_TITLE, isLeft, posY); _addXilianCont(String(this._itemData.addattrzhiliao), isLeft, posY); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 减伤 if (this._itemData.addattrjianshang > 0) { _addXilianTitle(CJLang(""HERO_UI_REDUCEHURT""), TEXT_COLOR_TITLE, isLeft, posY); _addXilianCont(String(this._itemData.addattrjianshang), isLeft, posY); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 吸血 if (this._itemData.addattrxixue > 0) { _addXilianTitle(CJLang(""HERO_UI_BLOOD""), TEXT_COLOR_TITLE, isLeft, posY); _addXilianCont(String(this._itemData.addattrxixue), isLeft, posY); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } // 伤害加深 if (this._itemData.addattrshanghai > 0) { _addXilianTitle(CJLang(""HERO_UI_INCHURT""), TEXT_COLOR_TITLE, isLeft, posY); _addXilianCont(String(this._itemData.addattrshanghai), isLeft, posY); if (false == isLeft) { posY += 11; } isLeft = !isLeft; } posY += (!isLeft ? 11 : 0); this._addLine(this.currentY + posY); posY += 5; this.currentY += posY; this.bgHeight += posY; } private function _addXilianTitle(text:String, color:Object, isLeft:Boolean, posY:int):void { var labTemp:Label = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); labTemp.textRendererProperties.textFormat.color = color; labTemp.text = text; labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); } private function _addXilianCont(text:String, isLeft:Boolean, posY:int):void { // 文字 - 内容 var labTemp:Label = new Label(); labTemp.textRendererProperties.textFormat = this._tfCont; labTemp.text = SIGN_ADD + text; labTemp.x = 49 + (isLeft? 0 : 100); labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); } // /** // * 装备孔镶嵌宝石属性 // * // */ // private function _initEquipJewelProp():void // { // // 文字 - 洗练属性 // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfTitle; // labTemp.text = CJLang(""ITEM_TOOLTIP_JEWEL""); // labTemp.x = LABEL_TITEL_INIT_X; // labTemp.y = this.currentY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // this._infoLayer.addChild(labTemp); // // var labTemp:Label; // var posY:int = 11; // var isLeft:Boolean = true; // var jewelItemTmpl:Json_item_setting; // var jewelTmpl:Json_item_jewel_config; // // var itemData:CJDataOfItem; // // // 孔0 // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfCont; // labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // if (this._itemData.holeitemid0 != ""0"") // { // itemData = this._equipData.getHoleItem(this._itemData.holeitemid0); // Assert(itemData != null, ""item tooltip hole0 jewel item is null, jewel itemid is:"" + this._itemData.holeitemid0); // jewelItemTmpl = this._itemTemplateSetting.getTemplate(itemData.templateid); // jewelTmpl = this._jewelTemplateProperty.getItemJewelConfigById(itemData.templateid); // labTemp.text = CJLang(jewelItemTmpl.itemname) // + "" "" // + CJLang(jewelTmpl.type) // + "" "" // + SIGN_ADD // + CJJewelCombineUtil.o.getJewelPropertyBySubtype(parseInt(jewelItemTmpl.subtype), jewelTmpl); // } // else // { // labTemp.text = CJLang(""ITEM_TOOLTIP_JEWEL_NONE""); // } // this._infoLayer.addChild(labTemp); // if (false == isLeft) // { // posY += 11; // } // isLeft = !isLeft; // // // // 孔1 // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfCont; // labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // if (this._itemData.holeitemid1 != ""0"") // { // itemData = this._equipData.getHoleItem(this._itemData.holeitemid1); // Assert(itemData != null, ""item tooltip hole0 jewel item is null, jewel itemid is:"" + this._itemData.holeitemid1); // jewelItemTmpl = this._itemTemplateSetting.getTemplate(itemData.templateid); // jewelTmpl = this._jewelTemplateProperty.getItemJewelConfigById(itemData.templateid); // labTemp.text = CJLang(jewelItemTmpl.itemname) // + "" "" // + CJLang(jewelTmpl.type) // + "" "" // + SIGN_ADD // + CJJewelCombineUtil.o.getJewelPropertyBySubtype(parseInt(jewelItemTmpl.subtype), jewelTmpl); // } // else // { // labTemp.text = CJLang(""ITEM_TOOLTIP_JEWEL_NONE""); // } // this._infoLayer.addChild(labTemp); // if (false == isLeft) // { // posY += 11; // } // isLeft = !isLeft; // // // 孔2 // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfCont; // labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // if (this._itemData.holeitemid2 != ""0"") // { // itemData = this._equipData.getHoleItem(this._itemData.holeitemid2); // Assert(itemData != null, ""item tooltip hole0 jewel item is null, jewel itemid is:"" + this._itemData.holeitemid2); // jewelItemTmpl = this._itemTemplateSetting.getTemplate(itemData.templateid); // jewelTmpl = this._jewelTemplateProperty.getItemJewelConfigById(itemData.templateid); // labTemp.text = CJLang(jewelItemTmpl.itemname) // + "" "" // + CJLang(jewelTmpl.type) // + "" "" // + SIGN_ADD // + CJJewelCombineUtil.o.getJewelPropertyBySubtype(parseInt(jewelItemTmpl.subtype), jewelTmpl); // } // else // { // labTemp.text = CJLang(""ITEM_TOOLTIP_JEWEL_NONE""); // } // this._infoLayer.addChild(labTemp); // if (false == isLeft) // { // posY += 11; // } // isLeft = !isLeft; // // // 孔3 // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfCont; // labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // if (this._itemData.holeitemid3 != ""0"") // { // itemData = this._equipData.getHoleItem(this._itemData.holeitemid3); // Assert(itemData != null, ""item tooltip hole0 jewel item is null, jewel itemid is:"" + this._itemData.holeitemid3); // jewelItemTmpl = this._itemTemplateSetting.getTemplate(itemData.templateid); // jewelTmpl = this._jewelTemplateProperty.getItemJewelConfigById(itemData.templateid); // labTemp.text = CJLang(jewelItemTmpl.itemname) // + "" "" // + CJLang(jewelTmpl.type) // + "" "" // + SIGN_ADD // + CJJewelCombineUtil.o.getJewelPropertyBySubtype(parseInt(jewelItemTmpl.subtype), jewelTmpl); // } // else // { // labTemp.text = CJLang(""ITEM_TOOLTIP_JEWEL_NONE""); // } // this._infoLayer.addChild(labTemp); // if (false == isLeft) // { // posY += 11; // } // isLeft = !isLeft; // // // 孔4 // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfCont; // labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // if (this._itemData.holeitemid4 != ""0"") // { // itemData = this._equipData.getHoleItem(this._itemData.holeitemid4); // Assert(itemData != null, ""item tooltip hole0 jewel item is null, jewel itemid is:"" + this._itemData.holeitemid4); // jewelItemTmpl = this._itemTemplateSetting.getTemplate(itemData.templateid); // jewelTmpl = this._jewelTemplateProperty.getItemJewelConfigById(itemData.templateid); // labTemp.text = CJLang(jewelItemTmpl.itemname) // + "" "" // + CJLang(jewelTmpl.type) // + "" "" // + SIGN_ADD // + CJJewelCombineUtil.o.getJewelPropertyBySubtype(parseInt(jewelItemTmpl.subtype), jewelTmpl); // } // else // { // labTemp.text = CJLang(""ITEM_TOOLTIP_JEWEL_NONE""); // } // this._infoLayer.addChild(labTemp); // if (false == isLeft) // { // posY += 11; // } // isLeft = !isLeft; // // // 孔5 // labTemp = new Label(); // labTemp.textRendererProperties.textFormat = this._tfCont; // labTemp.x = LABEL_TITEL_INIT_X + (isLeft? 0 : 100); // labTemp.y = this.currentY + posY; // labTemp.height = LABEL_HEIGHT_NORMAL; // labTemp.width = 100; // if (this._itemData.holeitemid5 != ""0"") // { // itemData = this._equipData.getHoleItem(this._itemData.holeitemid5); // Assert(itemData != null, ""item tooltip hole0 jewel item is null, jewel itemid is:"" + this._itemData.holeitemid5); // jewelItemTmpl = this._itemTemplateSetting.getTemplate(itemData.templateid); // jewelTmpl = this._jewelTemplateProperty.getItemJewelConfigById(itemData.templateid); // labTemp.text = CJLang(jewelItemTmpl.itemname) // + "" "" // + CJLang(jewelTmpl.type) // + "" "" // + SIGN_ADD // + CJJewelCombineUtil.o.getJewelPropertyBySubtype(parseInt(jewelItemTmpl.subtype), jewelTmpl); // } // else // { // labTemp.text = CJLang(""ITEM_TOOLTIP_JEWEL_NONE""); // } // this._infoLayer.addChild(labTemp); // if (false == isLeft) // { // posY += 11; // } // isLeft = !isLeft; // // // posY += (!isLeft ? 11 : 0); // // this._addLine(this.currentY + posY); // // posY += 5; // this.currentY += posY; // this.bgHeight += posY; // } /** * 增加宝石属性 * */ private function _initJewelInfo():void { var value:int = CJJewelCombineUtil.o.getJewelPropertyBySubtype(parseInt(this._itemTemplate.subtype), this._jewelTemplate); var labTemp:Label; var posY:int = 0; // 文字 - 属性 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfTitle; labTemp.text = CJLang(""ITEM_TOOLTIP_JEWELPRO""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); posY += 11; // 文字 - 属性名 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfTitle; labTemp.text = CJLang(this._jewelTemplate.type); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 属性值 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfCont; labTemp.text = SIGN_ADD + value; labTemp.x = 49; labTemp.y = this.currentY + posY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); posY += 11; this._addLine(this.currentY + posY + 2); this.currentY += posY + 9; this.bgHeight += posY + 9; } /** * 出售价格信息 * */ private function _initSellPrice():void { if (false == _showSellPrice) { return; } if (parseInt(this._itemTemplate.sellstate) == ConstItem.SCONST_ITEM_SELL_STATE_CAN) { this._addLine(this.currentY + 2, 205); this.currentY += 7; var labTemp:Label; // 可出售 // 文字 - 出售价格 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfTitle; labTemp.text = CJLang(""ITEM_TOOLTIP_SELL""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 出售价格数字 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfCont; labTemp.text = this._itemTemplate.sellprice; labTemp.x = 50; labTemp.y = this.currentY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 图片 - 银两 var imgTemp:SImage; if (ConstCurrency.CURRENCY_TYPE_SILVER == this._itemTemplate.selltype) { imgTemp = new SImage(SApplication.assets.getTexture(""common_yinliang"")); } else if (ConstCurrency.CURRENCY_TYPE_GOLD == this._itemTemplate.selltype) { imgTemp = new SImage(SApplication.assets.getTexture(""common_yuanbao"")); } if (imgTemp != null) { imgTemp.x = 85; imgTemp.y = currentY; imgTemp.width = 15; imgTemp.height = 11; this._infoLayer.addChild(imgTemp); } this.currentY += 15; this.bgHeight += 20; } } /** * 增加功能描述 * */ private function _initDescription():void { var subType:int = parseInt(this._itemTemplate.subtype) if (parseInt(this._itemTemplate.type) == ConstItem.SCONST_ITEM_TYPE_USE && (subType == ConstItem.SCONST_ITEM_SUBTYPE_USE_PACKAGE || subType == ConstItem.SCONST_ITEM_SUBTYPE_USE_LVPACKAGE)) { // 文字 - 需要等级 labTemp = new Label(); labTemp.textRendererProperties.textFormat = CObjectUtils.clone(this._tfTitle); labTemp.text = CJLang(""ITEM_TOOLTIP_NEEDLV""); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); // 文字 - 需要等级数字 labTemp = new Label(); labTemp.textRendererProperties.textFormat = this._tfCont; labTemp.text = this._itemTemplate.level; labTemp.x = 49; labTemp.y = this.currentY; labTemp.height = LABEL_HEIGHT_NORMAL; labTemp.width = 100; this._infoLayer.addChild(labTemp); this.currentY += LABEL_HEIGHT_NORMAL; this.bgHeight += LABEL_HEIGHT_NORMAL; } var showLine:int = 3; // 文字 - 功能描述 var labTemp:Label = new Label(); labTemp.textRendererProperties.textFormat = this._tfTitle; labTemp.text = CJLang(""ITEM_TOOLTIP_DESC"") + "" "" + CJLang(this._itemTemplate.description); labTemp.x = LABEL_TITEL_INIT_X; labTemp.y = this.currentY; labTemp.height = LABEL_HEIGHT_NORMAL * showLine; labTemp.width = 205; labTemp.textRendererProperties.wordWrap = true; this._infoLayer.addChild(labTemp); this.currentY += LABEL_HEIGHT_NORMAL * showLine + 2; this.bgHeight += LABEL_HEIGHT_NORMAL * showLine + 2; } /** * 增加分割线,高度自动设置为5,x坐标自动设置为18 * @param y y坐标 * @param width 宽度 * */ private function _addLine(y:int, width:int = 205):void { var textureLine:Texture = SApplication.assets.getTexture(""common_fengexian""); // var lineTexture:Scale3Textures = new Scale3Textures(textureLine, textureLine.width/2-1, 1); // var imgLine:Scale3Image = new Scale3Image(lineTexture); var imgLine:SImage = new SImage(textureLine); imgLine.x = 18; imgLine.y = y + 2; imgLine.width = width; imgLine.height = 2; this._infoLayer.addChild(imgLine); } /** * 添加按钮 * */ protected function initButtons():void { this.currentY += 2; if (true == this._hasButton) { this.currentY += this._btnHeight; this.bgHeight += this._btnHeight; } } /** * 增加多个按钮 * @param buttonArray 按钮数组 * */ public function addButtons(buttonArray:Array):void { for each (var button:Button in buttonArray) { this.addButton(button); } } /** * 增加按钮, 若按钮宽高小于通用标准将设置为标准最小值, 最小值见ConstBag.BUTTON_WIDTH_MIN,ConstBag.BUTTON_WIDTH_MIN * @param button 增加的按钮 * */ public function addButton(button:Button):void { if (button.width < ConstBag.BUTTON_WIDTH_MIN) { button.width = ConstBag.BUTTON_WIDTH_MIN; } if (button.height < ConstBag.BUTTON_HEIGHT_MIN) { button.height = ConstBag.BUTTON_HEIGHT_MIN; } _addButton(button, true); } /** * 增加按钮 * @param button 按钮 * @param addToArray 是否加入array * */ protected function _addButton(button:Button, addToArray:Boolean):void { if (false == this._hasButton) { this._hasButton = true; } this._infoLayer.addChild(button); //aaaaaaaaaaaaa _resetButtonY(button); if (true == addToArray) { _arrayBtns.push(button); } } /** * 刷新所有按钮y坐标 * */ private function _refreshAllButtonY():void { for each(var button:Button in _arrayBtns) { _resetButtonY(button); } } /** * 获取按钮y坐标 * */ private function _resetButtonY(button:Button):void { if (0 == _heightMin) { // 未设置最小高度 if (0 == button.y) { button.y = this.currentY; } else { button.y = this.currentY - button.height; } } else { // 设置最小高度 button.y = this.bgHeight - button.height - 11; } } override protected function draw():void { super.draw(); this.bgImage.height = this.bgHeight; // this.height = this.bgHeight; } /** * 关闭tooltip * */ public function closeToolTip(dispose:Boolean = true):void { // this.removeFromParent(dispose); _closeLayer(dispose); } override public function dispose():void { super.dispose(); this.removeAllEventListener(); } /** * 设置当前道具所属容器类型 * @param value * */ public function set containerType(value:int):void { this._containerType = value; } public function get containerType():int { return this._containerType; } /** * 获取语言表对应语言 * @param langKey * @return * */ private function _getLang(langKey:String) : String { return CJLang(langKey); } public function set itemId(value:String):void { this._itemId = value; } /** * 设置道具id显示tooltip * @param containerType 容器类型 * @param itemId 道具唯一id * */ public function setItemIdAndRefresh(containerType:int, itemId:String, useCurBtns:Boolean = false):void { this._type = TOOLTIP_TYPE_ITEMID; this.containerType = containerType; this.itemId = itemId; this._useCurBtns = useCurBtns; this._refreshItemInfo(); } /** * 设置道具模板id显示tooltip * @param itemTemplateId 道具模板id * */ public function setItemTemplateIdAndRefresh(itemTemplateId:int):void { this._type = TOOLTIP_TYPE_ITEMTEMPLATEID; this._initTemplateData(itemTemplateId); this._initControls(); } /** * 设置其他人(好友)数据显示道具tooltips * @param objData 从服务器获取的好友数据 * @param itemId 道具唯一id * */ public function setOtherItemDataAndRefresh(data:Object, itemId:String):void { this._type = TOOLTIP_TYPE_OTHERITEMID; this._initOtherItemData(data, itemId); this._initControls(); } /** * 重新设置高度 * */ private function _resetHeight():void { if (this.bgHeight < _heightMin) { this.bgHeight = _heightMin; bgImage.height = this.bgHeight; this._infoLayer.height = this.bgHeight; } } /** * 初始化其他人(好友)数据 * @param objData 从服务器获取的好友数据 * @param itemId 道具唯一id * */ private function _initOtherItemData(objData:Object, itemId:String):void { this._otherData = objData; var objEquip:Object = objData.equipmentbar; var equipItemData:Object = objEquip[itemId]; this._itemData = _getCJItemDataByFriendData(equipItemData); // Assert(this._itemData != null, ""CJItemTooltip item data is null!!! Item id is:"" + this._itemId + "", container type is:"" + this.containerType); var templateId:int = this._itemData.templateid; this._itemTemplateSetting = CJDataOfItemProperty.o; this._jewelTemplateProperty = CJDataOfItemJewelProperty.o; this._itemTemplate = this._itemTemplateSetting.getTemplate(templateId); if (parseInt(this._itemTemplate.type) == ConstItem.SCONST_ITEM_TYPE_EQUIP) { var itemEquipProperty:CJDataOfItemEquipProperty = CJDataOfItemEquipProperty.o; this._equipTemplate = itemEquipProperty.getItemEquipConfigById(templateId); } else if (parseInt(this._itemTemplate.type) == ConstItem.SCONST_ITEM_TYPE_JEWEL) { var itemJewelProperty:CJDataOfItemJewelProperty = CJDataOfItemJewelProperty.o; this._jewelTemplate = itemJewelProperty.getItemJewelConfigById(templateId); } } /** * 根据好友装备数据生成CJDataOfItem * @param obj * @return * */ private static function _getCJItemDataByFriendData(obj:Object):CJDataOfItem { var itemData:CJDataOfItem = new CJDataOfItem(); itemData.itemid = obj.itemid; itemData.templateid = int(obj.templateid); itemData.count = int(obj.count); itemData.containertype = int(obj.containertype); itemData.addattrjin = int(obj.addattrjin); itemData.addattrmu = int(obj.addattrmu); itemData.addattrshui = int(obj.addattrshui); itemData.addattrhuo = int(obj.addattrhuo); itemData.addattrtu = int(obj.addattrtu); return itemData; } private function _initTemplateData(itemTemplateId:int):void { this._itemData = new CJDataOfItem(); this._itemData.templateid = itemTemplateId; this._itemTemplateSetting = CJDataOfItemProperty.o; this._itemTemplate = this._itemTemplateSetting.getTemplate(itemTemplateId); if (parseInt(this._itemTemplate.type) == ConstItem.SCONST_ITEM_TYPE_EQUIP) { var itemEquipProperty:CJDataOfItemEquipProperty = CJDataOfItemEquipProperty.o; this._equipTemplate = itemEquipProperty.getItemEquipConfigById(itemTemplateId); } else if (parseInt(this._itemTemplate.type) == ConstItem.SCONST_ITEM_TYPE_JEWEL) { this._jewelTemplateProperty = CJDataOfItemJewelProperty.o; this._jewelTemplate = this._jewelTemplateProperty.getItemJewelConfigById(itemTemplateId); } } private function _getBattleEffectValue():int { var value:int = 0; if (this._type == TOOLTIP_TYPE_ITEMID || this._type == TOOLTIP_TYPE_OTHERITEMID) { value = CJBattleEffectUtil.getEquipValue(this._itemData); } else if (this._type == TOOLTIP_TYPE_ITEMTEMPLATEID) { value = CJBattleEffectUtil.getEquipTemplateValue(this._itemData.templateid); } return value; } /** * 移除所有事件监听 * */ protected function removeAllEventListener():void { } /** * 设置界面最小高度,如果当前高度小于设置高度则设置当前界面高度为所设置的高度 * @param heightMin 最小高度值 * */ public function setHeightMin(heightMin:int):void { this._heightMin = heightMin; if (this.bgImage.height < heightMin) { this.bgImage.height = heightMin; } } /** * 关闭 * */ private function _closeLayer(dispose:Boolean = false):void { CJLayerManager.o.removeFromLayerFadeout(this); if (_funcCloseCallback != null) { _funcCloseCallback(); } } /** * 设置关闭回调方法 * @param func 回调方法 * */ public function setCloseFunction(func:Function):void { _funcCloseCallback = func; } /** * 设置是否显示出售价格 * @param show 是否显示出售价格 * */ public function setShowSellPrice(show:Boolean):void { _showSellPrice = show; } /** * 背景图片 */ private var _bgImage : Scale9Image; /** * 控件 getter */ public function get bgImage():Scale9Image { return this._bgImage; } /** * 控件setter */ } }",16270,True,3858.7027868826385,median "CLASS zcl_abapgit_objects DEFINITION PUBLIC CREATE PUBLIC . PUBLIC SECTION. TYPES: ty_types_tt TYPE SORTED TABLE OF tadir-object WITH UNIQUE KEY table_line . TYPES: BEGIN OF ty_serialization, files TYPE zif_abapgit_definitions=>ty_files_tt, item TYPE zif_abapgit_definitions=>ty_item, END OF ty_serialization . CLASS-METHODS serialize IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_language TYPE spras !iv_main_language_only TYPE abap_bool DEFAULT abap_false !it_translation_langs TYPE zif_abapgit_definitions=>ty_languages OPTIONAL RETURNING VALUE(rs_files_and_item) TYPE ty_serialization RAISING zcx_abapgit_exception . CLASS-METHODS deserialize IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo !is_checks TYPE zif_abapgit_definitions=>ty_deserialize_checks !ii_log TYPE REF TO zif_abapgit_log RETURNING VALUE(rt_accessed_files) TYPE zif_abapgit_definitions=>ty_file_signatures_tt RAISING zcx_abapgit_exception . CLASS-METHODS deserialize_checks IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo RETURNING VALUE(rs_checks) TYPE zif_abapgit_definitions=>ty_deserialize_checks RAISING zcx_abapgit_exception . CLASS-METHODS delete IMPORTING !it_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt !is_checks TYPE zif_abapgit_definitions=>ty_delete_checks OPTIONAL !ii_log TYPE REF TO zif_abapgit_log OPTIONAL RAISING zcx_abapgit_exception . CLASS-METHODS jump IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_line_number TYPE i OPTIONAL !iv_sub_obj_name TYPE zif_abapgit_definitions=>ty_item-obj_name OPTIONAL !iv_sub_obj_type TYPE zif_abapgit_definitions=>ty_item-obj_type OPTIONAL RAISING zcx_abapgit_exception . CLASS-METHODS changed_by IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_user) TYPE xubname RAISING zcx_abapgit_exception . CLASS-METHODS is_supported IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_native_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rv_bool) TYPE abap_bool . CLASS-METHODS exists IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_bool) TYPE abap_bool . CLASS-METHODS supported_list RETURNING VALUE(rt_types) TYPE ty_types_tt . CLASS-METHODS is_active IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_active) TYPE abap_bool RAISING zcx_abapgit_exception . PROTECTED SECTION. PRIVATE SECTION. TYPES: BEGIN OF ty_obj_serializer_item, item TYPE zif_abapgit_definitions=>ty_item, metadata TYPE zif_abapgit_definitions=>ty_metadata, END OF ty_obj_serializer_item . TYPES: ty_obj_serializer_map TYPE SORTED TABLE OF ty_obj_serializer_item WITH UNIQUE KEY item . CLASS-DATA gt_obj_serializer_map TYPE ty_obj_serializer_map . CLASS-DATA gt_supported_obj_types TYPE ty_types_tt . CLASS-METHODS check_duplicates IMPORTING !it_files TYPE zif_abapgit_definitions=>ty_files_tt RAISING zcx_abapgit_exception . CLASS-METHODS class_name IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_class_name) TYPE string . CLASS-METHODS update_package_tree IMPORTING !iv_package TYPE devclass . CLASS-METHODS delete_object IMPORTING !iv_package TYPE devclass !is_item TYPE zif_abapgit_definitions=>ty_item RAISING zcx_abapgit_exception . CLASS-METHODS compare_remote_to_local IMPORTING !ii_object TYPE REF TO zif_abapgit_object !it_remote TYPE zif_abapgit_definitions=>ty_files_tt !is_result TYPE zif_abapgit_definitions=>ty_result !ii_log TYPE REF TO zif_abapgit_log RAISING zcx_abapgit_exception . CLASS-METHODS deserialize_objects IMPORTING !is_step TYPE zif_abapgit_objects=>ty_step_data !ii_log TYPE REF TO zif_abapgit_log CHANGING !ct_files TYPE zif_abapgit_definitions=>ty_file_signatures_tt RAISING zcx_abapgit_exception . CLASS-METHODS check_objects_locked IMPORTING !iv_language TYPE spras !it_items TYPE zif_abapgit_definitions=>ty_items_tt RAISING zcx_abapgit_exception . CLASS-METHODS create_object IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_language TYPE spras !is_metadata TYPE zif_abapgit_definitions=>ty_metadata OPTIONAL !iv_native_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ri_obj) TYPE REF TO zif_abapgit_object RAISING zcx_abapgit_exception . CLASS-METHODS map_tadir_to_items IMPORTING !it_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt RETURNING VALUE(rt_items) TYPE zif_abapgit_definitions=>ty_items_tt . CLASS-METHODS map_results_to_items IMPORTING !it_results TYPE zif_abapgit_definitions=>ty_results_tt RETURNING VALUE(rt_items) TYPE zif_abapgit_definitions=>ty_items_tt . CLASS-METHODS get_deserialize_steps RETURNING VALUE(rt_steps) TYPE zif_abapgit_objects=>ty_step_data_tt . CLASS-METHODS check_main_package IMPORTING !iv_package TYPE devclass !iv_obj_type TYPE tadir-object RAISING zcx_abapgit_exception . ENDCLASS. CLASS ZCL_ABAPGIT_OBJECTS IMPLEMENTATION. METHOD changed_by. DATA: li_obj TYPE REF TO zif_abapgit_object. IF is_item IS NOT INITIAL. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). rv_user = li_obj->changed_by( ). ENDIF. IF rv_user IS INITIAL. * eg. "".abapgit.xml"" file rv_user = zcl_abapgit_objects_super=>c_user_unknown. ENDIF. ENDMETHOD. METHOD check_duplicates. DATA: lt_files TYPE zif_abapgit_definitions=>ty_files_tt, lv_path TYPE string, lv_filename TYPE string, lt_duplicates TYPE STANDARD TABLE OF string WITH DEFAULT KEY, lv_duplicates LIKE LINE OF lt_duplicates, lv_all_duplicates TYPE string. FIELD-SYMBOLS: LIKE LINE OF it_files. lt_files = it_files. SORT lt_files BY path ASCENDING filename ASCENDING. LOOP AT lt_files ASSIGNING . IF lv_path = -path AND lv_filename = -filename. CONCATENATE -path -filename INTO lv_duplicates. APPEND lv_duplicates TO lt_duplicates. ENDIF. lv_path = -path. lv_filename = -filename. ENDLOOP. IF lt_duplicates IS NOT INITIAL. CONCATENATE LINES OF lt_duplicates INTO lv_all_duplicates SEPARATED BY `, `. zcx_abapgit_exception=>raise( |Duplicates: { lv_all_duplicates }| ). ENDIF. ENDMETHOD. METHOD check_main_package. "" check package restrictions, closed package, descriptive or "" functional package cl_pak_object_types=>check_object_type( EXPORTING i_working_mode = 'I' i_package_name = iv_package i_pgmid = 'R3TR' i_object_type = iv_obj_type EXCEPTIONS wrong_object_type = 1 package_not_extensible = 2 package_not_loaded = 3 OTHERS = 4 ). CASE sy-subrc. WHEN 0. RETURN. WHEN 2. zcx_abapgit_exception=>raise( |Object type { iv_obj_type } not allowed for package { iv_package }| ). WHEN OTHERS. zcx_abapgit_exception=>raise_t100( ). ENDCASE. ENDMETHOD. METHOD check_objects_locked. DATA: li_obj TYPE REF TO zif_abapgit_object. FIELD-SYMBOLS: LIKE LINE OF it_items. LOOP AT it_items ASSIGNING . "" You should remember that we ignore not supported objects here, "" because otherwise the process aborts which is not desired IF is_supported( ) = abap_false. CONTINUE. ENDIF. li_obj = create_object( is_item = iv_language = iv_language ). IF li_obj->is_locked( ) = abap_true. zcx_abapgit_exception=>raise( |Object { -obj_type } { -obj_name } | && |is locked. Action not possible.| ). ENDIF. ENDLOOP. ENDMETHOD. METHOD class_name. CONCATENATE 'ZCL_ABAPGIT_OBJECT_' is_item-obj_type INTO rv_class_name. ENDMETHOD. METHOD compare_remote_to_local. * this method is used for comparing local with remote objects * before pull, this is useful eg. when overwriting a TABL object. * only the main XML file is used for comparison DATA: ls_remote_file TYPE zif_abapgit_definitions=>ty_file, li_remote_version TYPE REF TO zif_abapgit_xml_input, lv_count TYPE i, ls_result TYPE zif_abapgit_comparator=>ty_result, lv_answer TYPE string, li_comparator TYPE REF TO zif_abapgit_comparator, lv_gui_is_available TYPE abap_bool, ls_item TYPE zif_abapgit_definitions=>ty_item. FIND ALL OCCURRENCES OF '.' IN is_result-filename MATCH COUNT lv_count. IF is_result-filename CS '.XML' AND lv_count = 2. IF ii_object->exists( ) = abap_false. RETURN. ENDIF. READ TABLE it_remote WITH KEY filename = is_result-filename INTO ls_remote_file. IF sy-subrc <> 0. ""if file does not exist in remote, we don't need to validate RETURN. ENDIF. li_comparator = ii_object->get_comparator( ). IF NOT li_comparator IS BOUND. RETURN. ENDIF. CREATE OBJECT li_remote_version TYPE zcl_abapgit_xml_input EXPORTING iv_xml = zcl_abapgit_convert=>xstring_to_string_utf8( ls_remote_file-data ) iv_filename = ls_remote_file-filename. ls_result = li_comparator->compare( ii_remote = li_remote_version ii_log = ii_log ). IF ls_result-text IS INITIAL. RETURN. ENDIF. ""log comparison result ls_item-obj_type = is_result-obj_type. ls_item-obj_name = is_result-obj_name. ii_log->add_warning( iv_msg = ls_result-text is_item = ls_item ). ""continue or abort? lv_gui_is_available = zcl_abapgit_ui_factory=>get_gui_functions( )->gui_is_available( ). IF lv_gui_is_available = abap_true. CALL FUNCTION 'POPUP_TO_CONFIRM' EXPORTING titlebar = 'Warning' text_question = ls_result-text text_button_1 = 'Abort' icon_button_1 = 'ICON_CANCEL' text_button_2 = 'Pull anyway' icon_button_2 = 'ICON_OKAY' default_button = '2' display_cancel_button = abap_false IMPORTING answer = lv_answer EXCEPTIONS text_not_found = 1 OTHERS = 2. IF sy-subrc <> 0 OR lv_answer = 1. zcx_abapgit_exception=>raise( |Deserialization for object { is_result-obj_name } | & |(type { is_result-obj_type }) aborted by user| ). ENDIF. ELSE. zcx_abapgit_exception=>raise( |Deserialization for object { is_result-obj_name } | & |(type { is_result-obj_type }) aborted, user descision required| ). ENDIF. ENDIF. ENDMETHOD. METHOD create_object. DATA: lv_message TYPE string, lv_class_name TYPE string, ls_obj_serializer_map LIKE LINE OF gt_obj_serializer_map. READ TABLE gt_obj_serializer_map INTO ls_obj_serializer_map WITH KEY item = is_item. IF sy-subrc = 0. lv_class_name = ls_obj_serializer_map-metadata-class. ELSEIF is_metadata IS NOT INITIAL. * Metadata is provided only on serialization * Once this has been triggered, the same serializer shall be used * for subsequent processes. * Thus, buffer the metadata afterwards ls_obj_serializer_map-item = is_item. ls_obj_serializer_map-metadata = is_metadata. INSERT ls_obj_serializer_map INTO TABLE gt_obj_serializer_map. lv_class_name = is_metadata-class. ELSE. lv_class_name = class_name( is_item ). ENDIF. REPLACE FIRST OCCURRENCE OF 'LCL' IN lv_class_name WITH 'ZCL_ABAPGIT'. TRY. CREATE OBJECT ri_obj TYPE (lv_class_name) EXPORTING is_item = is_item iv_language = iv_language. CATCH cx_sy_create_object_error. lv_message = |Object type { is_item-obj_type } not supported, serialize|. IF iv_native_only = abap_false. TRY. "" 2nd step, try looking for plugins CREATE OBJECT ri_obj TYPE zcl_abapgit_objects_bridge EXPORTING is_item = is_item. CATCH cx_sy_create_object_error. zcx_abapgit_exception=>raise( lv_message ). ENDTRY. ELSE. "" No native support? -> fail zcx_abapgit_exception=>raise( lv_message ). ENDIF. ENDTRY. ENDMETHOD. METHOD delete. DATA: ls_item TYPE zif_abapgit_definitions=>ty_item, li_progress TYPE REF TO zif_abapgit_progress, lt_tadir LIKE it_tadir, lt_deleted LIKE it_tadir, lt_items TYPE zif_abapgit_definitions=>ty_items_tt, lx_error TYPE REF TO zcx_abapgit_exception, lv_count TYPE i. FIELD-SYMBOLS: LIKE LINE OF it_tadir. lt_tadir = it_tadir. IF is_checks-transport-required = abap_true. zcl_abapgit_default_transport=>get_instance( )->set( is_checks-transport-transport ). ENDIF. TRY. zcl_abapgit_dependencies=>resolve( CHANGING ct_tadir = lt_tadir ). li_progress = zcl_abapgit_progress=>get_instance( lines( lt_tadir ) ). lt_items = map_tadir_to_items( lt_tadir ). check_objects_locked( iv_language = zif_abapgit_definitions=>c_english it_items = lt_items ). CATCH zcx_abapgit_exception INTO lx_error. zcl_abapgit_default_transport=>get_instance( )->reset( ). RAISE EXCEPTION lx_error. ENDTRY. lv_count = 1. DO. CLEAR lt_deleted. LOOP AT lt_tadir ASSIGNING . li_progress->show( iv_current = lv_count iv_text = |Delete { -obj_name }| ). CLEAR ls_item. ls_item-obj_type = -object. ls_item-obj_name = -obj_name. TRY. delete_object( iv_package = -devclass is_item = ls_item ). INSERT INTO TABLE lt_deleted. DELETE lt_tadir. lv_count = lv_count + 1. "" make sure to save object deletions COMMIT WORK. CATCH zcx_abapgit_exception INTO lx_error. IF ii_log IS BOUND. ii_log->add_exception( ix_exc = lx_error is_item = ls_item ). ii_log->add_error( iv_msg = |Deletion of object { ls_item-obj_name } failed| is_item = ls_item ). ENDIF. ENDTRY. ENDLOOP. "" Exit if done or nothing else was deleted IF lines( lt_tadir ) = 0 OR lines( lt_deleted ) = 0. EXIT. ENDIF. ENDDO. zcl_abapgit_default_transport=>get_instance( )->reset( ). IF lx_error IS BOUND AND lines( lt_tadir ) > 0. zcx_abapgit_exception=>raise( 'Error during uninstall. Check the log.' ). ENDIF. li_progress->off( ). ENDMETHOD. METHOD delete_object. DATA: li_obj TYPE REF TO zif_abapgit_object. IF is_supported( is_item ) = abap_true. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). li_obj->delete( iv_package ). IF li_obj->get_metadata( )-delete_tadir = abap_true. CALL FUNCTION 'TR_TADIR_INTERFACE' EXPORTING wi_delete_tadir_entry = abap_true wi_tadir_pgmid = 'R3TR' wi_tadir_object = is_item-obj_type wi_tadir_obj_name = is_item-obj_name wi_test_modus = abap_false EXCEPTIONS OTHERS = 1 ##FM_SUBRC_OK. "" We deliberately ignore the subrc, because throwing an exception would "" break the deletion of lots of object types. On the other hand we have "" to catch the exceptions because otherwise messages would directly be issued "" by the function module and change the control flow. Thus breaking the "" deletion of TOBJ and other object types. "" TODO: This is not very clean and has to be improved in the future. See PR 2741. ENDIF. ENDIF. ENDMETHOD. METHOD deserialize. DATA: ls_item TYPE zif_abapgit_definitions=>ty_item, li_obj TYPE REF TO zif_abapgit_object, lt_remote TYPE zif_abapgit_definitions=>ty_files_tt, lv_package TYPE devclass, lo_files TYPE REF TO zcl_abapgit_objects_files, lo_xml TYPE REF TO zif_abapgit_xml_input, lt_results TYPE zif_abapgit_definitions=>ty_results_tt, li_progress TYPE REF TO zif_abapgit_progress, lv_path TYPE string, lt_items TYPE zif_abapgit_definitions=>ty_items_tt, lt_steps_id TYPE zif_abapgit_definitions=>ty_deserialization_step_tt, lt_steps TYPE zif_abapgit_objects=>ty_step_data_tt, lx_exc TYPE REF TO zcx_abapgit_exception. DATA: lo_folder_logic TYPE REF TO zcl_abapgit_folder_logic. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_result, TYPE LINE OF zif_abapgit_definitions=>ty_deserialization_step_tt, TYPE LINE OF zif_abapgit_objects=>ty_step_data_tt, TYPE LINE OF zif_abapgit_objects=>ty_deserialization_tt. lt_steps = get_deserialize_steps( ). lv_package = io_repo->get_package( ). IF is_checks-transport-required = abap_true. zcl_abapgit_default_transport=>get_instance( )->set( is_checks-transport-transport ). ENDIF. zcl_abapgit_objects_activation=>clear( ). lt_remote = io_repo->get_files_remote( ). lt_results = zcl_abapgit_file_deserialize=>get_results( io_repo = io_repo ii_log = ii_log ). zcl_abapgit_objects_check=>checks_adjust( EXPORTING io_repo = io_repo is_checks = is_checks CHANGING ct_results = lt_results ). li_progress = zcl_abapgit_progress=>get_instance( lines( lt_results ) ). lt_items = map_results_to_items( lt_results ). check_objects_locked( iv_language = io_repo->get_dot_abapgit( )->get_main_language( ) it_items = lt_items ). lo_folder_logic = zcl_abapgit_folder_logic=>get_instance( ). LOOP AT lt_results ASSIGNING . li_progress->show( iv_current = sy-tabix iv_text = |Deserialize { -obj_name }| ). CLEAR ls_item. ls_item-obj_type = -obj_type. ls_item-obj_name = -obj_name. ""error handling & logging added TRY. "" If package does not exist yet, it will be created with this call lv_package = lo_folder_logic->path_to_package( iv_top = io_repo->get_package( ) io_dot = io_repo->get_dot_abapgit( ) iv_path = -path ). check_main_package( iv_package = lv_package iv_obj_type = ls_item-obj_type ). IF ls_item-obj_type = 'DEVC'. "" Packages have the same filename across different folders. The path needs to be supplied "" to find the correct file. lv_path = -path. ENDIF. CREATE OBJECT lo_files EXPORTING is_item = ls_item iv_path = lv_path. lo_files->set_files( lt_remote ). ""analyze XML in order to instantiate the proper serializer lo_xml = lo_files->read_xml( ). li_obj = create_object( is_item = ls_item iv_language = io_repo->get_dot_abapgit( )->get_main_language( ) is_metadata = lo_xml->get_metadata( ) ). compare_remote_to_local( ii_object = li_obj it_remote = lt_remote is_result = ii_log = ii_log ). li_obj->mo_files = lo_files. ""get required steps for deserialize the object lt_steps_id = li_obj->get_deserialize_steps( ). LOOP AT lt_steps_id ASSIGNING . READ TABLE lt_steps WITH KEY step_id = ASSIGNING . ASSERT sy-subrc = 0. IF -is_ddic = abap_true AND li_obj->get_metadata( )-ddic = abap_false. "" DDIC only for DDIC objects zcx_abapgit_exception=>raise( |Step { } is only for DDIC objects| ). ENDIF. APPEND INITIAL LINE TO -objects ASSIGNING . -item = ls_item. -obj = li_obj. -xml = lo_xml. -package = lv_package. ENDLOOP. CLEAR: lv_path, lv_package. CATCH zcx_abapgit_exception INTO lx_exc. ii_log->add_exception( ix_exc = lx_exc is_item = ls_item ). ii_log->add_error( iv_msg = |Import of object { ls_item-obj_name } failed| is_item = ls_item ). ""object should not be part of any deserialization step CONTINUE. ENDTRY. ENDLOOP. ""run deserialize for all steps and it's objects SORT lt_steps BY order. LOOP AT lt_steps ASSIGNING . deserialize_objects( EXPORTING is_step = ii_log = ii_log CHANGING ct_files = rt_accessed_files ). ENDLOOP. update_package_tree( io_repo->get_package( ) ). SORT rt_accessed_files BY path ASCENDING filename ASCENDING. DELETE ADJACENT DUPLICATES FROM rt_accessed_files. "" Just in case zcl_abapgit_default_transport=>get_instance( )->reset( ). li_progress->off( ). ENDMETHOD. METHOD deserialize_checks. rs_checks = zcl_abapgit_objects_check=>deserialize_checks( io_repo ). ENDMETHOD. METHOD deserialize_objects. DATA: li_progress TYPE REF TO zif_abapgit_progress, li_exit TYPE REF TO zif_abapgit_exit, lx_exc TYPE REF TO zcx_abapgit_exception. FIELD-SYMBOLS: LIKE LINE OF is_step-objects. zcl_abapgit_objects_activation=>clear( ). li_progress = zcl_abapgit_progress=>get_instance( lines( is_step-objects ) ). LOOP AT is_step-objects ASSIGNING . li_progress->show( iv_current = sy-tabix iv_text = |Deserialize { is_step-descr } - { -item-obj_name }| ). TRY. -obj->deserialize( iv_package = -package io_xml = -xml iv_step = is_step-step_id ii_log = ii_log ). APPEND LINES OF -obj->mo_files->get_accessed_files( ) TO ct_files. ii_log->add_success( iv_msg = |Object { -item-obj_name } imported| is_item = -item ). CATCH zcx_abapgit_exception INTO lx_exc. ii_log->add_exception( ix_exc = lx_exc is_item = -item ). ii_log->add_error( iv_msg = |Import of object { -item-obj_name } failed| is_item = -item ). ENDTRY. ENDLOOP. CASE is_step-step_id. WHEN zif_abapgit_object=>gc_step_id-ddic. zcl_abapgit_objects_activation=>activate( is_step-is_ddic ). WHEN zif_abapgit_object=>gc_step_id-abap. zcl_abapgit_objects_activation=>activate( is_step-is_ddic ). WHEN zif_abapgit_object=>gc_step_id-late. "" late can have both DDIC (like TABL with REF TO) and non-DDIC objects zcl_abapgit_objects_activation=>activate( abap_true ). zcl_abapgit_objects_activation=>activate( abap_false ). ENDCASE. * Call postprocessing li_exit = zcl_abapgit_exit=>get_instance( ). li_exit->deserialize_postprocess( is_step = is_step ii_log = ii_log ). ENDMETHOD. METHOD exists. DATA: li_obj TYPE REF TO zif_abapgit_object. TRY. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). rv_bool = li_obj->exists( ). CATCH zcx_abapgit_exception. * ignore all errors and assume the object exists rv_bool = abap_true. ENDTRY. ENDMETHOD. METHOD get_deserialize_steps. FIELD-SYMBOLS: TYPE LINE OF zif_abapgit_objects=>ty_step_data_tt. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-ddic. -descr = 'Import DDIC objects'. -is_ddic = abap_true. -syntax_check = abap_false. -order = 1. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-abap. -descr = 'Import objects main'. -is_ddic = abap_false. -syntax_check = abap_false. -order = 2. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-late. -descr = 'Import late objects'. -is_ddic = abap_false. -syntax_check = abap_true. -order = 3. ENDMETHOD. METHOD is_active. DATA: li_object TYPE REF TO zif_abapgit_object. TRY. li_object = create_object( is_item = is_item iv_language = sy-langu ). rv_active = li_object->is_active( ). CATCH cx_sy_dyn_call_illegal_method cx_sy_ref_is_initial zcx_abapgit_exception. rv_active = abap_true. ENDTRY. ENDMETHOD. METHOD is_supported. TRY. create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english iv_native_only = iv_native_only ). rv_bool = abap_true. CATCH zcx_abapgit_exception. rv_bool = abap_false. ENDTRY. ENDMETHOD. METHOD jump. DATA: li_obj TYPE REF TO zif_abapgit_object, lv_adt_jump_enabled TYPE abap_bool. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). IF li_obj->exists( ) = abap_false. zcx_abapgit_exception=>raise( |Object { is_item-obj_type } { is_item-obj_name } doesn't exist| ). ENDIF. lv_adt_jump_enabled = zcl_abapgit_persist_factory=>get_settings( )->read( )->get_adt_jump_enabled( ). IF lv_adt_jump_enabled = abap_true. TRY. zcl_abapgit_objects_super=>jump_adt( iv_obj_name = is_item-obj_name iv_obj_type = is_item-obj_type iv_sub_obj_name = iv_sub_obj_name iv_sub_obj_type = iv_sub_obj_type iv_line_number = iv_line_number ). CATCH zcx_abapgit_exception. li_obj->jump( ). ENDTRY. ELSEIF iv_line_number IS NOT INITIAL AND iv_sub_obj_type IS NOT INITIAL AND iv_sub_obj_name IS NOT INITIAL. "" For the line navigation we have to supply the sub object type (i_sub_obj_type). "" If we use is_item-obj_type it navigates only to the object. CALL FUNCTION 'RS_TOOL_ACCESS' EXPORTING operation = 'SHOW' object_name = is_item-obj_name object_type = iv_sub_obj_type include = iv_sub_obj_name position = iv_line_number in_new_window = abap_true EXCEPTIONS not_executed = 1 invalid_object_type = 2 OTHERS = 3. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ELSE. li_obj->jump( ). ENDIF. ENDMETHOD. METHOD map_results_to_items. DATA: ls_item LIKE LINE OF rt_items. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_result. LOOP AT it_results ASSIGNING . ls_item-devclass = -package. ls_item-obj_type = -obj_type. ls_item-obj_name = -obj_name. INSERT ls_item INTO TABLE rt_items. ENDLOOP. ENDMETHOD. METHOD map_tadir_to_items. DATA: ls_item LIKE LINE OF rt_items. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_tadir. LOOP AT it_tadir ASSIGNING . ls_item-devclass = -devclass. ls_item-obj_type = -object. ls_item-obj_name = -obj_name. INSERT ls_item INTO TABLE rt_items. ENDLOOP. ENDMETHOD. METHOD serialize. DATA: li_obj TYPE REF TO zif_abapgit_object, li_xml TYPE REF TO zif_abapgit_xml_output, lo_files TYPE REF TO zcl_abapgit_objects_files, ls_i18n_params TYPE zif_abapgit_definitions=>ty_i18n_params. FIELD-SYMBOLS: LIKE LINE OF rs_files_and_item-files. rs_files_and_item-item = is_item. IF is_supported( rs_files_and_item-item ) = abap_false. zcx_abapgit_exception=>raise( |Object type ignored, not supported: { rs_files_and_item-item-obj_type }-{ rs_files_and_item-item-obj_name }| ). ENDIF. CREATE OBJECT lo_files EXPORTING is_item = rs_files_and_item-item. li_obj = create_object( is_item = rs_files_and_item-item iv_language = iv_language ). li_obj->mo_files = lo_files. CREATE OBJECT li_xml TYPE zcl_abapgit_xml_output. ls_i18n_params-main_language = iv_language. ls_i18n_params-main_language_only = iv_main_language_only. ls_i18n_params-translation_languages = it_translation_langs. li_xml->i18n_params( ls_i18n_params ). li_obj->serialize( li_xml ). lo_files->add_xml( ii_xml = li_xml is_metadata = li_obj->get_metadata( ) ). rs_files_and_item-files = lo_files->get_files( ). check_duplicates( rs_files_and_item-files ). rs_files_and_item-item-inactive = boolc( li_obj->is_active( ) = abap_false ). LOOP AT rs_files_and_item-files ASSIGNING . -sha1 = zcl_abapgit_hash=>sha1_blob( -data ). ENDLOOP. ENDMETHOD. METHOD supported_list. DATA: lt_objects TYPE STANDARD TABLE OF ko100, ls_item TYPE zif_abapgit_definitions=>ty_item. FIELD-SYMBOLS LIKE LINE OF lt_objects. IF gt_supported_obj_types IS NOT INITIAL. rt_types = gt_supported_obj_types. RETURN. ENDIF. CALL FUNCTION 'TR_OBJECT_TABLE' TABLES wt_object_text = lt_objects EXCEPTIONS OTHERS = 1 ##FM_SUBRC_OK. LOOP AT lt_objects ASSIGNING WHERE pgmid = 'R3TR'. ls_item-obj_type = -object. IF is_supported( ls_item ) = abap_true. INSERT -object INTO TABLE rt_types. ENDIF. ENDLOOP. gt_supported_obj_types = rt_types. ENDMETHOD. METHOD update_package_tree. DATA: lt_packages TYPE zif_abapgit_sap_package=>ty_devclass_tt, lv_package LIKE LINE OF lt_packages, lv_tree TYPE dirtree-tname. lt_packages = zcl_abapgit_factory=>get_sap_package( iv_package )->list_subpackages( ). APPEND iv_package TO lt_packages. LOOP AT lt_packages INTO lv_package. * update package tree for SE80 lv_tree = 'EU_' && lv_package. CALL FUNCTION 'WB_TREE_ACTUALIZE' EXPORTING tree_name = lv_tree without_crossreference = abap_true with_tcode_index = abap_true. ENDLOOP. ENDMETHOD. ENDCLASS. ",8244,False,1895.7016305967613,median "CLASS lcl_excel_common_test DEFINITION DEFERRED. CLASS zcl_excel_common DEFINITION LOCAL FRIENDS lcl_excel_common_test. *----------------------------------------------------------------------* * CLASS lcl_Excel_Common_Test DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_excel_common_test DEFINITION FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. PRIVATE SECTION. * ================ TYPES: BEGIN OF ty_convert_range2column_a_row, column_start TYPE zexcel_cell_column_alpha, column_start_int TYPE zexcel_cell_column, column_end TYPE zexcel_cell_column_alpha, column_end_int TYPE zexcel_cell_column, row_start TYPE zexcel_cell_row, row_end TYPE zexcel_cell_row, sheet TYPE string, END OF ty_convert_range2column_a_row. DATA: lx_excel TYPE REF TO zcx_excel, ls_symsg_act LIKE sy, "" actual messageinformation of exception ls_symsg_exp LIKE sy, "" expected messageinformation of exception f_cut TYPE REF TO zcl_excel_common. ""class under test METHODS: setup. METHODS: convert_column2alpha_simple FOR TESTING. METHODS: convert_column2alpha_maxcol FOR TESTING. METHODS: convert_column2alpha_last FOR TESTING. METHODS: convert_column2alpha_oob FOR TESTING. METHODS convert_column2int_basic FOR TESTING. METHODS convert_column2int_from_int FOR TESTING RAISING cx_static_check. METHODS convert_column2int_maxcol FOR TESTING. METHODS convert_column2int_oob_empty FOR TESTING. METHODS convert_column2int_oob_invalid FOR TESTING. METHODS convert_column_a_row2columnrow FOR TESTING RAISING cx_static_check. METHODS convert_columnrow2column_a_row FOR TESTING RAISING cx_static_check. METHODS date_to_excel_string1 FOR TESTING RAISING cx_static_check. METHODS date_to_excel_string2 FOR TESTING RAISING cx_static_check. METHODS date_to_excel_string3 FOR TESTING RAISING cx_static_check. METHODS date_to_excel_string4 FOR TESTING RAISING cx_static_check. METHODS date_to_excel_string5 FOR TESTING RAISING cx_static_check. METHODS date_to_excel_string6 FOR TESTING RAISING cx_static_check. METHODS: encrypt_password FOR TESTING. METHODS: excel_string_to_date FOR TESTING. METHODS excel_string_to_time1 FOR TESTING RAISING cx_static_check. METHODS excel_string_to_time2 FOR TESTING RAISING cx_static_check. METHODS excel_string_to_time3 FOR TESTING RAISING cx_static_check. METHODS excel_string_to_time4 FOR TESTING RAISING cx_static_check. METHODS excel_string_to_time5 FOR TESTING RAISING cx_static_check. METHODS time_to_excel_string1 FOR TESTING RAISING cx_static_check. METHODS time_to_excel_string2 FOR TESTING RAISING cx_static_check. METHODS time_to_excel_string3 FOR TESTING RAISING cx_static_check. METHODS time_to_excel_string4 FOR TESTING RAISING cx_static_check. METHODS: split_file FOR TESTING. METHODS: convert_range2column_a_row FOR TESTING RAISING cx_static_check. METHODS: assert_convert_range2column_a_ IMPORTING i_range TYPE clike i_allow_1dim_range TYPE abap_bool DEFAULT abap_false is_exp TYPE ty_convert_range2column_a_row RAISING cx_static_check. METHODS: describe_structure FOR TESTING. METHODS macro_calculate_cell_distance IMPORTING iv_reference_cell TYPE clike iv_current_cell TYPE clike iv_expected_column TYPE i iv_expected_row TYPE i RAISING cx_static_check. METHODS: calc_cell_dist_samecell FOR TESTING RAISING cx_static_check, calc_cell_dist_down1pl FOR TESTING RAISING cx_static_check, calc_cell_dist_downsome FOR TESTING RAISING cx_static_check, calc_cell_dist_up1pl FOR TESTING RAISING cx_static_check, calc_cell_dist_upsome FOR TESTING RAISING cx_static_check, calc_cell_dist_right1pl FOR TESTING RAISING cx_static_check, calc_cell_dist_rightsome FOR TESTING RAISING cx_static_check, calc_cell_dist_left1pl FOR TESTING RAISING cx_static_check, calc_cell_dist_leftsome FOR TESTING RAISING cx_static_check, calc_cell_dist_fullpack FOR TESTING RAISING cx_static_check. METHODS macro_shift_formula IMPORTING iv_reference_formula TYPE clike iv_shift_cols TYPE i iv_shift_rows TYPE i iv_expected TYPE string. METHODS: shift_formula_basic FOR TESTING, shift_formula_rightdown FOR TESTING, shift_formula_leftup FOR TESTING, shift_formula_fixedcolrows FOR TESTING, shift_formula_mixedfixedrows FOR TESTING, shift_formula_rangename FOR TESTING, shift_formula_stringlitconc FOR TESTING, shift_formula_extref FOR TESTING, shift_formula_charblanks FOR TESTING, shift_formula_stringblanks FOR TESTING, shift_formula_funcnoargs FOR TESTING, shift_formula_nocellref FOR TESTING, shift_formula_empty FOR TESTING, shift_formula_referr_colunder FOR TESTING, shift_formula_referr_rowunder FOR TESTING, shift_formula_referr_rowcolund FOR TESTING, shift_formula_sheet_nodigit FOR TESTING, shift_formula_sheet_nodig FOR TESTING, shift_formula_sheet_special FOR TESTING, shift_formula_resp_blanks_1 FOR TESTING, shift_formula_resp_blanks_2 FOR TESTING, shift_formula_range FOR TESTING, shift_formula_notcols FOR TESTING, shift_formula_name FOR TESTING, shift_formula_refcolumn1 FOR TESTING, shift_formula_refcolumn2 FOR TESTING. METHODS is_cell_in_range_ulc_in FOR TESTING. METHODS is_cell_in_range_lrc_in FOR TESTING. METHODS is_cell_in_range_leftside_out FOR TESTING. METHODS is_cell_in_range_upperside_out FOR TESTING. METHODS is_cell_in_range_rightside_out FOR TESTING. METHODS is_cell_in_range_lowerside_out FOR TESTING. ENDCLASS. *----------------------------------------------------------------------* * CLASS lcl_Excel_Common_Test IMPLEMENTATION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_excel_common_test IMPLEMENTATION. * =========================================== METHOD setup. * ============= CREATE OBJECT f_cut. ENDMETHOD. ""setup METHOD convert_column2alpha_simple. * ============================ DATA ep_column TYPE zexcel_cell_column_alpha. * Test 1. Simple test TRY. ep_column = zcl_excel_common=>convert_column2alpha( 1 ). cl_abap_unit_assert=>assert_equals( act = ep_column exp = 'A' msg = 'Wrong column conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. ENDMETHOD. ""convert_column2alpha_simple METHOD convert_column2alpha_maxcol. * ============================ DATA ep_column TYPE zexcel_cell_column_alpha. * Test 2. Max column for OXML #16,384 = XFD TRY. ep_column = zcl_excel_common=>convert_column2alpha( 16384 ). cl_abap_unit_assert=>assert_equals( act = ep_column exp = 'XFD' msg = 'Wrong column conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. ENDMETHOD. ""convert_column2alpha_maxcol METHOD convert_column2alpha_last. * ============================ DATA ep_column TYPE zexcel_cell_column_alpha. * Test 3. Index 0 is out of bounds TRY. ep_column = zcl_excel_common=>convert_column2alpha( 0 ). cl_abap_unit_assert=>assert_equals( act = ep_column exp = 'A' ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>assert_equals( act = lx_excel->error exp = 'Index out of bounds' msg = 'Colum index 0 is out of bounds, min column index is 1' level = if_aunit_constants=>fatal ). ENDTRY. ENDMETHOD. ""convert_column2alpha_last METHOD convert_column2alpha_oob. * ============================ DATA ep_column TYPE zexcel_cell_column_alpha. * Test 4. Exception should be thrown index out of bounds TRY. ep_column = zcl_excel_common=>convert_column2alpha( 16385 ). cl_abap_unit_assert=>assert_differs( act = ep_column exp = 'XFE' msg = 'Colum index 16385 is out of bounds, max column index is 16384' level = if_aunit_constants=>fatal ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>assert_equals( act = lx_excel->error exp = 'Index out of bounds' msg = 'Wrong exception is thrown' level = if_aunit_constants=>tolerable ). ENDTRY. ENDMETHOD. ""convert_Column2alpha_oob METHOD convert_column2int_basic. * ========================== * Test 1. Basic test DATA ep_column TYPE zexcel_cell_column. TRY. ep_column = zcl_excel_common=>convert_column2int( 'A' ). cl_abap_unit_assert=>assert_equals( act = ep_column exp = 1 msg = 'Wrong column conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. ENDMETHOD. ""convert_column2int_basic. METHOD convert_column2int_from_int. DATA ep_column TYPE zexcel_cell_column. ep_column = zcl_excel_common=>convert_column2int( 5 ). cl_abap_unit_assert=>assert_equals( act = ep_column exp = 5 ). ENDMETHOD. METHOD convert_column2int_maxcol. * ========================== * Test 2. Max column DATA ep_column TYPE zexcel_cell_column. TRY. ep_column = zcl_excel_common=>convert_column2int( 'XFD' ). cl_abap_unit_assert=>assert_equals( act = ep_column exp = 16384 msg = 'Wrong column conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. ENDMETHOD. ""convert_column2int_maxcol METHOD convert_column2int_oob_empty. * ========================== * Test 3. Out of bounds DATA ep_column TYPE zexcel_cell_column. TRY. ep_column = zcl_excel_common=>convert_column2int( '' ). cl_abap_unit_assert=>assert_differs( act = ep_column exp = '0' msg = 'Wrong column conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. CLEAR: ls_symsg_act, ls_symsg_exp. ls_symsg_exp-msgid = 'ZABAP2XLSX'. ls_symsg_exp-msgno = '800'. ls_symsg_act-msgid = lx_excel->syst_at_raise-msgid. ls_symsg_act-msgno = lx_excel->syst_at_raise-msgno. cl_abap_unit_assert=>assert_equals( act = ls_symsg_act exp = ls_symsg_exp msg = 'Colum name should be a valid string' level = if_aunit_constants=>fatal ). ENDTRY. ENDMETHOD. ""convert_column2int_oob_empty. METHOD convert_column2int_oob_invalid. * ========================== * Test 4. Out of bounds DATA ep_column TYPE zexcel_cell_column. TRY. ep_column = zcl_excel_common=>convert_column2int( 'XFE' ). cl_abap_unit_assert=>assert_differs( act = ep_column exp = 16385 msg = 'Wrong column conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>assert_equals( act = lx_excel->error exp = 'Index out of bounds' msg = 'Colum XFE is out of range' level = if_aunit_constants=>fatal ). ENDTRY. ENDMETHOD. ""convert_column2int_oob_invalid. METHOD convert_column_a_row2columnrow. DATA: cell_coords TYPE string. cell_coords = zcl_excel_common=>convert_column_a_row2columnrow( i_column = 'B' i_row = 6 ). cl_abap_unit_assert=>assert_equals( act = cell_coords exp = 'B6' ). cell_coords = zcl_excel_common=>convert_column_a_row2columnrow( i_column = 2 i_row = 6 ). cl_abap_unit_assert=>assert_equals( act = cell_coords exp = 'B6' ). ENDMETHOD. METHOD convert_columnrow2column_a_row. DATA: column TYPE zexcel_cell_column_alpha, column_int TYPE zexcel_cell_column, row TYPE zexcel_cell_row. zcl_excel_common=>convert_columnrow2column_a_row( EXPORTING i_columnrow = 'B6' IMPORTING e_column = column e_column_int = column_int e_row = row ). cl_abap_unit_assert=>assert_equals( act = column exp = 'B' msg = 'Invalid column (alpha)' ). cl_abap_unit_assert=>assert_equals( act = column_int exp = 2 msg = 'Invalid column (numeric)' ). cl_abap_unit_assert=>assert_equals( act = row exp = 6 msg = 'Invalid row' ). ENDMETHOD. METHOD date_to_excel_string1. DATA ep_value TYPE zexcel_cell_value. * Test 1. Basic conversion ep_value = zcl_excel_common=>date_to_excel_string( '19000101' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = 1 msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD date_to_excel_string2. DATA ep_value TYPE zexcel_cell_value. * Check around the ""Excel Leap Year"" 1900 ep_value = zcl_excel_common=>date_to_excel_string( '19000228' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = 59 msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD date_to_excel_string3. DATA ep_value TYPE zexcel_cell_value. ep_value = zcl_excel_common=>date_to_excel_string( '19000301' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = 61 msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD date_to_excel_string4. DATA ep_value TYPE zexcel_cell_value. * Test 2. Basic conversion ep_value = zcl_excel_common=>date_to_excel_string( '99991212' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = 2958446 msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD date_to_excel_string5. DATA ep_value TYPE zexcel_cell_value. * Test 3. Initial date DATA: lv_date TYPE d. ep_value = zcl_excel_common=>date_to_excel_string( lv_date ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD date_to_excel_string6. DATA ep_value TYPE zexcel_cell_value. * Test 2. Basic conversion DATA exp_value TYPE zexcel_cell_value VALUE 0. ep_value = zcl_excel_common=>date_to_excel_string( '18991231' ). cl_abap_unit_assert=>assert_differs( act = ep_value exp = exp_value msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD encrypt_password. * ======================== DATA lv_encrypted_pwd TYPE zexcel_aes_password. TRY. lv_encrypted_pwd = zcl_excel_common=>encrypt_password( 'test' ). cl_abap_unit_assert=>assert_equals( act = lv_encrypted_pwd exp = 'CBEB' msg = 'Wrong password encryption' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. ENDMETHOD. ""encrypt_Password METHOD excel_string_to_date. * ============================ DATA ep_value TYPE d. * Test 1. Simple test -> ABAP Manage also date prior of 1900 TRY. ep_value = zcl_excel_common=>excel_string_to_date( '0' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '00000000' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. * Check empty content TRY. ep_value = zcl_excel_common=>excel_string_to_date( '' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '00000000' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. * Check space character TRY. ep_value = zcl_excel_common=>excel_string_to_date( ` ` ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '00000000' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. * Check first Excel date 1/1/1900 TRY. ep_value = zcl_excel_common=>excel_string_to_date( '1' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '19000101' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. * Check around the ""Excel Leap Year"" 1900 TRY. ep_value = zcl_excel_common=>excel_string_to_date( '59' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '19000228' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. TRY. ep_value = zcl_excel_common=>excel_string_to_date( '61' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '19000301' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. * Test 2. Simple test TRY. ep_value = zcl_excel_common=>excel_string_to_date( '1' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '19000101' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. * Test 3. Last possible date TRY. ep_value = zcl_excel_common=>excel_string_to_date( '2958465' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '99991231' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>fail( msg = 'unexpected exception' level = if_aunit_constants=>critical "" Error Severity ). ENDTRY. * Test 4. Exception should be thrown index out of bounds TRY. ep_value = zcl_excel_common=>excel_string_to_date( '2958466' ). cl_abap_unit_assert=>fail( msg = |Unexpected result '{ ep_value }'| level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>assert_equals( act = lx_excel->error exp = 'Unable to interpret date' msg = 'Time should be a valid date' level = if_aunit_constants=>fatal ). ENDTRY. ENDMETHOD. ""excel_String_To_Date METHOD excel_string_to_time1. DATA ep_value TYPE t. * Test 1. Simple test ep_value = zcl_excel_common=>excel_string_to_time( '0' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '000000' msg = 'Wrong date conversion' level = if_aunit_constants=>tolerable ). ENDMETHOD. METHOD excel_string_to_time2. DATA ep_value TYPE t. * Test 2. Simple test ep_value = zcl_excel_common=>excel_string_to_time( '1' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '000000' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD excel_string_to_time3. DATA ep_value TYPE t. * Test 3. Simple test ep_value = zcl_excel_common=>excel_string_to_time( '0.99999' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '235959' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD excel_string_to_time4. DATA ep_value TYPE t. * Test 4. Also string greater than 1 should be managed ep_value = zcl_excel_common=>excel_string_to_time( '4.1' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '022400' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD excel_string_to_time5. DATA ep_value TYPE t. * Test 4. string is not a number TRY. ep_value = zcl_excel_common=>excel_string_to_time( 'NaN' ). cl_abap_unit_assert=>assert_differs( act = ep_value exp = '000000' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). CATCH zcx_excel INTO lx_excel. cl_abap_unit_assert=>assert_equals( act = lx_excel->error exp = 'Unable to interpret time' msg = 'Time should be a valid string' level = if_aunit_constants=>fatal ). ENDTRY. ENDMETHOD. METHOD time_to_excel_string1. DATA ep_value TYPE zexcel_cell_value. * Test 1. Basic conversion ep_value = zcl_excel_common=>time_to_excel_string( '000001' ). "" A test directly in Excel returns the value 0.0000115740740740741000 cl_abap_unit_assert=>assert_equals( act = ep_value exp = '0.0000115740740741' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD time_to_excel_string2. DATA ep_value TYPE zexcel_cell_value. * Test 2. Basic conversion ep_value = zcl_excel_common=>time_to_excel_string( '235959' ). "" A test directly in Excel returns the value 0.9999884259259260000000 cl_abap_unit_assert=>assert_equals( act = ep_value exp = '0.9999884259259260' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD time_to_excel_string3. DATA ep_value TYPE zexcel_cell_value. * Test 3. Initial date ep_value = zcl_excel_common=>time_to_excel_string( '000000' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '0' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD time_to_excel_string4. DATA ep_value TYPE zexcel_cell_value. * Test 2. Basic conversion ep_value = zcl_excel_common=>time_to_excel_string( '022400' ). cl_abap_unit_assert=>assert_equals( act = ep_value exp = '0.1000000000000000' msg = 'Wrong date conversion' level = if_aunit_constants=>critical ). ENDMETHOD. METHOD split_file. * ============================ DATA: ep_file TYPE text255, ep_extension TYPE char10, ep_dotextension TYPE char10. * Test 1. Basic conversion zcl_excel_common=>split_file( EXPORTING ip_file = 'filename.xml' IMPORTING ep_file = ep_file ep_extension = ep_extension ep_dotextension = ep_dotextension ). cl_abap_unit_assert=>assert_equals( act = ep_file exp = 'filename' msg = 'Split filename failed' level = if_aunit_constants=>critical ). cl_abap_unit_assert=>assert_equals( act = ep_extension exp = 'xml' msg = 'Split extension failed' level = if_aunit_constants=>critical ). cl_abap_unit_assert=>assert_equals( act = ep_dotextension exp = '.xml' msg = 'Split extension failed' level = if_aunit_constants=>critical ). * Test 2. no extension zcl_excel_common=>split_file( EXPORTING ip_file = 'filename' IMPORTING ep_file = ep_file ep_extension = ep_extension ep_dotextension = ep_dotextension ). cl_abap_unit_assert=>assert_equals( act = ep_file exp = 'filename' msg = 'Split filename failed' level = if_aunit_constants=>critical ). cl_abap_unit_assert=>assert_equals( act = ep_extension exp = '' msg = 'Split extension failed' level = if_aunit_constants=>critical ). cl_abap_unit_assert=>assert_equals( act = ep_dotextension exp = '' msg = 'Split extension failed' level = if_aunit_constants=>critical ). ENDMETHOD. ""split_file METHOD convert_range2column_a_row. DATA: lv_range TYPE string, ls_exp TYPE ty_convert_range2column_a_row. * a) input empty --> nothing to do lv_range = ''. CLEAR ls_exp. assert_convert_range2column_a_( i_range = lv_range is_exp = ls_exp ). * b) sheetname existing - starts with ' example 'Sheet 1'!$B$6:$D$13 lv_range = `'Sheet 1'!$B$6:$D$13`. CLEAR ls_exp. ls_exp-column_start = 'B'. ls_exp-column_start_int = 2. ls_exp-column_end = 'D'. ls_exp-column_end_int = 4. ls_exp-row_start = 6. ls_exp-row_end = 13. ls_exp-sheet = 'Sheet 1'. assert_convert_range2column_a_( i_range = lv_range is_exp = ls_exp ). * c) sheetname existing - does not start with ' example Sheet1!$B$6:$D$13 lv_range = `Sheet1!B6:$D$13`. CLEAR ls_exp. ls_exp-column_start = 'B'. ls_exp-column_start_int = 2. ls_exp-column_end = 'D'. ls_exp-column_end_int = 4. ls_exp-row_start = 6. ls_exp-row_end = 13. ls_exp-sheet = 'Sheet1'. assert_convert_range2column_a_( i_range = lv_range is_exp = ls_exp ). * d) no sheetname - just area example $B$6:$D$13 lv_range = `$B$6:D13`. CLEAR ls_exp. ls_exp-column_start = 'B'. ls_exp-column_start_int = 2. ls_exp-column_end = 'D'. ls_exp-column_end_int = 4. ls_exp-row_start = 6. ls_exp-row_end = 13. assert_convert_range2column_a_( i_range = lv_range is_exp = ls_exp ). ********************************************************************** * 1 Dimensional Ranges - Ros or Cols Only (eg Print Tiles) * lv_range = `$2:$7`. CLEAR ls_exp. assert_convert_range2column_a_( i_range = lv_range i_allow_1dim_range = abap_false is_exp = ls_exp ). *** lv_range = `$2:$7`. CLEAR ls_exp. ls_exp-row_start = 2. ls_exp-row_end = 7. assert_convert_range2column_a_( i_range = lv_range i_allow_1dim_range = abap_true is_exp = ls_exp ). *** lv_range = `Sheet3!$D:$I`. CLEAR ls_exp. ls_exp-column_start = 'D'. ls_exp-column_start_int = 4. ls_exp-column_end = 'I'. ls_exp-column_end_int = 9. ls_exp-sheet = 'Sheet3'. assert_convert_range2column_a_( i_range = lv_range i_allow_1dim_range = abap_true is_exp = ls_exp ). ENDMETHOD. ""convert_range2column_a_row METHOD assert_convert_range2column_a_. DATA: ls_act TYPE ty_convert_range2column_a_row, lv_message TYPE string. zcl_excel_common=>convert_range2column_a_row( EXPORTING i_range = i_range i_allow_1dim_range = i_allow_1dim_range IMPORTING e_column_start = ls_act-column_start e_column_start_int = ls_act-column_start_int e_column_end = ls_act-column_end e_column_end_int = ls_act-column_end_int e_row_start = ls_act-row_start e_row_end = ls_act-row_end e_sheet = ls_act-sheet ). lv_message = `Invalid column start (alpha) for ` && i_range. cl_abap_unit_assert=>assert_equals( act = ls_act-column_start exp = is_exp-column_start msg = lv_message ). lv_message = `Invalid column start (numeric) for ` && i_range. cl_abap_unit_assert=>assert_equals( act = ls_act-column_start_int exp = is_exp-column_start_int msg = lv_message ). lv_message = `Invalid column end (alpha) for ` && i_range. cl_abap_unit_assert=>assert_equals( act = ls_act-column_end exp = is_exp-column_end msg = lv_message ). lv_message = `Invalid column end (numeric) for ` && i_range. cl_abap_unit_assert=>assert_equals( act = ls_act-column_end_int exp = is_exp-column_end_int msg = lv_message ). lv_message = `Invalid row start for ` && i_range. cl_abap_unit_assert=>assert_equals( act = ls_act-row_start exp = is_exp-row_start msg = lv_message ). lv_message = `Invalid row end for ` && i_range. cl_abap_unit_assert=>assert_equals( act = ls_act-row_end exp = is_exp-row_end msg = lv_message ). lv_message = `Invalid sheet for ` && i_range. cl_abap_unit_assert=>assert_equals( act = ls_act-sheet exp = is_exp-sheet msg = lv_message ). ENDMETHOD. METHOD describe_structure. DATA: ls_test TYPE zexcel_pane. DATA: lo_structdescr TYPE REF TO cl_abap_structdescr. DATA: lt_structure TYPE ddfields. FIELD-SYMBOLS: LIKE LINE OF lt_structure. "" Test with DDIC Type lo_structdescr ?= cl_abap_structdescr=>describe_by_data( p_data = ls_test ). lt_structure = zcl_excel_common=>describe_structure( io_struct = lo_structdescr ). READ TABLE lt_structure ASSIGNING INDEX 1. cl_abap_unit_assert=>assert_equals( act = -fieldname exp = 'YSPLIT' msg = 'Describe structure failed' level = if_aunit_constants=>critical ). "" Test with local defined structure having DDIC and non DDIC elements TYPES: BEGIN OF t_test, carrid TYPE string, carrname TYPE string, carrdesc TYPE string, END OF t_test. DATA: ls_ttest TYPE t_test. lo_structdescr ?= cl_abap_structdescr=>describe_by_data( p_data = ls_ttest ). lt_structure = zcl_excel_common=>describe_structure( io_struct = lo_structdescr ). READ TABLE lt_structure ASSIGNING INDEX 1. cl_abap_unit_assert=>assert_equals( act = -fieldname exp = 'CARRID' msg = 'Describe structure failed' level = if_aunit_constants=>critical ). ENDMETHOD. ""describe_structure METHOD macro_calculate_cell_distance. DATA: lv_offset_rows TYPE i, lv_offset_cols TYPE i, lv_message TYPE string. zcl_excel_common=>calculate_cell_distance( EXPORTING iv_reference_cell = iv_reference_cell iv_current_cell = iv_current_cell IMPORTING ev_row_difference = lv_offset_rows ev_col_difference = lv_offset_cols ). * Check delta columns CONCATENATE 'Error calculating column difference in test:' iv_reference_cell '->' iv_current_cell INTO lv_message SEPARATED BY space. cl_abap_unit_assert=>assert_equals( act = lv_offset_cols exp = iv_expected_column msg = lv_message quit = 0 "" continue tests level = if_aunit_constants=>critical ). * Check delta rows CONCATENATE 'Error calculating row difference in test:' iv_reference_cell '->' iv_current_cell INTO lv_message SEPARATED BY space. cl_abap_unit_assert=>assert_equals( act = lv_offset_rows exp = iv_expected_row msg = lv_message quit = 0 "" continue tests level = if_aunit_constants=>critical ). ENDMETHOD. METHOD calc_cell_dist_samecell. "" Same cell macro_calculate_cell_distance( iv_reference_cell = 'C12' iv_current_cell = 'C12' iv_expected_column = 0 iv_expected_row = 0 ). ENDMETHOD. METHOD calc_cell_dist_down1pl. "" Shift down 1 place macro_calculate_cell_distance( iv_reference_cell = 'C12' iv_current_cell = 'C13' iv_expected_column = 0 iv_expected_row = 1 ). ENDMETHOD. METHOD calc_cell_dist_downsome. "" Shift down some places macro_calculate_cell_distance( iv_reference_cell = 'C12' iv_current_cell = 'C25' iv_expected_column = 0 iv_expected_row = 13 ). ENDMETHOD. METHOD calc_cell_dist_up1pl. "" Shift up 1 place macro_calculate_cell_distance( iv_reference_cell = 'C12' iv_current_cell = 'C11' iv_expected_column = 0 iv_expected_row = -1 ). ENDMETHOD. METHOD calc_cell_dist_upsome. "" Shift up some place macro_calculate_cell_distance( iv_reference_cell = 'C12' iv_current_cell = 'C1' iv_expected_column = 0 iv_expected_row = -11 ). ENDMETHOD. METHOD calc_cell_dist_right1pl. "" Shift right 1 place macro_calculate_cell_distance( iv_reference_cell = 'C12' iv_current_cell = 'D12' iv_expected_column = 1 iv_expected_row = 0 ). ENDMETHOD. METHOD calc_cell_dist_rightsome. "" Shift right some places macro_calculate_cell_distance( iv_reference_cell = 'C12' iv_current_cell = 'AA12' iv_expected_column = 24 iv_expected_row = 0 ). ENDMETHOD. METHOD calc_cell_dist_left1pl. "" Shift left 1 place macro_calculate_cell_distance( iv_reference_cell = 'C12' iv_current_cell = 'B12' iv_expected_column = -1 iv_expected_row = 0 ). ENDMETHOD. METHOD calc_cell_dist_leftsome. "" Shift left some place macro_calculate_cell_distance( iv_reference_cell = 'AA12' iv_current_cell = 'C12' iv_expected_column = -24 iv_expected_row = 0 ). ENDMETHOD. METHOD calc_cell_dist_fullpack. "" The full package. macro_calculate_cell_distance( iv_reference_cell = 'AA121' iv_current_cell = 'C12' iv_expected_column = -24 iv_expected_row = -109 ). ENDMETHOD. METHOD macro_shift_formula. DATA: lv_resulting_formula TYPE string, lv_message TYPE string, lv_counter TYPE n LENGTH 8. ADD 1 TO lv_counter. CLEAR lv_resulting_formula. TRY. lv_resulting_formula = zcl_excel_common=>shift_formula( iv_reference_formula = iv_reference_formula iv_shift_cols = iv_shift_cols iv_shift_rows = iv_shift_rows ). CONCATENATE 'Wrong result in test' lv_counter 'shifting formula ' iv_reference_formula INTO lv_message SEPARATED BY space. cl_abap_unit_assert=>assert_equals( act = lv_resulting_formula exp = iv_expected msg = lv_message quit = 0 "" continue tests level = if_aunit_constants=>critical ). CATCH zcx_excel. CONCATENATE 'Unexpected exception occurred in test' lv_counter 'shifting formula ' iv_reference_formula INTO lv_message SEPARATED BY space. cl_abap_unit_assert=>assert_equals( act = lv_resulting_formula exp = iv_expected msg = lv_message quit = 0 "" continue tests level = if_aunit_constants=>critical ). ENDTRY. ENDMETHOD. METHOD shift_formula_basic. "" Very basic check macro_shift_formula( iv_reference_formula = 'C17' iv_shift_cols = 0 iv_shift_rows = 0 iv_expected = 'C17' ). ENDMETHOD. METHOD shift_formula_rightdown. "" Check shift right and down macro_shift_formula( iv_reference_formula = 'C17' iv_shift_cols = 2 iv_shift_rows = 3 iv_expected = 'E20' ). ENDMETHOD. METHOD shift_formula_leftup. "" Check shift left and up macro_shift_formula( iv_reference_formula = 'C17' iv_shift_cols = -2 iv_shift_rows = -3 iv_expected = 'A14' ). ENDMETHOD. METHOD shift_formula_fixedcolrows. "" Fixed columns/rows macro_shift_formula( iv_reference_formula = '$C$17' iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = '$C$17' ). ENDMETHOD. METHOD shift_formula_mixedfixedrows. "" Operators and Ranges, mixed fixed rows or columns macro_shift_formula( iv_reference_formula = 'SUM($C17:C$23)+C30' iv_shift_cols = 1 iv_shift_rows = 11 iv_expected = 'SUM($C28:D$23)+D41' ). ENDMETHOD. METHOD shift_formula_rangename. "" Operators and Rangename macro_shift_formula( iv_reference_formula = 'RNGNAME1+C7' iv_shift_cols = -1 iv_shift_rows = -4 iv_expected = 'RNGNAME1+B3' ). ENDMETHOD. METHOD shift_formula_stringlitconc. "" String literals and string concatenation macro_shift_formula( iv_reference_formula = '""Date:""&TEXT(B2)' iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = '""Date:""&TEXT(C3)' ). ENDMETHOD. METHOD shift_formula_extref. "" External sheet reference macro_shift_formula( iv_reference_formula = '[TEST6.XLSX]SHEET1!A1' iv_shift_cols = 1 iv_shift_rows = 11 iv_expected = '[TEST6.XLSX]SHEET1!B12' ). ENDMETHOD. METHOD shift_formula_charblanks. "" superflous blanks, multi-argument functions, literals in function, unknown functions macro_shift_formula( iv_reference_formula = `X(B13, ""KK"" ) ` iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = `X(C14, ""KK"" ) ` ). ENDMETHOD. METHOD shift_formula_stringblanks. "" same as above - but with string input instead of Char-input macro_shift_formula( iv_reference_formula = `SIN(SIN(SIN(SIN(E22))))` iv_shift_cols = 0 iv_shift_rows = 1 iv_expected = 'SIN(SIN(SIN(SIN(E23))))' ). ENDMETHOD. METHOD shift_formula_funcnoargs. "" Functions w/o arguments, No cellreferences macro_shift_formula( iv_reference_formula = 'HEUTE()' iv_shift_cols = 2 iv_shift_rows = 5 iv_expected = 'HEUTE()' ). ENDMETHOD. METHOD shift_formula_nocellref. "" No cellreferences macro_shift_formula( iv_reference_formula = '""B2""' iv_shift_cols = 2 iv_shift_rows = 5 iv_expected = '""B2""' ). ENDMETHOD. METHOD shift_formula_empty. "" Empty macro_shift_formula( iv_reference_formula = '' iv_shift_cols = 2 iv_shift_rows = 5 iv_expected = '' ). ENDMETHOD. METHOD shift_formula_referr_colunder. "" Referencing error , column only , underflow macro_shift_formula( iv_reference_formula = 'A1+$A1+A$1+$A$1+B2' iv_shift_cols = -1 iv_shift_rows = 0 iv_expected = '#REF!+$A1+#REF!+$A$1+A2' ). ENDMETHOD. METHOD shift_formula_referr_rowunder. "" Referencing error , row only , underflow macro_shift_formula( iv_reference_formula = 'A1+$A1+A$1+$A$1+B2' iv_shift_cols = 0 iv_shift_rows = -1 iv_expected = '#REF!+#REF!+A$1+$A$1+B1' ). ENDMETHOD. METHOD shift_formula_referr_rowcolund. "" Referencing error , row and column , underflow macro_shift_formula( iv_reference_formula = 'A1+$A1+A$1+$A$1+B2' iv_shift_cols = -1 iv_shift_rows = -1 iv_expected = '#REF!+#REF!+#REF!+$A$1+A1' ). ENDMETHOD. METHOD shift_formula_sheet_nodigit. "" Sheet name not ending with digit macro_shift_formula( iv_reference_formula = 'Sheet!A1' iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = 'Sheet!B2' ). ENDMETHOD. METHOD shift_formula_sheet_nodig. "" Sheet name ending with digit macro_shift_formula( iv_reference_formula = 'Sheet2!A1' iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = 'Sheet2!B2' ). ENDMETHOD. METHOD shift_formula_sheet_special. "" Sheet name with special characters macro_shift_formula( iv_reference_formula = |'Sheet name'!A1| iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = |'Sheet name'!B2| ). ENDMETHOD. METHOD shift_formula_resp_blanks_1. "" Respecting blanks macro_shift_formula( iv_reference_formula = 'SUBTOTAL(109,Table1[SUM 1])' iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = 'SUBTOTAL(109,Table1[SUM 1])' ). ENDMETHOD. METHOD shift_formula_resp_blanks_2. "" Respecting blanks macro_shift_formula( iv_reference_formula = 'B4 & C4' iv_shift_cols = 0 iv_shift_rows = 1 iv_expected = 'B5 & C5' ). ENDMETHOD. METHOD shift_formula_range. "" F_1 is a range name, not a cell address macro_shift_formula( iv_reference_formula = 'SUM(F_1,F_2)' iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = 'SUM(F_1,F_2)' ). ENDMETHOD. METHOD shift_formula_notcols. "" RC are not columns macro_shift_formula( iv_reference_formula = 'INDIRECT(""RC[4]"",FALSE)' iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = 'INDIRECT(""RC[4]"",FALSE)' ). ENDMETHOD. METHOD shift_formula_name. "" A1 is a sheet name macro_shift_formula( iv_reference_formula = |'A1'!$A$1| iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = |'A1'!$A$1| ). ENDMETHOD. METHOD shift_formula_refcolumn1. "" Reference to another column in the same row of a Table, with a space in the column name macro_shift_formula( iv_reference_formula = 'Tbl[[#This Row],[Air fare]]' iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = 'Tbl[[#This Row],[Air fare]]' ). ENDMETHOD. METHOD shift_formula_refcolumn2. "" Reference to another column in the same row of a Table, inside more complex expression macro_shift_formula( iv_reference_formula = 'Tbl[[#This Row],[Air]]+A1' iv_shift_cols = 1 iv_shift_rows = 1 iv_expected = 'Tbl[[#This Row],[Air]]+B2' ). ENDMETHOD. METHOD is_cell_in_range_ulc_in. * Test 1: upper left corner (in range) DATA ep_cell_in_range TYPE abap_bool. TRY. ep_cell_in_range = zcl_excel_common=>is_cell_in_range( ip_column = 'B' ip_row = 2 ip_range = 'B2:D4' ). cl_abap_unit_assert=>assert_equals( act = ep_cell_in_range exp = abap_true msg = 'Check cell in range failed' level = if_aunit_constants=>critical ). CATCH zcx_excel. cl_abap_unit_assert=>fail( msg = 'Unexpected exception' level = if_aunit_constants=>critical ). ENDTRY. ENDMETHOD. ""is_cell_in_range_ulc_in METHOD is_cell_in_range_lrc_in. * Test 2: lower right corner (in range) DATA ep_cell_in_range TYPE abap_bool. TRY. ep_cell_in_range = zcl_excel_common=>is_cell_in_range( ip_column = 'D' ip_row = 4 ip_range = 'B2:D4' ). cl_abap_unit_assert=>assert_equals( act = ep_cell_in_range exp = abap_true msg = 'Check cell in range failed' level = if_aunit_constants=>critical ). CATCH zcx_excel. cl_abap_unit_assert=>fail( msg = 'Unexpected exception' level = if_aunit_constants=>critical ). ENDTRY. ENDMETHOD. ""is_cell_in_range_lrc_in METHOD is_cell_in_range_leftside_out. * Test 3: left side (out of range) DATA ep_cell_in_range TYPE abap_bool. TRY. ep_cell_in_range = zcl_excel_common=>is_cell_in_range( ip_column = 'A' ip_row = 3 ip_range = 'B2:D4' ). cl_abap_unit_assert=>assert_equals( act = ep_cell_in_range exp = abap_false msg = 'Check cell in range failed' level = if_aunit_constants=>critical ). CATCH zcx_excel. cl_abap_unit_assert=>fail( msg = 'Unexpected exception' level = if_aunit_constants=>critical ). ENDTRY. ENDMETHOD. ""is_cell_in_range_leftside_out METHOD is_cell_in_range_upperside_out. * Test 4: upper side (out of range) DATA ep_cell_in_range TYPE abap_bool. TRY. ep_cell_in_range = zcl_excel_common=>is_cell_in_range( ip_column = 'C' ip_row = 1 ip_range = 'B2:D4' ). cl_abap_unit_assert=>assert_equals( act = ep_cell_in_range exp = abap_false msg = 'Check cell in range failed' level = if_aunit_constants=>critical ). CATCH zcx_excel. cl_abap_unit_assert=>fail( msg = 'Unexpected exception' level = if_aunit_constants=>critical ). ENDTRY. ENDMETHOD. ""is_cell_in_range_upperside_out METHOD is_cell_in_range_rightside_out. * Test 5: right side (out of range) DATA ep_cell_in_range TYPE abap_bool. TRY. ep_cell_in_range = zcl_excel_common=>is_cell_in_range( ip_column = 'E' ip_row = 3 ip_range = 'B2:D4' ). cl_abap_unit_assert=>assert_equals( act = ep_cell_in_range exp = abap_false msg = 'Check cell in range failed' level = if_aunit_constants=>critical ). CATCH zcx_excel. cl_abap_unit_assert=>fail( msg = 'Unexpected exception' level = if_aunit_constants=>critical ). ENDTRY. ENDMETHOD. ""is_cell_in_range_rightside_out METHOD is_cell_in_range_lowerside_out. * Test 6: lower side (out of range) DATA ep_cell_in_range TYPE abap_bool. TRY. ep_cell_in_range = zcl_excel_common=>is_cell_in_range( ip_column = 'C' ip_row = 5 ip_range = 'B2:D4' ). cl_abap_unit_assert=>assert_equals( act = ep_cell_in_range exp = abap_false msg = 'Check cell in range failed' level = if_aunit_constants=>critical ). CATCH zcx_excel. cl_abap_unit_assert=>fail( msg = 'Unexpected exception' level = if_aunit_constants=>critical ). ENDTRY. ENDMETHOD. ""is_cell_in_range_lowerside_out. ENDCLASS. ",12429,True,2561.5130074860494,median "CLASS zcl_abapgit_gui_page_diff DEFINITION PUBLIC INHERITING FROM zcl_abapgit_gui_page CREATE PUBLIC. PUBLIC SECTION. TYPES: BEGIN OF ty_file_diff, path TYPE string, filename TYPE string, obj_type TYPE string, obj_name TYPE string, lstate TYPE char1, rstate TYPE char1, fstate TYPE char1, "" FILE state - Abstraction for shorter ifs o_diff TYPE REF TO zcl_abapgit_diff, changed_by TYPE xubname, type TYPE string, END OF ty_file_diff. TYPES: tt_file_diff TYPE STANDARD TABLE OF ty_file_diff WITH NON-UNIQUE DEFAULT KEY WITH NON-UNIQUE SORTED KEY secondary COMPONENTS path filename. CONSTANTS: BEGIN OF c_fstate, local TYPE char1 VALUE 'L', remote TYPE char1 VALUE 'R', both TYPE char1 VALUE 'B', END OF c_fstate. METHODS constructor IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key !is_file TYPE zif_abapgit_definitions=>ty_file OPTIONAL !is_object TYPE zif_abapgit_definitions=>ty_item OPTIONAL RAISING zcx_abapgit_exception. METHODS zif_abapgit_gui_event_handler~on_event REDEFINITION. PROTECTED SECTION. DATA mv_unified TYPE abap_bool VALUE abap_true ##NO_TEXT. DATA mo_repo TYPE REF TO zcl_abapgit_repo. DATA mt_diff_files TYPE tt_file_diff . METHODS: get_normalized_fname_with_path IMPORTING is_diff TYPE ty_file_diff RETURNING VALUE(rv_filename) TYPE string, normalize_path IMPORTING iv_path TYPE string RETURNING VALUE(rv_normalized) TYPE string, normalize_filename IMPORTING iv_filename TYPE string RETURNING VALUE(rv_normalized) TYPE string, render_content REDEFINITION, add_menu_end IMPORTING io_menu TYPE REF TO zcl_abapgit_html_toolbar , calculate_diff IMPORTING is_file TYPE zif_abapgit_definitions=>ty_file OPTIONAL is_object TYPE zif_abapgit_definitions=>ty_item OPTIONAL RAISING zcx_abapgit_exception, add_menu_begin IMPORTING io_menu TYPE REF TO zcl_abapgit_html_toolbar, render_table_head_non_unified IMPORTING io_html TYPE REF TO zcl_abapgit_html is_diff TYPE ty_file_diff, render_beacon_begin_of_row IMPORTING io_html TYPE REF TO zcl_abapgit_html is_diff TYPE ty_file_diff, render_diff_head_after_state IMPORTING io_html TYPE REF TO zcl_abapgit_html is_diff TYPE ty_file_diff, insert_nav RETURNING VALUE(rv_insert_nav) TYPE abap_bool, render_line_split_row IMPORTING io_html TYPE REF TO zcl_abapgit_html iv_filename TYPE string is_diff_line TYPE zif_abapgit_definitions=>ty_diff iv_index TYPE sy-tabix iv_fstate TYPE char1 iv_new TYPE string iv_old TYPE string RAISING zcx_abapgit_exception, build_menu RETURNING VALUE(ro_menu) TYPE REF TO zcl_abapgit_html_toolbar. PRIVATE SECTION. CONSTANTS: BEGIN OF c_actions, toggle_unified TYPE string VALUE 'toggle_unified', END OF c_actions . DATA mt_delayed_lines TYPE zif_abapgit_definitions=>ty_diffs_tt . DATA mv_repo_key TYPE zif_abapgit_persistence=>ty_repo-key . DATA mv_seed TYPE string . "" Unique page id to bind JS sessionStorage METHODS render_diff IMPORTING !is_diff TYPE ty_file_diff RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html RAISING zcx_abapgit_exception . METHODS render_diff_head IMPORTING !is_diff TYPE ty_file_diff RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_table_head IMPORTING !is_diff TYPE ty_file_diff RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_beacon IMPORTING !is_diff_line TYPE zif_abapgit_definitions=>ty_diff !is_diff TYPE ty_file_diff RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS render_line_split IMPORTING !is_diff_line TYPE zif_abapgit_definitions=>ty_diff !iv_filename TYPE string !iv_fstate TYPE char1 !iv_index TYPE sy-tabix RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html RAISING zcx_abapgit_exception . METHODS render_line_unified IMPORTING !is_diff_line TYPE zif_abapgit_definitions=>ty_diff OPTIONAL RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html . METHODS append_diff IMPORTING !it_remote TYPE zif_abapgit_definitions=>ty_files_tt !it_local TYPE zif_abapgit_definitions=>ty_files_item_tt !is_status TYPE zif_abapgit_definitions=>ty_result RAISING zcx_abapgit_exception . METHODS is_binary IMPORTING !iv_d1 TYPE xstring !iv_d2 TYPE xstring RETURNING VALUE(rv_yes) TYPE abap_bool . METHODS add_jump_sub_menu IMPORTING !io_menu TYPE REF TO zcl_abapgit_html_toolbar . METHODS add_filter_sub_menu IMPORTING io_menu TYPE REF TO zcl_abapgit_html_toolbar . METHODS render_lines IMPORTING is_diff TYPE ty_file_diff RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html RAISING zcx_abapgit_exception. METHODS render_table_head_unified IMPORTING io_html TYPE REF TO zcl_abapgit_html. METHODS render_scripts RETURNING VALUE(ro_html) TYPE REF TO zcl_abapgit_html RAISING zcx_abapgit_exception. ENDCLASS. CLASS ZCL_ABAPGIT_GUI_PAGE_DIFF IMPLEMENTATION. METHOD add_filter_sub_menu. DATA: lo_sub_filter TYPE REF TO zcl_abapgit_html_toolbar, lt_types TYPE string_table, lt_users TYPE string_table. FIELD-SYMBOLS: LIKE LINE OF mt_diff_files, TYPE string. "" Get unique LOOP AT mt_diff_files ASSIGNING . APPEND -type TO lt_types. APPEND -changed_by TO lt_users. ENDLOOP. SORT lt_types. DELETE ADJACENT DUPLICATES FROM lt_types. SORT lt_users. DELETE ADJACENT DUPLICATES FROM lt_users. IF lines( lt_types ) > 1 OR lines( lt_users ) > 1. CREATE OBJECT lo_sub_filter EXPORTING iv_id = 'diff-filter'. "" File types IF lines( lt_types ) > 1. lo_sub_filter->add( iv_txt = 'TYPE' iv_typ = zif_abapgit_html=>c_action_type-separator ). LOOP AT lt_types ASSIGNING . lo_sub_filter->add( iv_txt = iv_typ = zif_abapgit_html=>c_action_type-onclick iv_aux = 'type' iv_chk = abap_true ). ENDLOOP. ENDIF. "" Changed by IF lines( lt_users ) > 1. lo_sub_filter->add( iv_txt = 'CHANGED BY' iv_typ = zif_abapgit_html=>c_action_type-separator ). LOOP AT lt_users ASSIGNING . lo_sub_filter->add( iv_txt = iv_typ = zif_abapgit_html=>c_action_type-onclick iv_aux = 'changed-by' iv_chk = abap_true ). ENDLOOP. ENDIF. io_menu->add( iv_txt = 'Filter' io_sub = lo_sub_filter ) ##NO_TEXT. ENDIF. ENDMETHOD. METHOD add_jump_sub_menu. DATA: lo_sub_jump TYPE REF TO zcl_abapgit_html_toolbar, lv_jump_target TYPE string. FIELD-SYMBOLS: LIKE LINE OF mt_diff_files. CREATE OBJECT lo_sub_jump EXPORTING iv_id = 'jump'. LOOP AT mt_diff_files ASSIGNING . lv_jump_target = -path && -filename. lo_sub_jump->add( iv_id = |li_jump_{ sy-tabix }| iv_txt = lv_jump_target iv_typ = zif_abapgit_html=>c_action_type-onclick ). ENDLOOP. io_menu->add( iv_txt = 'Jump' io_sub = lo_sub_jump ) ##NO_TEXT. ENDMETHOD. METHOD add_menu_begin. ENDMETHOD. METHOD add_menu_end. io_menu->add( iv_txt = 'Split/Unified view' iv_act = c_actions-toggle_unified ) ##NO_TEXT. ENDMETHOD. METHOD append_diff. DATA: lv_offs TYPE i, ls_r_dummy LIKE LINE OF it_remote ##NEEDED, ls_l_dummy LIKE LINE OF it_local ##NEEDED. FIELD-SYMBOLS: LIKE LINE OF it_remote, LIKE LINE OF it_local, LIKE LINE OF mt_diff_files. READ TABLE it_remote ASSIGNING WITH KEY filename = is_status-filename path = is_status-path. IF sy-subrc <> 0. ASSIGN ls_r_dummy TO . ENDIF. READ TABLE it_local ASSIGNING WITH KEY file-filename = is_status-filename file-path = is_status-path. IF sy-subrc <> 0. ASSIGN ls_l_dummy TO . ENDIF. IF IS INITIAL AND IS INITIAL. zcx_abapgit_exception=>raise( |DIFF: file not found { is_status-filename }| ). ENDIF. APPEND INITIAL LINE TO mt_diff_files ASSIGNING . -path = is_status-path. -filename = is_status-filename. -obj_type = is_status-obj_type. -obj_name = is_status-obj_name. -lstate = is_status-lstate. -rstate = is_status-rstate. IF -lstate IS NOT INITIAL AND -rstate IS NOT INITIAL. -fstate = c_fstate-both. ELSEIF -lstate IS NOT INITIAL. -fstate = c_fstate-local. ELSE. ""rstate IS NOT INITIAL, lstate = empty. -fstate = c_fstate-remote. ENDIF. "" Changed by IF -item-obj_type IS NOT INITIAL. -changed_by = to_lower( zcl_abapgit_objects=>changed_by( -item ) ). ENDIF. IF -changed_by IS INITIAL. -changed_by = to_lower( zcl_abapgit_objects_super=>c_user_unknown ). ENDIF. "" Extension IF -file-filename IS NOT INITIAL. -type = reverse( -file-filename ). ELSE. -type = reverse( -filename ). ENDIF. FIND FIRST OCCURRENCE OF '.' IN -type MATCH OFFSET lv_offs. -type = reverse( substring( val = -type len = lv_offs ) ). IF -type <> 'xml' AND -type <> 'abap'. -type = 'other'. ENDIF. IF -type = 'other' AND is_binary( iv_d1 = -data iv_d2 = -file-data ) = abap_true. -type = 'binary'. ENDIF. "" Diff data IF -type <> 'binary'. IF -fstate = c_fstate-remote. "" Remote file leading changes CREATE OBJECT -o_diff EXPORTING iv_new = -data iv_old = -file-data. ELSE. "" Local leading changes or both were modified CREATE OBJECT -o_diff EXPORTING iv_new = -file-data iv_old = -data. ENDIF. ENDIF. ENDMETHOD. METHOD build_menu. CREATE OBJECT ro_menu. add_menu_begin( ro_menu ). add_jump_sub_menu( ro_menu ). add_filter_sub_menu( ro_menu ). add_menu_end( ro_menu ). ENDMETHOD. METHOD calculate_diff. DATA: lt_remote TYPE zif_abapgit_definitions=>ty_files_tt, lt_local TYPE zif_abapgit_definitions=>ty_files_item_tt, lt_status TYPE zif_abapgit_definitions=>ty_results_tt. FIELD-SYMBOLS: LIKE LINE OF lt_status. CLEAR: mt_diff_files. lt_remote = mo_repo->get_files_remote( ). lt_local = mo_repo->get_files_local( ). mo_repo->reset_status( ). lt_status = mo_repo->status( ). IF is_file IS NOT INITIAL. "" Diff for one file READ TABLE lt_status ASSIGNING WITH KEY path = is_file-path filename = is_file-filename. append_diff( it_remote = lt_remote it_local = lt_local is_status = ). ELSEIF is_object IS NOT INITIAL. "" Diff for whole object LOOP AT lt_status ASSIGNING WHERE obj_type = is_object-obj_type AND obj_name = is_object-obj_name AND match IS INITIAL. append_diff( it_remote = lt_remote it_local = lt_local is_status = ). ENDLOOP. ELSE. "" Diff for the whole repo SORT lt_status BY path ASCENDING filename ASCENDING. LOOP AT lt_status ASSIGNING WHERE match IS INITIAL. append_diff( it_remote = lt_remote it_local = lt_local is_status = ). ENDLOOP. ENDIF. ENDMETHOD. METHOD constructor. DATA: lv_ts TYPE timestamp. super->constructor( ). ms_control-page_title = 'DIFF'. mv_unified = zcl_abapgit_persistence_user=>get_instance( )->get_diff_unified( ). mv_repo_key = iv_key. mo_repo ?= zcl_abapgit_repo_srv=>get_instance( )->get( iv_key ). GET TIME STAMP FIELD lv_ts. mv_seed = |diff{ lv_ts }|. "" Generate based on time ASSERT is_file IS INITIAL OR is_object IS INITIAL. "" just one passed calculate_diff( is_file = is_file is_object = is_object ). IF lines( mt_diff_files ) = 0. zcx_abapgit_exception=>raise( 'PAGE_DIFF ERROR: No diff files found' ). ENDIF. ms_control-page_menu = build_menu( ). ENDMETHOD. METHOD get_normalized_fname_with_path. rv_filename = normalize_path( is_diff-path ) && `_` && normalize_filename( is_diff-filename ). ENDMETHOD. METHOD insert_nav. ENDMETHOD. METHOD is_binary. FIELD-SYMBOLS LIKE iv_d1. IF iv_d1 IS NOT INITIAL. "" One of them might be new and so empty ASSIGN iv_d1 TO . ELSE. ASSIGN iv_d2 TO . ENDIF. rv_yes = zcl_abapgit_utils=>is_binary( ). ENDMETHOD. METHOD normalize_filename. rv_normalized = replace( val = iv_filename sub = '.' occ = 0 with = '_' ). ENDMETHOD. METHOD normalize_path. rv_normalized = replace( val = iv_path sub = '/' occ = 0 with = '_' ). ENDMETHOD. METHOD render_beacon. DATA: lv_beacon TYPE string, lt_beacons TYPE zif_abapgit_definitions=>ty_string_tt. CREATE OBJECT ro_html. IF is_diff_line-beacon > 0. lt_beacons = is_diff-o_diff->get_beacons( ). READ TABLE lt_beacons INTO lv_beacon INDEX is_diff_line-beacon. ELSE. lv_beacon = '---'. ENDIF. ro_html->add( '' ). ro_html->add( '' ). render_beacon_begin_of_row( io_html = ro_html is_diff = is_diff ). IF mv_unified = abap_true. ro_html->add( '' ). ro_html->add( '' ). ro_html->add( |@@ { is_diff_line-new_num } @@ { lv_beacon }| ). ELSE. ro_html->add( |@@ { is_diff_line-new_num } @@ { lv_beacon }| ). ENDIF. ro_html->add( '' ). ro_html->add( '' ). ENDMETHOD. METHOD render_beacon_begin_of_row. io_html->add( '' ). ENDMETHOD. METHOD render_content. DATA: ls_diff_file LIKE LINE OF mt_diff_files, li_progress TYPE REF TO zif_abapgit_progress. CREATE OBJECT ri_html TYPE zcl_abapgit_html. li_progress = zcl_abapgit_progress=>get_instance( lines( mt_diff_files ) ). ri_html->add( |
    | ). ri_html->add( zcl_abapgit_gui_chunk_lib=>render_js_error_banner( ) ). LOOP AT mt_diff_files INTO ls_diff_file. li_progress->show( iv_current = sy-tabix iv_text = |Render Diff - { ls_diff_file-filename }| ). ri_html->add( render_diff( ls_diff_file ) ). ENDLOOP. IF sy-subrc <> 0. ri_html->add( |No more diffs| ). ENDIF. ri_html->add( '
    ' ). register_deferred_script( render_scripts( ) ). ENDMETHOD. METHOD render_diff. CREATE OBJECT ro_html. ro_html->add( |
    | ). ""#EC NOTEXT ro_html->add( render_diff_head( is_diff ) ). "" Content IF is_diff-type <> 'binary'. ro_html->add( '
    ' ). ""#EC NOTEXT ro_html->add( || ). ""#EC NOTEXT ro_html->add( render_table_head( is_diff ) ). ro_html->add( render_lines( is_diff ) ). ro_html->add( '
    ' ). ""#EC NOTEXT ELSE. ro_html->add( '
    ' ). ""#EC NOTEXT ro_html->add( 'The content seems to be binary.' ). ""#EC NOTEXT ro_html->add( 'Cannot display as diff.' ). ""#EC NOTEXT ENDIF. ro_html->add( '
    ' ). ""#EC NOTEXT ro_html->add( '
    ' ). ""#EC NOTEXT ENDMETHOD. METHOD render_diff_head. DATA: ls_stats TYPE zif_abapgit_definitions=>ty_count, lv_adt_link TYPE string. CREATE OBJECT ro_html. ro_html->add( '
    ' ). ""#EC NOTEXT ro_html->add_icon( iv_name = 'chevron-down' iv_hint = 'Collapse/Expand' iv_class = 'cursor-pointer' iv_onclick = 'onDiffCollapse(event)' ). IF is_diff-type <> 'binary'. ls_stats = is_diff-o_diff->stats( ). IF is_diff-fstate = c_fstate-both. "" Merge stats into 'update' if both were changed ls_stats-update = ls_stats-update + ls_stats-insert + ls_stats-delete. CLEAR: ls_stats-insert, ls_stats-delete. ENDIF. ro_html->add( |+ { ls_stats-insert }| ). ro_html->add( |- { ls_stats-delete }| ). ro_html->add( |~ { ls_stats-update }| ). ENDIF. "" no links for nonexistent or deleted objects IF is_diff-lstate IS NOT INITIAL AND is_diff-lstate <> 'D'. lv_adt_link = zcl_abapgit_html=>a( iv_txt = |{ is_diff-path }{ is_diff-filename }| iv_typ = zif_abapgit_html=>c_action_type-sapevent iv_act = |jump?TYPE={ is_diff-obj_type }&NAME={ is_diff-obj_name }| ). ENDIF. IF lv_adt_link IS NOT INITIAL. ro_html->add( |{ lv_adt_link }| ). ""#EC NOTEXT ELSE. ro_html->add( |{ is_diff-path }{ is_diff-filename }| ). ""#EC NOTEXT ENDIF. ro_html->add( zcl_abapgit_gui_chunk_lib=>render_item_state( iv_lstate = is_diff-lstate iv_rstate = is_diff-rstate ) ). render_diff_head_after_state( io_html = ro_html is_diff = is_diff ). ro_html->add( |last change by: { is_diff-changed_by }| ). ro_html->add( '
    ' ). ""#EC NOTEXT ENDMETHOD. METHOD render_diff_head_after_state. IF is_diff-fstate = c_fstate-both AND mv_unified = abap_true. io_html->add( 'Attention: Unified mode' && ' highlighting for MM assumes local file is newer ! ' ). ""#EC NOTEXT ENDIF. ENDMETHOD. METHOD render_lines. DATA: lo_highlighter TYPE REF TO zcl_abapgit_syntax_highlighter, lt_diffs TYPE zif_abapgit_definitions=>ty_diffs_tt, lv_insert_nav TYPE abap_bool, lv_tabix TYPE syst-tabix. FIELD-SYMBOLS LIKE LINE OF lt_diffs. lo_highlighter = zcl_abapgit_syntax_highlighter=>create( is_diff-filename ). CREATE OBJECT ro_html. lt_diffs = is_diff-o_diff->get( ). lv_insert_nav = insert_nav( ). LOOP AT lt_diffs ASSIGNING . lv_tabix = sy-tabix. IF -short = abap_false. lv_insert_nav = abap_true. CONTINUE. ENDIF. IF lv_insert_nav = abap_true. "" Insert separator line with navigation ro_html->add( render_beacon( is_diff_line = is_diff = is_diff ) ). lv_insert_nav = abap_false. ENDIF. IF lo_highlighter IS BOUND. -new = lo_highlighter->process_line( -new ). -old = lo_highlighter->process_line( -old ). ELSE. -new = escape( val = -new format = cl_abap_format=>e_html_attr ). -old = escape( val = -old format = cl_abap_format=>e_html_attr ). ENDIF. CONDENSE -new_num. ""get rid of leading spaces CONDENSE -old_num. IF mv_unified = abap_true. ro_html->add( render_line_unified( is_diff_line = ) ). ELSE. ro_html->add( render_line_split( is_diff_line = iv_filename = get_normalized_fname_with_path( is_diff ) iv_fstate = is_diff-fstate iv_index = lv_tabix ) ). ENDIF. ENDLOOP. IF mv_unified = abap_true. ro_html->add( render_line_unified( ) ). "" Release delayed lines ENDIF. ENDMETHOD. METHOD render_line_split. DATA: lv_new TYPE string, lv_old TYPE string, lv_mark TYPE string, lv_bg TYPE string. CREATE OBJECT ro_html. "" New line lv_mark = ` `. IF is_diff_line-result IS NOT INITIAL. IF iv_fstate = c_fstate-both OR is_diff_line-result = zif_abapgit_definitions=>c_diff-update. lv_bg = ' diff_upd'. lv_mark = `~`. ELSEIF is_diff_line-result = zif_abapgit_definitions=>c_diff-insert. lv_bg = ' diff_ins'. lv_mark = `+`. ENDIF. ENDIF. lv_new = || && |{ lv_mark }| && |{ is_diff_line-new }|. "" Old line CLEAR lv_bg. lv_mark = ` `. IF is_diff_line-result IS NOT INITIAL. IF iv_fstate = c_fstate-both OR is_diff_line-result = zif_abapgit_definitions=>c_diff-update. lv_bg = ' diff_upd'. lv_mark = `~`. ELSEIF is_diff_line-result = zif_abapgit_definitions=>c_diff-delete. lv_bg = ' diff_del'. lv_mark = `-`. ENDIF. ENDIF. lv_old = || && |{ lv_mark }| && |{ is_diff_line-old }|. "" render line, inverse sides if remote is newer ro_html->add( '' ). ""#EC NOTEXT render_line_split_row( io_html = ro_html iv_filename = iv_filename is_diff_line = is_diff_line iv_index = iv_index iv_fstate = iv_fstate iv_old = lv_old iv_new = lv_new ). ro_html->add( '' ). ""#EC NOTEXT ENDMETHOD. METHOD render_line_split_row. IF iv_fstate = c_fstate-remote. "" Remote file leading changes io_html->add( iv_old ). "" local io_html->add( iv_new ). "" remote ELSE. "" Local leading changes or both were modified io_html->add( iv_new ). "" local io_html->add( iv_old ). "" remote ENDIF. ENDMETHOD. METHOD render_line_unified. FIELD-SYMBOLS LIKE LINE OF mt_delayed_lines. CREATE OBJECT ro_html. "" Release delayed subsequent update lines IF is_diff_line-result <> zif_abapgit_definitions=>c_diff-update. LOOP AT mt_delayed_lines ASSIGNING . ro_html->add( '' ). ""#EC NOTEXT ro_html->add( |-old_num }"">| && || && |-| && |{ -old }| ). ro_html->add( '' ). ""#EC NOTEXT ENDLOOP. LOOP AT mt_delayed_lines ASSIGNING . ro_html->add( '' ). ""#EC NOTEXT ro_html->add( || && |-new_num }"">| && |+| && |{ -new }| ). ro_html->add( '' ). ""#EC NOTEXT ENDLOOP. CLEAR mt_delayed_lines. ENDIF. ro_html->add( '' ). ""#EC NOTEXT CASE is_diff_line-result. WHEN zif_abapgit_definitions=>c_diff-update. APPEND is_diff_line TO mt_delayed_lines. "" Delay output of subsequent updates WHEN zif_abapgit_definitions=>c_diff-insert. ro_html->add( || && || && |+| && |{ is_diff_line-new }| ). WHEN zif_abapgit_definitions=>c_diff-delete. ro_html->add( || && || && |-| && |{ is_diff_line-old }| ). WHEN OTHERS. ""none ro_html->add( || && || && | | && |{ is_diff_line-old }| ). ENDCASE. ro_html->add( '' ). ""#EC NOTEXT ENDMETHOD. METHOD render_scripts. CREATE OBJECT ro_html. ro_html->zif_abapgit_html~set_title( cl_abap_typedescr=>describe_by_object_ref( me )->get_relative_name( ) ). ro_html->add( 'restoreScrollPosition();' ). ro_html->add( 'var gHelper = new DiffHelper({' ). ro_html->add( | seed: ""{ mv_seed }"",| ). ro_html->add( ' ids: {' ). ro_html->add( ' jump: ""jump"",' ). ro_html->add( ' diffList: ""diff-list"",' ). ro_html->add( ' filterMenu: ""diff-filter"",' ). ro_html->add( ' }' ). ro_html->add( '});' ). ro_html->add( 'addMarginBottom();' ). ro_html->add( 'var gGoJumpPalette = new CommandPalette(enumerateJumpAllFiles, {' ). ro_html->add( ' toggleKey: ""F2"",' ). ro_html->add( ' hotkeyDescription: ""Jump to file ...""' ). ro_html->add( '});' ). "" Feature for selecting ABAP code by column and copy to clipboard ro_html->add( 'var columnSelection = new DiffColumnSelection();' ). ENDMETHOD. METHOD render_table_head. CREATE OBJECT ro_html. ro_html->add( '' ). ""#EC NOTEXT ro_html->add( '' ). ""#EC NOTEXT IF mv_unified = abap_true. render_table_head_unified( ro_html ). ELSE. render_table_head_non_unified( io_html = ro_html is_diff = is_diff ). ENDIF. ro_html->add( '' ). ""#EC NOTEXT ro_html->add( '' ). ""#EC NOTEXT ENDMETHOD. METHOD render_table_head_non_unified. io_html->add( '' ). ""#EC NOTEXT io_html->add( '' ). ""#EC NOTEXT io_html->add( 'LOCAL' ). ""#EC NOTEXT io_html->add( '' ). ""#EC NOTEXT io_html->add( '' ). ""#EC NOTEXT io_html->add( 'REMOTE' ). ""#EC NOTEXT ENDMETHOD. METHOD render_table_head_unified. io_html->add( 'old' ). ""#EC NOTEXT io_html->add( 'new' ). ""#EC NOTEXT io_html->add( '' ). ""#EC NOTEXT io_html->add( 'code' ). ""#EC NOTEXT ENDMETHOD. METHOD zif_abapgit_gui_event_handler~on_event. CASE iv_action. WHEN c_actions-toggle_unified. "" Toggle file diplay mv_unified = zcl_abapgit_persistence_user=>get_instance( )->toggle_diff_unified( ). ev_state = zcl_abapgit_gui=>c_event_state-re_render. WHEN OTHERS. super->zif_abapgit_gui_event_handler~on_event( EXPORTING iv_action = iv_action iv_getdata = iv_getdata it_postdata = it_postdata IMPORTING ei_page = ei_page ev_state = ev_state ). ENDCASE. ENDMETHOD. ENDCLASS. ",7939,False,1499.670220889452,median "*----------------------------------------------------------------------* ***INCLUDE ZAL30_MAIN_VIEW_F01 . *----------------------------------------------------------------------* *&---------------------------------------------------------------------* *& Form F4_VIEW *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM f4_view . DATA lo_excep TYPE REF TO zcx_al30. DATA ld_view TYPE tabname. TRY. CALL METHOD zcl_al30_util=>f4_view EXPORTING iv_program = sy-repid iv_dynpro = sy-dynnr iv_dynprofield = 'P_VIEW'. CATCH zcx_al30 INTO lo_excep. MESSAGE s018. ENDTRY. ENDFORM. "" F4_VIEW *&---------------------------------------------------------------------* *& Form VALIDACION_PANTALLA *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM chequeo_vista. DATA ls_return TYPE bapiret2. DATA ld_diff TYPE sap_bool. DATA ld_auth TYPE sap_bool. * Verifico que la vista/tabla sea correcta CALL METHOD mo_cnt_al30->check_view EXPORTING iv_name_view = zal30_t_view-tabname iv_operation = zif_al30_data=>cv_operation_read IMPORTING es_return = ls_return. IF ls_return-type = zif_al30_data=>cs_msg_type-error. "" Antes de dar el mensaje de error se mira si la tabla que se pide es la que gestiona la autorización "" de los usuarios. Si es así, lo que haré es crearla de manera automática. IF zal30_t_view-tabname = zif_al30_data=>cs_internal_tables-auth_user. PERFORM create_view_user_auth CHANGING ls_return. ENDIF. IF ls_return IS NOT INITIAL. MESSAGE ID ls_return-id TYPE ls_return-type NUMBER ls_return-number WITH ls_return-message_v1 ls_return-message_v2 ls_return-message_v3 ls_return-message_v4. ENDIF. ENDIF. "" Se lanza el chequeo autorización de la vista PERFORM check_autorization CHANGING ld_auth mv_mode. IF ld_auth = abap_false. MESSAGE e041. ELSE. "" Si tiene autorizacion pero para visualizar se informa IF mv_mode = zif_al30_data=>cv_mode_view. MESSAGE s042. ENDIF. ENDIF. * Lectura de los campos de la vista PERFORM read_view. * Miro que no existan diferencias entre la configuracion de la vista y el diccionario. * Si la vista no tiene el autoajuste automático no se puede continuar con la edición mo_cnt_al30->check_changes_dict_view( EXPORTING is_view = ms_view IMPORTING ev_diff_fields = DATA(lv_diff_fields) ev_diff_text = DATA(lv_diff_text) ). IF lv_diff_fields = abap_true OR lv_diff_text = abap_true. IF mo_cnt_al30->view_have_auto_adjust( ms_view-tabname ) = abap_true. mo_cnt_al30->auto_adjust_view_ddic( EXPORTING iv_name_view = ms_view-tabname IMPORTING es_return = ls_return et_fields_view_alv = mt_fields et_fields_text_view_alv = mt_fields_text es_view = ms_view et_foreign_key_ddic = mt_foreign_key_ddic ). "" Solo si hay errores en el ajuste IF ls_return-type = zif_al30_data=>cs_msg_type-error. MESSAGE ID ls_return-id TYPE ls_return-type NUMBER ls_return-number WITH ls_return-message_v1 ls_return-message_v2 ls_return-message_v3 ls_return-message_v4. ENDIF. ELSE. MESSAGE e024. ENDIF. ENDIF. * Se instancia la clase que gestionará las exit IF ms_view-exit_class IS NOT INITIAL. mo_cnt_al30->instance_exit_class( iv_exit_class = ms_view-exit_class ). ENDIF. * Se pasan los campos y vista a la clase de la vista para que los use mo_cnt_al30->set_data_conf_view( EXPORTING it_fields_view_alv = mt_fields it_fields_text_view_alv = mt_fields_text is_view = ms_view it_fields_ddic = mt_fields_ddic it_foreign_key_ddic = mt_foreign_key_ddic ). ENDFORM. "" VALIDACION_PANTALLA *&---------------------------------------------------------------------* *& Form INICIALIZACION_DATOS *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM inicializacion_datos . * Indico que los refrescos de los ALV no se moverán de filas y columna ms_stable-row = abap_true. ms_stable-col = abap_true. * Por defecto los datos son válidos mv_datos_validos = abap_true. ENDFORM. "" INICIALIZACION_DATOS *&---------------------------------------------------------------------* *& Form INICIALIZACION_PROG *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM inicializacion_prog . "" Creo el objeto que orquestará todas las operaciones dentro de los procesos de la AL30 IF mo_cnt_al30 IS NOT BOUND. CREATE OBJECT mo_cnt_al30. ENDIF. "" Se crea el controlador intenro del programa IF mo_controller IS NOT BOUND. CREATE OBJECT mo_controller. ENDIF. * Se informa el lenguaje de visualización IF mv_lang_vis IS INITIAL. mv_lang_vis = sy-langu. ENDIF. * Indico que los refrescos de los ALV no se moverán de filas y columna ms_stable-row = abap_true. ms_stable-col = abap_true. * Transacción original que se llama IF ms_conf_screen-origin_tcode IS INITIAL. ms_conf_screen-origin_tcode = cl_dynpro=>get_current_transaction( ). "" Se busca la descripción de la transacción original SELECT SINGLE ttext INTO ms_conf_screen-origin_tcode_text FROM tstct WHERE sprsl = sy-langu AND tcode = ms_conf_screen-origin_tcode. ENDIF. ENDFORM. "" INICIALIZACION_PROG *&---------------------------------------------------------------------* *& Form CATALOGO_CAMPOS_ALV *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM catalogo_campos_alv . DATA ls_return TYPE bapiret2. * El catalogo de campos como la tabla interna de datos tendrá campos adicionales * para la edicion. CALL METHOD mo_cnt_al30->get_fieldcat_view EXPORTING iv_mode = mv_mode IMPORTING es_return = ls_return et_fieldcat = mt_fieldcat. IF ls_return-type IS INITIAL. "" En modo de edición se añade el campo de acciones IF mv_mode = zif_al30_data=>cv_mode_change. zcl_al30_util=>read_single_data_element( EXPORTING iv_rollname = zif_al30_data=>cs_data_element-actions iv_langu = sy-langu IMPORTING es_info = DATA(ls_info) ). DATA(ls_fieldcat) = CORRESPONDING lvc_s_fcat( ls_info ). ls_fieldcat-fieldname = zif_al30_data=>cs_control_fields_alv_data-actions. ls_fieldcat-col_pos = 1. ls_fieldcat-icon = abap_true. ls_fieldcat-fix_column = abap_true. ls_fieldcat-hotspot = abap_true. INSERT ls_fieldcat INTO TABLE mt_fieldcat. CLEAR ls_fieldcat. ls_fieldcat-fieldname = zif_al30_data=>cs_control_fields_alv_data-row_status_msg. ls_fieldcat-col_pos = 999. ls_fieldcat-tech = abap_true. INSERT ls_fieldcat INTO TABLE mt_fieldcat. ls_fieldcat-fieldname = zif_al30_data=>cs_control_fields_alv_data-row_status. ls_fieldcat-col_pos = 999. ls_fieldcat-tech = abap_true. INSERT ls_fieldcat INTO TABLE mt_fieldcat. ENDIF. ELSE. * Si hay mensaje lo saco tal cual, aunque sea de error. MESSAGE ID ls_return-id TYPE ls_return-type NUMBER ls_return-number WITH ls_return-message_v1 ls_return-message_v2 ls_return-message_v3 ls_return-message_v4. ENDIF. ENDFORM. "" CATALOGO_CAMPOS_ALV *&---------------------------------------------------------------------* *& Form READ_DATA_VIEW *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM read_data_view . DATA ls_filter TYPE zif_al30_data=>ts_filter_read_data. CLEAR . "" Se lee los filtros de la tabla. No todas las tablas tendrán filtros porque depende "" de su configuración. READ TABLE ms_conf_screen-sel_screen ASSIGNING FIELD-SYMBOL() WITH KEY tabname = ms_view-tabname. IF sy-subrc = 0. ls_filter-fields_ranges = -fields_ranges. ls_filter-where_clauses = -where_clauses. ls_filter-expressions = -expressions. ENDIF. CALL METHOD mo_cnt_al30->read_data EXPORTING is_filters = ls_filter IMPORTING es_return = DATA(ls_return) CHANGING co_data = mo_datos. * Si hay un mensaje de error lo devuelvo como warning para que no salga del programa, * pero que se vea bien. IF ls_return-type = 'E'. MESSAGE ID ls_return-id TYPE 'W' NUMBER ls_return-number WITH ls_return-message_v1 ls_return-message_v2 ls_return-message_v3 ls_return-message_v4. ELSE. * Si un mensaje que no es de error lo saco para que se vea. Ya que podria ser el de las autorizaciones. IF ls_return IS NOT INITIAL. MESSAGE ID ls_return-id TYPE ls_return-type NUMBER ls_return-number WITH ls_return-message_v1 ls_return-message_v2 ls_return-message_v3 ls_return-message_v4. ENDIF. * En el modo edición recorro los datos para hacer lo siguiente se hace una ajuste de los campo segun sus valores. IF mv_mode = zif_al30_data=>cv_mode_change. PERFORM adjust_data_post_read. ENDIF. ENDIF. ENDFORM. "" READ_DATA_VIEW *&---------------------------------------------------------------------* *& Form CLEAN_DATA *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM clean_data . CLEAR: mv_mode, ms_view, mt_fields, , mv_text_view. IF mo_alv IS BOUND. mo_alv->free( ). mo_container->free( ). FREE: mo_alv, mo_container. ENDIF. ENDFORM. "" CLEAN_DATA *&---------------------------------------------------------------------* *& Form CREATE_IT_DATA_VIEW *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM create_it_data_view . "" Se lanza la creación de la tabla principal de datos, aunque la tabla es temporal porque lo que interesa "" es su estructura. Esta estructura servirá como base, en caso de edicicón, para añadir nuevos campos para "" construir la tabla definitiva. En caso de visualización se pasa la temporal a la definitiva. CALL METHOD mo_cnt_al30->create_it_data_view EXPORTING iv_mode = mv_mode IMPORTING et_data = DATA(lo_data) es_data = DATA(lo_wa_data) es_return = DATA(ls_return). IF ls_return-type IS INITIAL. "" En modo edición se añade el campo de acciones que sacará los semaforos si la línea tiene errores. IF mv_mode = zif_al30_data=>cv_mode_change.. DATA(lt_fcat) = VALUE lvc_t_fcat( ( fieldname = zif_al30_data=>cs_control_fields_alv_data-actions rollname = zif_al30_data=>cs_data_element-actions ) ). zcl_ca_dynamic_tables=>create_it_fields_base_ref( EXPORTING i_base_fields = lo_wa_data i_new_fields = lt_fcat IMPORTING e_table = mo_datos ). ELSE. "" En modo visualización se pasa la tabla generada a la global mo_datos = lo_data. ENDIF. ASSIGN mo_datos->* TO . * Si se esta en modo edicion, creo una replica que será la que guarde los registros que se borren IF mv_mode = zif_al30_data=>cv_mode_change. CALL METHOD mo_cnt_al30->create_it_data_view EXPORTING iv_mode = mv_mode IMPORTING et_data = mo_datos_del. ASSIGN mo_datos_del->* TO . ENDIF. ELSE. MESSAGE ID ls_return-id TYPE ls_return-type NUMBER ls_return-number WITH ls_return-message_v1 ls_return-message_v2 ls_return-message_v3 ls_return-message_v4. ENDIF. ENDFORM. "" CREATE_IT_DATA_VIEW *&---------------------------------------------------------------------* *& Form CREATE_DATA_VIEW *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM create_data_view . * Si la tabla tiene la opcion de grabar de entradas y el sistema permite transportar * entonces se solicitará orden de tranporte. IF ms_view-transport = abap_true AND mo_cnt_al30->allowed_transport( ) = abap_true. mv_pedir_orden = abap_true. ELSE. mv_pedir_orden = abap_false. ENDIF. * Si hay tabla de textos me quedo con el nombre del campo de idioma IF ms_view-texttable IS NOT INITIAL. READ TABLE mt_fields ASSIGNING FIELD-SYMBOL() WITH KEY lang_texttable = abap_true. IF sy-subrc = 0. mv_field_lang_textable = -fieldname. ENDIF. ENDIF. * Se bloquea la tabla para que no se pueda editar a la vez. Si no se puede bloquear se visualizarán los datos PERFORM lock_view. * Creo la tabla interna de datos PERFORM create_it_data_view. * Leo el catalogo de campos PERFORM catalogo_campos_alv. ENDFORM. "" CREATE_DATA_VIEW *&---------------------------------------------------------------------* *& Form DATA_CHANGED *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM data_changed CHANGING ps_data_changed TYPE REF TO cl_alv_changed_data_protocol ps_onf4 ps_onf4_before ps_onf4_after ps_ucomm. FIELD-SYMBOLS TYPE lvc_s_moce. DATA ls_control_data TYPE ts_control_data. DATA ld_tabix_ddic TYPE sytabix. * Inicialmente los datos son correctos. mv_datos_validos = abap_true. * Líneas borradas * Solo se borran las líneas que provienen del diccionario y que estarán * en la tabla . De esta manera se simplifica el tratamiento LOOP AT ps_data_changed->mt_deleted_rows ASSIGNING . PERFORM row_delete USING CHANGING ps_data_changed. ENDLOOP. * Líneas moificadas/insertadas * Esta es la parte más compleja porque en ""mp_mod_rows"" están las líneas * tanto insertadas como borradas. Y pueden modificar líneas que han sido previamente * insertadas PERFORM row_insert_modify CHANGING ps_data_changed. ENDFORM. "" DATA_CHANGED *&---------------------------------------------------------------------* *& Form ROW_DELETE *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM row_delete USING pe_rows TYPE lvc_s_moce CHANGING ps_data_changed TYPE REF TO cl_alv_changed_data_protocol. FIELD-SYMBOLS TYPE any. FIELD-SYMBOLS TYPE any. DATA ld_tabix TYPE sytabix. DATA ld_fieldname TYPE fieldname. * Me posicino en el registro marcado para borrar READ TABLE ASSIGNING INDEX pe_rows-row_id. IF sy-subrc = 0. * Miro si el registro viene del diccionario ASSIGN COMPONENT zif_al30_data=>cs_control_fields_alv_data-is_dict OF STRUCTURE TO . IF sy-subrc = 0. * Si viene del diccionario paso el registro a otra tabla. IF = abap_true. * Pongo el indicador de registro borrado, para tenerlo en cuenta en procesos posteriores. ASSIGN COMPONENT zif_al30_data=>cs_control_fields_alv_data-updkz OF STRUCTURE TO . IF sy-subrc = 0. = zif_al30_data=>cv_mode_delete. INSERT INITIAL LINE INTO TABLE ASSIGNING FIELD-SYMBOL(). = CORRESPONDING #( ). ENDIF. ENDIF. ENDIF. ENDIF. ENDFORM. "" ROW_DELETE *&---------------------------------------------------------------------* *& Form ROW_INSERT *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* FORM row_insert USING pe_modif TYPE lvc_s_modi pe_datos_im TYPE any CHANGING ps_data_changed TYPE REF TO cl_alv_changed_data_protocol. FIELD-SYMBOLS TYPE lvc_s_fcat. FIELD-SYMBOLS TYPE lvc_t_styl. * Lo primero que hago es habilitar los campos clave, ya que estos datos no éstán * guardados todavía en la base de datos LOOP AT mt_fieldcat ASSIGNING WHERE key = abap_true. "" Los estilos se modificarán directamente en la tabla porque al final de proceso se aplican los estilos "" que hayan podido ser modificados en las exit o procesos estándar ASSIGN COMPONENT zif_al30_data=>cs_control_fields_alv_data-style OF STRUCTURE pe_datos_im TO . IF sy-subrc = 0. READ TABLE ASSIGNING FIELD-SYMBOL() WITH KEY fieldname = -fieldname. IF sy-subrc = 0. -style = cl_gui_alv_grid=>mc_style_enabled. ELSE. INSERT VALUE #( fieldname = -fieldname style = cl_gui_alv_grid=>mc_style_enabled ) INTO TABLE . ENDIF. "" Se comenta porque si luego se cambia los estilos del mismo campo solo tiene en cuenta el primer registro del campo. * CALL METHOD ps_data_changed->modify_style * EXPORTING * i_row_id = pe_modif-row_id * i_fieldname = -fieldname * i_style = cl_gui_alv_grid=>mc_style_enabled. ENDIF. * Si el tipo de datos es mandante informo del mismo (necesario para el transporte). IF -datatype = zif_al30_data=>cs_datatype-mandt. CALL METHOD ps_data_changed->modify_cell EXPORTING i_row_id = pe_modif-row_id i_fieldname = -fieldname i_value = sy-mandt. "" Se informa el campo de idioma de la tabla de texto ELSEIF -fieldname = mv_field_lang_textable AND mv_field_lang_textable IS NOT INITIAL. CALL METHOD ps_data_changed->modify_cell EXPORTING i_row_id = pe_modif-row_id i_fieldname = -fieldname i_value = sy-langu. ENDIF. ENDLOOP. "" Pongo que esa línea es insertada CALL METHOD ps_data_changed->modify_cell EXPORTING i_row_id = pe_modif-row_id i_fieldname = zif_al30_data=>cs_control_fields_alv_data-updkz i_value = zif_al30_data=>cv_mode_insert. "" Pongo el número de linea CALL METHOD ps_data_changed->modify_cell EXPORTING i_row_id = pe_modif-row_id i_fieldname = zif_al30_data=>cs_control_fields_alv_data-tabix i_value = pe_modif-row_id. ENDFORM. "" ROW_INSERT *&---------------------------------------------------------------------* *& Form ROW_INSERT_MODIFY *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM row_insert_modify CHANGING ps_data_changed TYPE REF TO cl_alv_changed_data_protocol. * Tabla con datos insertados o modificados FIELD-SYMBOLS TYPE table. FIELD-SYMBOLS TYPE any. FIELD-SYMBOLS TYPE lvc_s_modi. * DATA ld_count TYPE sytabix. * Recupero los datos modificados o insertados ASSIGN ps_data_changed->mp_mod_rows->* TO . IF sy-subrc = 0. "" Las celdas se pasan a una tabla local. El motivo es que en procedimiento verify_change_row_data se pasan los datos modificados al listado. "" Si se esta insertando una nueva línea y hay un campo que se no se informa nada en el momento de pasarlo al listado, provoca que se añade una nueva "" línea al mt_mod_cells volviendo a procesar el nuevo campo y provocando un bucle infinito, porque se añade una y otra vez. DATA(lt_mod_cells) = ps_data_changed->mt_mod_cells. LOOP AT lt_mod_cells ASSIGNING . ** El row_id que se inserte o modifica no coincide con el regustro en la tabla , ** aunque los registros siempre están consecutivos. Con lo que si tenemos dos row_id: 5 y 6 ** sabremos que el 5 están la linea 1 de la tabla de registros modificados. Y la seis en la dos. ** Por ello tengo un contador propio para saber el registros en la tabla de datos AT NEW row_id. * ADD 1 TO ld_count. "" Leo el registro modificado/insertado READ TABLE ASSIGNING INDEX -tabix. "" Se resetea el campo de status mo_controller->clear_row_status_fields( CHANGING cs_row_data = ). * Trato la linea para ver si se ha modificado o insertado PERFORM trat_new_row_id USING ""ld_count CHANGING ps_data_changed. * Compruebo que los camps claves que se haya introducido/modificado no esten introducido PERFORM check_key_duplicate USING CHANGING ps_data_changed . ENDAT. "" NOTA IRB: 16/06/2020 - Esta exit queda como obsoleta. Se sustituye por la verify_change_row_data que lo aglutina todo * PERFORM verify_content_fields USING * CHANGING ps_data_changed * ps_datos_validos. * Al final de cada registro se lanza la verificacion a nivel de fila AT END OF row_id. PERFORM verify_change_row_data USING CHANGING ps_data_changed. "" Si en la fila tiene un error, lo que se hará es añadir los errores del propio ALV al campo donde se acumula los mensajes de la fila IF -error = abap_true. mo_controller->trans_alv_error_2_row( EXPORTING io_data_changed = ps_data_changed CHANGING cs_row_data = ). ENDIF. "" Se sincronizan los valores de la fila modificados durante el proceso a la tabla interna global. mo_controller->upd_values_from_data_changed( EXPORTING is_mod_cell = CHANGING cs_row_data = co_data_changed = ps_data_changed ). ENDAT. ENDLOOP. ENDIF. ENDFORM. "" ROW_INSERT_MODIFY *&---------------------------------------------------------------------* *& Form ROW_MODIFY *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM row_modify USING pe_modif TYPE lvc_s_modi pe_datos_im TYPE any CHANGING ps_data_changed TYPE REF TO cl_alv_changed_data_protocol. * Miro el valor del campo que indica el tipo de actualización ASSIGN COMPONENT zif_al30_data=>cs_control_fields_alv_data-updkz OF STRUCTURE pe_datos_im TO FIELD-SYMBOL(). IF sy-subrc = 0. * Si el registro no ha sido insertado previamente pongo el status a modificado. IF NE zif_al30_data=>cv_mode_insert. * Y informo la tabla de datos CALL METHOD ps_data_changed->modify_cell EXPORTING i_row_id = pe_modif-row_id i_fieldname = zif_al30_data=>cs_control_fields_alv_data-updkz i_value = zif_al30_data=>cv_mode_change. ENDIF. ENDIF. ENDFORM. "" ROW_MODIFY *&---------------------------------------------------------------------* *& Form TRAT_NEW_ROW_ID *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM trat_new_row_id USING ""pe_count TYPE sytabix pe_modif TYPE lvc_s_modi pe_datos_im TYPE any CHANGING ps_data_changed TYPE REF TO cl_alv_changed_data_protocol. * Lo primero que averiguo si es una inserción u modificación. Para saberlo miro * Si el registro están en la tabla ""mt_inserted_rows"", si lo esta entonces se esta insertando. READ TABLE ps_data_changed->mt_inserted_rows TRANSPORTING NO FIELDS WITH KEY row_id = pe_modif-row_id. IF sy-subrc = 0. * Hago las operaciones cuando una linea se inserta PERFORM row_insert USING pe_modif pe_datos_im CHANGING ps_data_changed. ELSE. * Si no esta en la tabla es que se esta insertando PERFORM row_modify USING pe_modif pe_datos_im CHANGING ps_data_changed. ENDIF. ENDFORM. "" TRAT_NEW_ROW_ID *&---------------------------------------------------------------------* *& Form CHECK_KEY_DUPLICATE *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM check_key_duplicate USING pe_modif TYPE lvc_s_modi CHANGING ps_data_changed TYPE REF TO cl_alv_changed_data_protocol pe_datos_im TYPE any. FIELD-SYMBOLS TYPE any. FIELD-SYMBOLS TYPE zal30_i_row_status_msg. DATA ld_valor TYPE string. DATA ld_found TYPE sap_bool. DATA lv_cond TYPE string. * Primero miro si el registro viene del diccionario. En caso afirmativo no compruebo * clave duplicada ya que no la pueden modificar ASSIGN COMPONENT zif_al30_data=>cs_control_fields_alv_data-is_dict OF STRUCTURE pe_datos_im TO FIELD-SYMBOL(). IF sy-subrc = 0. IF = abap_false. * No leo los campos claves que están marcados como técnicos y que además pertenezcan a la tabla de textos(como el idioma), ya que no se van a introducir. LOOP AT mt_fields ASSIGNING FIELD-SYMBOL() WHERE tech = abap_false AND key_ddic = abap_true AND field_texttable = abap_false. ASSIGN COMPONENT -fieldname OF STRUCTURE pe_datos_im TO . IF sy-subrc = 0. lv_cond = COND string( LET sep = 'AND' cond = |{ -fieldname } = '{ }'| IN WHEN lv_cond IS INITIAL THEN cond ELSE |{ lv_cond } { sep } { cond }| ). ENDIF. ENDLOOP. * Si no hay campos clave no tiene sentido hacer verificaciones. IF sy-subrc = 0. * Añado la condición de no busque los registros previamente borrados lv_cond = COND string( LET sep1 = 'AND' cond = |{ zif_al30_data=>cs_control_fields_alv_data-updkz } NE '{ zif_al30_data=>cv_mode_delete }'| IN WHEN lv_cond IS INITIAL THEN cond ELSE |{ lv_cond } { sep1 } { cond }| ). * Como los cambios se realizan fuera del evento DATA_CHANGED en la tabla * tengo los valores antiguos y por lo que nunca se encontrará ""a si mismo"" el registro * modificado. La excepcion son lo que vienen del diccionario. Cuya clave no se puede cambiar y en ese * caso me encontrará el mismo registro. * Lo que si que hay que controlar es la posición del registro sea distinta a la del registro * que el ALV me dice que esta modificado. Si es el mismo significa que estoy en el mismo. * Esto habitualmente no pasaria salvo cuando hay un campo obligatorio que no esta informado, y segun * su configuración deberia estarlo. En ese caso, saco un mensaje de error a través del DATA_CHANGED, con * lo cual si se pulsa un botón o algo, cuando entra al data_changed este registro SAP lo tiene como * modificado, aunque no se haya modificado ningún valor. Lo tiene modificado porque le he indicado que habia * un error en ese registro. ld_found = abap_false. LOOP AT ASSIGNING WHERE (lv_cond). IF sy-tabix NE pe_modif-row_id. ld_found = abap_true. ENDIF. EXIT. ENDLOOP. IF ld_found = abap_true. CALL METHOD ps_data_changed->add_protocol_entry EXPORTING i_msgid = zif_al30_data=>cv_msg_id i_msgno = '043' i_msgty = zif_al30_data=>cs_msg_type-error i_fieldname = -fieldname "" Se escoge el último campo de la clave i_row_id = pe_modif-row_id i_tabix = pe_modif-tabix. "" Para poder guardar los errores necesito los campos donde se almacenan dichos mensajes y su campo de control ASSIGN COMPONENT zif_al30_data=>cs_control_fields_alv_data-row_status_msg OF STRUCTURE pe_datos_im TO . IF sy-subrc = 0. INSERT VALUE #( type = zif_al30_data=>cs_msg_type-error fieldname = -fieldname ) INTO TABLE ASSIGNING FIELD-SYMBOL(). -message = zcl_al30_util=>fill_return( EXPORTING iv_type = zif_al30_data=>cs_msg_type-error iv_number = '043' iv_id = zif_al30_data=>cv_msg_id )-message. ASSIGN COMPONENT zif_al30_data=>cs_control_fields_alv_data-row_status OF STRUCTURE pe_datos_im TO FIELD-SYMBOL(). IF sy-subrc = 0. = zif_al30_data=>cs_msg_type-error. ENDIF. ENDIF. ENDIF. ENDIF. ENDIF. ENDIF. ENDFORM. "" CHECK_KEY_DUPLICATE *&---------------------------------------------------------------------* *& Form GRABAR_DATOS *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM grabar_datos . "" Si se puede pedir orden de transporte se llama al método que validar y/o seleccionará la orden de transporter IF mv_pedir_orden = abap_true. mo_cnt_al30->check_select_transport_order( EXPORTING iv_category = zif_al30_data=>cs_order_category-workbench IMPORTING es_return = DATA(ls_return) CHANGING cv_order = mv_orden_transporte ). ENDIF. "" Si no hay errores y hay orden de transporte, se hace la grabación IF ls_return IS INITIAL AND ( mv_pedir_orden = abap_false OR ( mv_orden_transporte IS NOT INITIAL AND mv_pedir_orden = abap_true ) ) . CALL METHOD mo_cnt_al30->save_data EXPORTING iv_allow_request = mv_pedir_orden IMPORTING et_return = DATA(lt_return) CHANGING ct_datos_del = ct_datos = cv_order = mv_orden_transporte. "" Si hay mensajes se mira cuantos hay. Si solo hay uno se visualiza como mensaje directamente "" en caso contrario se mostrará los mensajes en una ventana IF lt_return IS NOT INITIAL. DESCRIBE TABLE lt_return. IF sy-tfill = 1 . READ TABLE lt_return REFERENCE INTO DATA(lo_return) INDEX 1. "" El mensaje se cambia a 'S' y se muestra como el tipo original MESSAGE ID lo_return->id TYPE 'S' NUMBER lo_return->number WITH lo_return->message_v1 lo_return->message_v2 lo_return->message_v3 lo_return->message_v4 DISPLAY LIKE lo_return->type. ELSE. mo_controller->show_messages( it_messages = VALUE #( FOR IN lt_return ( type = -type message = -message ) ) ). ENDIF. ENDIF. "" Si no hay error se hace los mismos ajustes que se hacen al leer los datos. IF NOT line_exists( lt_return[ type = zif_al30_data=>cs_msg_type-error ] ). PERFORM adjust_data_post_read. ENDIF. ELSE. MESSAGE ID ls_return-id TYPE ls_return-type NUMBER ls_return-number WITH ls_return-message_v1 ls_return-message_v2 ls_return-message_v3 ls_return-message_v4. ENDIF. ENDFORM. "" GRABAR_DATOS *&---------------------------------------------------------------------* *& Form VERIFY_CONTENT_FIELDS *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM verify_content_fields USING pe_modif TYPE lvc_s_modi CHANGING ps_data_changed TYPE REF TO cl_alv_changed_data_protocol ps_datos_validos TYPE sap_bool. DATA ls_return TYPE bapiret2. mo_cnt_al30->verify_field_data( EXPORTING iv_fieldname = pe_modif-fieldname iv_value = pe_modif-value IMPORTING es_return = ls_return ). IF ls_return IS NOT INITIAL. CALL METHOD ps_data_changed->add_protocol_entry EXPORTING i_msgid = ls_return-id i_msgno = ls_return-number i_msgty = ls_return-type i_fieldname = pe_modif-fieldname i_row_id = pe_modif-row_id i_tabix = pe_modif-tabix. ENDIF. "" Si el mensaje es errónea se marca que los datos no son validos. IF ls_return-type = zif_al30_data=>cs_msg_type-error. ps_datos_validos = abap_false. ENDIF. ENDFORM. "" VERIFY_CONTENT_FIELDS *&---------------------------------------------------------------------* *& Form CHECK_AUTORIZATION *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM check_autorization CHANGING ps_auth TYPE sap_bool ps_mode TYPE char1. ps_auth = abap_true. "" Por defecto se tiene autorizacion ps_mode = zif_al30_data=>cv_mode_change. "" Puede modificar DATA(lv_level_auth) = mo_cnt_al30->check_authorization_view( iv_view_name = zal30_t_view-tabname iv_view_action = COND #( WHEN ps_mode = zif_al30_data=>cv_mode_change THEN zif_al30_data=>cs_action_auth-update ELSE zif_al30_data=>cs_action_auth-show ) iv_user = sy-uname ). "" Segun el nivel de autorización cambiará que es lo que puede hacer. CASE lv_level_auth. WHEN zif_al30_data=>cs_level_auth_user-non. ps_auth = abap_false. WHEN zif_al30_data=>cs_level_auth_user-read. ps_mode = zif_al30_data=>cv_mode_view. WHEN zif_al30_data=>cs_level_auth_user-full. "" Nada, valores por defecto ENDCASE. ** Se mira si tiene control de autorización por usuario * IF mo_controller->view_have_user_auth( zal30_t_view-tabname ) = abap_true. * DATA(lv_level_auth) = mo_controller->get_level_auth_view( iv_user = sy-uname iv_view = ms_view-tabname ). * * "" Segun el nivel de autorización cambiará que es lo que puede hacer. * CASE lv_level_auth. * WHEN zif_al30_data=>cs_level_auth_user-non. * ps_auth = abap_false. * WHEN zif_al30_data=>cs_level_auth_user-read. * ps_mode = zif_al30_data=>cv_mode_view. * WHEN zif_al30_data=>cs_level_auth_user-full. * "" Nada, valores por defecto * ENDCASE. * ENDIF. * * IF ps_auth = abap_true. * IF mo_controller->view_have_sap_auth( zal30_t_view-tabname ). * * TRY. * CALL METHOD mo_controller->check_sap_authorization * EXPORTING * iv_view_name = zal30_t_view-tabname * iv_view_action = COND #( WHEN ps_mode = zif_al30_data=>cv_mode_change THEN zif_al30_data=>cs_action_auth-update ELSE zif_al30_data=>cs_action_auth-show ). * * CATCH zcx_al30 . * ps_auth = abap_false. * ENDTRY. * * ENDIF. * * ENDIF. ENDFORM. "" CHECK_AUTORIZATION *&---------------------------------------------------------------------* *& Form EDIT_MODE_ALV *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* FORM edit_mode_alv . DATA lv_mode TYPE int4. IF mo_alv IS BOUND. CASE mv_mode. WHEN zif_al30_data=>cv_mode_change. lv_mode = 1. mo_cnt_al30->set_edit_mode_alv_data( EXPORTING it_data = IMPORTING ev_edit_mode = DATA(lv_edit_mode) ). "" Si el modo de edición es visualizar se cambia el modo que se pasará al ALV. En caso contrario se indica el determinado "" por defecto lv_mode = COND #( WHEN lv_edit_mode = zif_al30_data=>cv_mode_view THEN 0 ELSE lv_mode ). WHEN zif_al30_data=>cv_mode_view. lv_mode = 0. ENDCASE. CALL METHOD mo_alv->set_ready_for_input EXPORTING i_ready_for_input = lv_mode. ENDIF. ENDFORM. "" EDIT_MODE_ALV *&---------------------------------------------------------------------* *& Form TRANSPORTAR_DATOS *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* FORM transportar_datos . FIELD-SYMBOLS TYPE lvc_s_row. FIELD-SYMBOLS TYPE STANDARD TABLE. FIELD-SYMBOLS TYPE any. DATA lt_index TYPE lvc_t_row. DATA lv_answer TYPE c. DATA lo_datos TYPE REF TO data. DATA ls_return TYPE bapiret2. CALL METHOD mo_alv->get_selected_rows IMPORTING et_index_rows = lt_index. * Se ha de seleccionar una entrada para poder transportar IF lt_index IS NOT INITIAL. CALL FUNCTION 'POPUP_TO_CONFIRM' EXPORTING titlebar = 'Transportation content table'(001) text_question = 'Do you want to transport the selected table entries?'(002) IMPORTING answer = lv_answer EXCEPTIONS text_not_found = 1 OTHERS = 2. IF lv_answer = '1'. "" Se pide la orden a transportar, o se valida la última utilizada mo_cnt_al30->check_select_transport_order( EXPORTING iv_category = zif_al30_data=>cs_order_category-workbench IMPORTING es_return = ls_return CHANGING cv_order = mv_orden_transporte ). IF ls_return-type NE zif_al30_data=>cs_msg_type-error. "" Se crea una tabla local para pasar los datos seleccionados CREATE DATA lo_datos LIKE . ASSIGN lo_datos->* TO . * Monto los campos clave de las entradas seleccionadas LOOP AT lt_index ASSIGNING . READ TABLE ASSIGNING FIELD-SYMBOL() INDEX -index. IF sy-subrc = 0. INSERT INTO TABLE . ENDIF. ENDLOOP. * Llamo al proceso encargado que añadira las entradas a la tabla ls_return = mo_cnt_al30->transport_data_entries( EXPORTING it_data = CHANGING cv_order = mv_orden_transporte ). IF ls_return IS NOT INITIAL. MESSAGE ID ls_return-id TYPE ls_return-type NUMBER ls_return-number WITH ls_return-message_v1 ls_return-message_v2 ls_return-message_v3 ls_return-message_v4. ENDIF. ENDIF. ENDIF. ELSE. MESSAGE s044. ENDIF. ENDFORM ""transportar_datos . "" TRANSPORTAR_DATOS *&---------------------------------------------------------------------* *& Form VERIFY_CHANGE_ROW_DATA *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* FORM verify_change_row_data USING pe_modif TYPE lvc_s_modi ps_row_data TYPE any CHANGING ps_data_changed TYPE REF TO cl_alv_changed_data_protocol. FIELD-SYMBOLS TYPE any. FIELD-SYMBOLS TYPE lvc_s_fcat. FIELD-SYMBOLS TYPE any. FIELD-SYMBOLS: TYPE lvc_t_styl. FIELD-SYMBOLS TYPE zal30_i_row_status_msg. * data lt_row_msg type zal30_i_row_status_msg. "" Debido a que las validacion en las clases resetean los campos de control de status me los guardo variables locales para luego "" volver a mover en caso que haya habido errores ASSIGN COMPONENT zif_al30_data=>cs_control_fields_alv_data-row_status_msg OF STRUCTURE ps_row_data TO . IF sy-subrc = 0. DATA(lt_row_msg) = . ASSIGN COMPONENT zif_al30_data=>cs_control_fields_alv_data-row_status OF STRUCTURE ps_row_data TO FIELD-SYMBOL(). IF sy-subrc = 0. DATA(lv_row_status) = CONV string( ). ENDIF. ENDIF. CALL METHOD mo_cnt_al30->verify_change_row_data EXPORTING iv_row = pe_modif-row_id IMPORTING et_return = DATA(lt_return) CHANGING cs_row_data = ps_row_data. * Si hay mensaje lo devuelvo a la clase IF lt_return IS NOT INITIAL. LOOP AT lt_return ASSIGNING FIELD-SYMBOL(). CALL METHOD ps_data_changed->add_protocol_entry EXPORTING i_msgid = -id i_msgno = -number i_msgty = -type i_msgv1 = -message_v1 i_msgv2 = -message_v2 i_msgv3 = -message_v3 i_msgv4 = -message_v4 i_fieldname = -field i_row_id = pe_modif-row_id i_tabix = pe_modif-row_id. ENDLOOP. ENDIF. "" Una vez finalizado el proceso se añaden los mensajes previos de nuevo al campo IF IS ASSIGNED. INSERT LINES OF lt_row_msg INTO TABLE . ENDIF. "" Si previamente hay error lo vuelvo a poner. Si en la validación ya viene con error pues se pondrá "" el mismo valor, pero así hago el código más simple. IF IS ASSIGNED AND lv_row_status = zif_al30_data=>cs_msg_type-error. = lv_row_status. ENDIF. * Ahora se actualiza los estilos por si se hubiesen modificado en la exit ASSIGN COMPONENT zif_al30_data=>cs_control_fields_alv_data-style OF STRUCTURE TO . IF sy-subrc = 0. LOOP AT ASSIGNING FIELD-SYMBOL(