commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
|---|---|---|---|---|---|---|---|---|---|
4ecbc30a2e04a9e3ff3253943cb6cb0c14239035
|
src/objects/core/zcl_abapgit_objects_activation.clas.abap
|
src/objects/core/zcl_abapgit_objects_activation.clas.abap
|
CLASS zcl_abapgit_objects_activation DEFINITION
PUBLIC
CREATE PUBLIC .
PUBLIC SECTION.
CLASS-METHODS add
IMPORTING
!iv_type TYPE trobjtype
!iv_name TYPE clike
!iv_delete TYPE abap_bool DEFAULT abap_false
RAISING
zcx_abapgit_exception .
CLASS-METHODS add_item
IMPORTING
!is_item TYPE zif_abapgit_definitions=>ty_item
RAISING
zcx_abapgit_exception .
CLASS-METHODS activate
IMPORTING
!iv_ddic TYPE abap_bool DEFAULT abap_false
RAISING
zcx_abapgit_exception .
CLASS-METHODS clear .
PROTECTED SECTION.
PRIVATE SECTION.
TYPES:
BEGIN OF ty_classes,
object TYPE trobjtype,
clsname TYPE seoclsname,
END OF ty_classes.
CLASS-DATA:
gt_classes TYPE STANDARD TABLE OF ty_classes WITH DEFAULT KEY .
CLASS-DATA:
gt_objects TYPE TABLE OF dwinactiv .
CLASS-METHODS update_where_used .
CLASS-METHODS use_new_activation_logic
RETURNING
VALUE(rv_use_new_activation_logic) TYPE abap_bool .
CLASS-METHODS activate_new
IMPORTING
!iv_ddic TYPE abap_bool DEFAULT abap_false
RAISING
zcx_abapgit_exception .
CLASS-METHODS activate_old
IMPORTING
!iv_ddic TYPE abap_bool DEFAULT abap_false
RAISING
zcx_abapgit_exception .
CLASS-METHODS activate_ddic
RAISING
zcx_abapgit_exception .
CLASS-METHODS show_activation_errors
IMPORTING
!iv_logname TYPE ddmass-logname
RAISING
zcx_abapgit_exception .
CLASS-METHODS is_ddic_type
IMPORTING
!iv_obj_type TYPE trobjtype
RETURNING
VALUE(rv_result) TYPE abap_bool .
ENDCLASS.
CLASS ZCL_ABAPGIT_OBJECTS_ACTIVATION IMPLEMENTATION.
METHOD activate.
" Make sure that all changes are committed since any activation error will lead to a rollback
COMMIT WORK AND WAIT.
IF use_new_activation_logic( ) = abap_true.
activate_new( iv_ddic ).
ELSE.
activate_old( iv_ddic ).
ENDIF.
update_where_used( ).
ENDMETHOD.
METHOD activate_ddic.
DATA: lt_gentab TYPE STANDARD TABLE OF dcgentb,
lv_rc TYPE sy-subrc,
ls_gentab LIKE LINE OF lt_gentab,
lt_deltab TYPE STANDARD TABLE OF dcdeltb,
lt_action_tab TYPE STANDARD TABLE OF dctablres,
lv_logname TYPE ddmass-logname.
FIELD-SYMBOLS: <ls_object> LIKE LINE OF gt_objects.
LOOP AT gt_objects ASSIGNING <ls_object>.
" Filter types supported by mass activation
IF is_ddic_type( <ls_object>-object ) = abap_false.
CONTINUE.
ENDIF.
ls_gentab-tabix = sy-tabix.
ls_gentab-type = <ls_object>-object.
ls_gentab-name = <ls_object>-obj_name.
IF ls_gentab-type = 'INDX' OR ls_gentab-type = 'XINX' OR ls_gentab-type = 'MCID'.
CALL FUNCTION 'DD_E071_TO_DD'
EXPORTING
object = <ls_object>-object
obj_name = <ls_object>-obj_name
IMPORTING
name = ls_gentab-name
id = ls_gentab-indx.
ENDIF.
INSERT ls_gentab INTO TABLE lt_gentab.
ENDLOOP.
IF lt_gentab IS NOT INITIAL.
lv_logname = |ABAPGIT_{ sy-datum }_{ sy-uzeit }|.
CALL FUNCTION 'DD_MASS_ACT_C3'
EXPORTING
ddmode = 'O' " activate changes in Original System
frcact = abap_true " force Activation
medium = 'T' " transport order
device = 'T' " saves to table DDRPH?
version = 'M' " activate newest version
logname = lv_logname
write_log = abap_true
log_head_tail = abap_true
t_on = space
prid = 1
IMPORTING
act_rc = lv_rc
TABLES
gentab = lt_gentab
deltab = lt_deltab
cnvtab = lt_action_tab
EXCEPTIONS
access_failure = 1
no_objects = 2
locked = 3
internal_error = 4
OTHERS = 5.
IF sy-subrc <> 0.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
IF lv_rc > 0.
show_activation_errors( lv_logname ).
ENDIF.
" Remove objects from activation queue to avoid double activation in activate_old
LOOP AT lt_gentab INTO ls_gentab.
DELETE gt_objects WHERE object = ls_gentab-type AND obj_name = ls_gentab-name.
ENDLOOP.
DELETE gt_objects WHERE object = 'INDX' OR object = 'XINX' OR object = 'MCID'.
ENDIF.
ENDMETHOD.
METHOD activate_new.
DATA: li_progress TYPE REF TO zif_abapgit_progress.
IF gt_objects IS INITIAL.
RETURN.
ENDIF.
li_progress = zcl_abapgit_progress=>get_instance( 100 ).
IF iv_ddic = abap_true.
li_progress->show( iv_current = 98
iv_text = 'Activating DDIC' ).
activate_ddic( ).
ELSE.
li_progress->show( iv_current = 98
iv_text = 'Activating non DDIC' ).
activate_old( ).
ENDIF.
ENDMETHOD.
METHOD activate_old.
DATA: lv_popup TYPE abap_bool,
lv_no_ui TYPE abap_bool.
IF gt_objects IS NOT INITIAL.
IF zcl_abapgit_ui_factory=>get_gui_functions( )->gui_is_available( ) = abap_true.
IF zcl_abapgit_persist_factory=>get_settings( )->read( )->get_activate_wo_popup( ) = abap_true.
lv_popup = abap_false.
ELSE.
lv_popup = abap_true.
ENDIF.
ELSE.
lv_popup = abap_false.
ENDIF.
lv_no_ui = boolc( lv_popup = abap_false ).
TRY.
CALL FUNCTION 'RS_WORKING_OBJECTS_ACTIVATE'
EXPORTING
activate_ddic_objects = iv_ddic
with_popup = lv_popup
ui_decoupled = lv_no_ui
TABLES
objects = gt_objects
EXCEPTIONS
excecution_error = 1
cancelled = 2
insert_into_corr_error = 3
OTHERS = 4 ##SUBRC_OK.
CATCH cx_sy_dyn_call_param_not_found.
CALL FUNCTION 'RS_WORKING_OBJECTS_ACTIVATE'
EXPORTING
activate_ddic_objects = iv_ddic
with_popup = lv_popup
TABLES
objects = gt_objects
EXCEPTIONS
excecution_error = 1
cancelled = 2
insert_into_corr_error = 3
OTHERS = 4 ##SUBRC_OK.
ENDTRY.
CASE sy-subrc.
WHEN 1 OR 3 OR 4.
zcx_abapgit_exception=>raise_t100( ).
WHEN 2.
zcx_abapgit_exception=>raise( 'Activation cancelled. Check the inactive objects.' ).
ENDCASE.
ENDIF.
ENDMETHOD.
METHOD add.
* function group SEWORKINGAREA
* function module RS_INSERT_INTO_WORKING_AREA
* class CL_WB_ACTIVATION_WORK_AREA
FIELD-SYMBOLS: <ls_object> TYPE dwinactiv,
<ls_classes> LIKE LINE OF gt_classes.
IF iv_type = 'CLAS' OR iv_type = 'INTF'.
APPEND INITIAL LINE TO gt_classes ASSIGNING <ls_classes>.
<ls_classes>-object = iv_type.
<ls_classes>-clsname = iv_name.
ELSE.
APPEND INITIAL LINE TO gt_objects ASSIGNING <ls_object>.
<ls_object>-object = iv_type.
<ls_object>-obj_name = iv_name.
<ls_object>-delet_flag = iv_delete.
ENDIF.
ENDMETHOD.
METHOD add_item.
add( iv_type = is_item-obj_type
iv_name = is_item-obj_name ).
ENDMETHOD.
METHOD clear.
CLEAR gt_objects.
CLEAR gt_classes.
ENDMETHOD.
METHOD is_ddic_type.
" Determine if object can be handled by mass activation (see RADMASUTC form ma_tab_check)
CONSTANTS:
lc_domain TYPE c LENGTH 9 VALUE 'DOMA DOMD',
lc_types TYPE c LENGTH 50 VALUE 'DTEL DTED TABL TABD SQLT SQLD TTYP TTYD VIEW VIED',
lc_technset TYPE c LENGTH 24 VALUE 'TABT VIET SQTT INDX XINX',
lc_f4_objects TYPE c LENGTH 35 VALUE 'SHLP SHLD MCOB MCOD MACO MACD MCID',
lc_enqueue TYPE c LENGTH 9 VALUE 'ENQU ENQD',
lc_sqsc TYPE c LENGTH 4 VALUE 'SQSC',
lc_stob TYPE c LENGTH 4 VALUE 'STOB',
lc_ntab TYPE c LENGTH 14 VALUE 'NTTT NTTB NTDT',
lc_ddls TYPE c LENGTH 4 VALUE 'DDLS',
lc_switches TYPE c LENGTH 24 VALUE 'SF01 SF02 SFSW SFBS SFBF',
lc_enhd TYPE c LENGTH 4 VALUE 'ENHD'.
rv_result = abap_true.
IF lc_domain NS iv_obj_type AND lc_types NS iv_obj_type AND
lc_technset NS iv_obj_type AND lc_f4_objects NS iv_obj_type AND
lc_enqueue NS iv_obj_type AND lc_sqsc NS iv_obj_type AND
lc_stob NS iv_obj_type AND lc_ntab NS iv_obj_type AND
lc_ddls NS iv_obj_type AND
lc_switches NS iv_obj_type AND iv_obj_type <> lc_enhd.
rv_result = abap_false.
ENDIF.
ENDMETHOD.
METHOD show_activation_errors.
DATA: lt_lines TYPE STANDARD TABLE OF trlog,
lv_logname_db TYPE ddprh-protname,
li_log TYPE REF TO zif_abapgit_log.
FIELD-SYMBOLS: <ls_line> LIKE LINE OF lt_lines.
lv_logname_db = iv_logname.
CALL FUNCTION 'TR_READ_LOG'
EXPORTING
iv_log_type = 'DB'
iv_logname_db = lv_logname_db
TABLES
et_lines = lt_lines
EXCEPTIONS
invalid_input = 1
access_error = 2
OTHERS = 3.
IF sy-subrc <> 0.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
DELETE lt_lines WHERE severity <> 'E'.
CREATE OBJECT li_log TYPE zcl_abapgit_log.
li_log->set_title( 'Activation Errors' ).
LOOP AT lt_lines ASSIGNING <ls_line>.
li_log->add( <ls_line>-line ).
ENDLOOP.
IF li_log->count( ) > 0.
zcl_abapgit_log_viewer=>show_log( li_log ).
ENDIF.
ENDMETHOD.
METHOD update_where_used.
DATA: ls_class LIKE LINE OF gt_classes,
lo_cross TYPE REF TO cl_wb_crossreference,
lv_include TYPE programm,
li_progress TYPE REF TO zif_abapgit_progress.
li_progress = zcl_abapgit_progress=>get_instance( lines( gt_classes ) ).
LOOP AT gt_classes INTO ls_class.
IF sy-tabix MOD 20 = 0.
li_progress->show(
iv_current = sy-tabix
iv_text = 'Updating where-used lists' ).
ENDIF.
CASE ls_class-object.
WHEN 'CLAS'.
lv_include = cl_oo_classname_service=>get_classpool_name( ls_class-clsname ).
WHEN 'INTF'.
lv_include = cl_oo_classname_service=>get_interfacepool_name( ls_class-clsname ).
ENDCASE.
CREATE OBJECT lo_cross
EXPORTING
p_name = lv_include
p_include = lv_include.
lo_cross->index_actualize( ).
ENDLOOP.
ENDMETHOD.
METHOD use_new_activation_logic.
CALL FUNCTION 'FUNCTION_EXISTS'
EXPORTING
funcname = 'DD_MASS_ACT_C3'
EXCEPTIONS
function_not_exist = 1
OTHERS = 2.
IF sy-subrc = 0.
rv_use_new_activation_logic = abap_true.
ENDIF.
ENDMETHOD.
ENDCLASS.
|
CLASS zcl_abapgit_objects_activation DEFINITION
PUBLIC
CREATE PUBLIC .
PUBLIC SECTION.
CLASS-METHODS add
IMPORTING
!iv_type TYPE trobjtype
!iv_name TYPE clike
!iv_delete TYPE abap_bool DEFAULT abap_false
RAISING
zcx_abapgit_exception .
CLASS-METHODS add_item
IMPORTING
!is_item TYPE zif_abapgit_definitions=>ty_item
RAISING
zcx_abapgit_exception .
CLASS-METHODS activate
IMPORTING
!iv_ddic TYPE abap_bool DEFAULT abap_false
RAISING
zcx_abapgit_exception .
CLASS-METHODS clear .
PROTECTED SECTION.
PRIVATE SECTION.
TYPES:
BEGIN OF ty_classes,
object TYPE trobjtype,
clsname TYPE seoclsname,
END OF ty_classes.
CLASS-DATA:
gt_classes TYPE STANDARD TABLE OF ty_classes WITH DEFAULT KEY .
CLASS-DATA:
gt_objects TYPE TABLE OF dwinactiv .
CLASS-METHODS update_where_used .
CLASS-METHODS use_new_activation_logic
RETURNING
VALUE(rv_use_new_activation_logic) TYPE abap_bool .
CLASS-METHODS activate_new
IMPORTING
!iv_ddic TYPE abap_bool DEFAULT abap_false
RAISING
zcx_abapgit_exception .
CLASS-METHODS activate_old
IMPORTING
!iv_ddic TYPE abap_bool DEFAULT abap_false
RAISING
zcx_abapgit_exception .
CLASS-METHODS activate_ddic
RAISING
zcx_abapgit_exception .
CLASS-METHODS show_activation_errors
IMPORTING
!iv_logname TYPE ddmass-logname
RAISING
zcx_abapgit_exception .
CLASS-METHODS is_ddic_type
IMPORTING
!iv_obj_type TYPE trobjtype
RETURNING
VALUE(rv_result) TYPE abap_bool .
ENDCLASS.
CLASS ZCL_ABAPGIT_OBJECTS_ACTIVATION IMPLEMENTATION.
METHOD activate.
" Make sure that all changes are committed since any activation error will lead to a rollback
COMMIT WORK AND WAIT.
IF use_new_activation_logic( ) = abap_true.
activate_new( iv_ddic ).
ELSE.
activate_old( iv_ddic ).
ENDIF.
update_where_used( ).
ENDMETHOD.
METHOD activate_ddic.
DATA: lt_gentab TYPE STANDARD TABLE OF dcgentb,
lv_rc TYPE sy-subrc,
ls_gentab LIKE LINE OF lt_gentab,
lt_deltab TYPE STANDARD TABLE OF dcdeltb,
lt_action_tab TYPE STANDARD TABLE OF dctablres,
lv_logname TYPE ddmass-logname.
FIELD-SYMBOLS: <ls_object> LIKE LINE OF gt_objects.
LOOP AT gt_objects ASSIGNING <ls_object>.
" Filter types supported by mass activation
IF is_ddic_type( <ls_object>-object ) = abap_false.
CONTINUE.
ENDIF.
ls_gentab-tabix = sy-tabix.
ls_gentab-type = <ls_object>-object.
ls_gentab-name = <ls_object>-obj_name.
IF ls_gentab-type = 'INDX' OR ls_gentab-type = 'XINX' OR ls_gentab-type = 'MCID'.
CALL FUNCTION 'DD_E071_TO_DD'
EXPORTING
object = <ls_object>-object
obj_name = <ls_object>-obj_name
IMPORTING
name = ls_gentab-name
id = ls_gentab-indx.
ENDIF.
INSERT ls_gentab INTO TABLE lt_gentab.
ENDLOOP.
IF lt_gentab IS NOT INITIAL.
lv_logname = |ABAPGIT_{ sy-datum }_{ sy-uzeit }|.
CALL FUNCTION 'DD_MASS_ACT_C3'
EXPORTING
ddmode = 'O' " activate changes in Original System
frcact = abap_true " force Activation
medium = 'T' " transport order
device = 'T' " saves to table DDRPH?
version = 'M' " activate newest version
logname = lv_logname
write_log = abap_true
log_head_tail = abap_true
t_on = space
prid = 1
IMPORTING
act_rc = lv_rc
TABLES
gentab = lt_gentab
deltab = lt_deltab
cnvtab = lt_action_tab
EXCEPTIONS
access_failure = 1
no_objects = 2
locked = 3
internal_error = 4
OTHERS = 5.
IF sy-subrc <> 0.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
IF lv_rc > 0.
show_activation_errors( lv_logname ).
ENDIF.
" Remove objects from activation queue to avoid double activation in activate_old
LOOP AT lt_gentab INTO ls_gentab.
DELETE gt_objects WHERE object = ls_gentab-type AND obj_name = ls_gentab-name.
ENDLOOP.
DELETE gt_objects WHERE object = 'INDX' OR object = 'XINX' OR object = 'MCID'.
ENDIF.
ENDMETHOD.
METHOD activate_new.
DATA: li_progress TYPE REF TO zif_abapgit_progress.
IF gt_objects IS INITIAL.
RETURN.
ENDIF.
li_progress = zcl_abapgit_progress=>get_instance( 100 ).
IF iv_ddic = abap_true.
li_progress->show( iv_current = 98
iv_text = 'Activating DDIC' ).
activate_ddic( ).
ELSE.
li_progress->show( iv_current = 98
iv_text = 'Activating non DDIC' ).
activate_old( ).
ENDIF.
ENDMETHOD.
METHOD activate_old.
DATA: lv_popup TYPE abap_bool,
lv_no_ui TYPE abap_bool.
IF gt_objects IS NOT INITIAL.
IF zcl_abapgit_ui_factory=>get_gui_functions( )->gui_is_available( ) = abap_true.
IF zcl_abapgit_persist_factory=>get_settings( )->read( )->get_activate_wo_popup( ) = abap_true.
lv_popup = abap_false.
ELSE.
lv_popup = abap_true.
ENDIF.
ELSE.
lv_popup = abap_false.
ENDIF.
lv_no_ui = boolc( lv_popup = abap_false ).
TRY.
CALL FUNCTION 'RS_WORKING_OBJECTS_ACTIVATE'
EXPORTING
activate_ddic_objects = iv_ddic
with_popup = lv_popup
ui_decoupled = lv_no_ui
TABLES
objects = gt_objects
EXCEPTIONS
excecution_error = 1
cancelled = 2
insert_into_corr_error = 3
OTHERS = 4 ##SUBRC_OK.
CATCH cx_sy_dyn_call_param_not_found.
CALL FUNCTION 'RS_WORKING_OBJECTS_ACTIVATE'
EXPORTING
activate_ddic_objects = iv_ddic
with_popup = lv_popup
TABLES
objects = gt_objects
EXCEPTIONS
excecution_error = 1
cancelled = 2
insert_into_corr_error = 3
OTHERS = 4 ##SUBRC_OK.
ENDTRY.
CASE sy-subrc.
WHEN 1 OR 3 OR 4.
zcx_abapgit_exception=>raise_t100( ).
WHEN 2.
zcx_abapgit_exception=>raise( 'Activation cancelled. Check the inactive objects.' ).
ENDCASE.
ENDIF.
ENDMETHOD.
METHOD add.
* function group SEWORKINGAREA
* function module RS_INSERT_INTO_WORKING_AREA
* class CL_WB_ACTIVATION_WORK_AREA
FIELD-SYMBOLS: <ls_object> TYPE dwinactiv,
<ls_classes> LIKE LINE OF gt_classes.
IF iv_type = 'CLAS' OR iv_type = 'INTF'.
APPEND INITIAL LINE TO gt_classes ASSIGNING <ls_classes>.
<ls_classes>-object = iv_type.
<ls_classes>-clsname = iv_name.
ELSE.
APPEND INITIAL LINE TO gt_objects ASSIGNING <ls_object>.
<ls_object>-object = iv_type.
<ls_object>-obj_name = iv_name.
<ls_object>-delet_flag = iv_delete.
ENDIF.
ENDMETHOD.
METHOD add_item.
add( iv_type = is_item-obj_type
iv_name = is_item-obj_name ).
ENDMETHOD.
METHOD clear.
CLEAR gt_objects.
CLEAR gt_classes.
ENDMETHOD.
METHOD is_ddic_type.
" Determine if object can be handled by mass activation (see RADMASUTC form ma_tab_check)
CONSTANTS:
lc_domain TYPE c LENGTH 9 VALUE 'DOMA DOMD',
lc_types TYPE c LENGTH 50 VALUE 'DTEL DTED TABL TABD SQLT SQLD TTYP TTYD VIEW VIED',
lc_technset TYPE c LENGTH 24 VALUE 'TABT VIET SQTT INDX XINX',
lc_f4_objects TYPE c LENGTH 35 VALUE 'SHLP SHLD MCOB MCOD MACO MACD MCID',
lc_enqueue TYPE c LENGTH 9 VALUE 'ENQU ENQD',
lc_sqsc TYPE c LENGTH 4 VALUE 'SQSC',
lc_stob TYPE c LENGTH 4 VALUE 'STOB',
lc_ntab TYPE c LENGTH 14 VALUE 'NTTT NTTB NTDT',
lc_ddls TYPE c LENGTH 14 VALUE 'DDLS DRUL DTDC',
lc_switches TYPE c LENGTH 24 VALUE 'SF01 SF02 SFSW SFBS SFBF',
lc_enhd TYPE c LENGTH 4 VALUE 'ENHD'.
rv_result = abap_true.
IF lc_domain NS iv_obj_type AND lc_types NS iv_obj_type AND
lc_technset NS iv_obj_type AND lc_f4_objects NS iv_obj_type AND
lc_enqueue NS iv_obj_type AND lc_sqsc NS iv_obj_type AND
lc_stob NS iv_obj_type AND lc_ntab NS iv_obj_type AND
lc_ddls NS iv_obj_type AND
lc_switches NS iv_obj_type AND iv_obj_type <> lc_enhd.
rv_result = abap_false.
ENDIF.
ENDMETHOD.
METHOD show_activation_errors.
DATA: lt_lines TYPE STANDARD TABLE OF trlog,
lv_logname_db TYPE ddprh-protname,
li_log TYPE REF TO zif_abapgit_log.
FIELD-SYMBOLS: <ls_line> LIKE LINE OF lt_lines.
lv_logname_db = iv_logname.
CALL FUNCTION 'TR_READ_LOG'
EXPORTING
iv_log_type = 'DB'
iv_logname_db = lv_logname_db
TABLES
et_lines = lt_lines
EXCEPTIONS
invalid_input = 1
access_error = 2
OTHERS = 3.
IF sy-subrc <> 0.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
DELETE lt_lines WHERE severity <> 'E'.
CREATE OBJECT li_log TYPE zcl_abapgit_log.
li_log->set_title( 'Activation Errors' ).
LOOP AT lt_lines ASSIGNING <ls_line>.
li_log->add( <ls_line>-line ).
ENDLOOP.
IF li_log->count( ) > 0.
zcl_abapgit_log_viewer=>show_log( li_log ).
ENDIF.
ENDMETHOD.
METHOD update_where_used.
DATA: ls_class LIKE LINE OF gt_classes,
lo_cross TYPE REF TO cl_wb_crossreference,
lv_include TYPE programm,
li_progress TYPE REF TO zif_abapgit_progress.
li_progress = zcl_abapgit_progress=>get_instance( lines( gt_classes ) ).
LOOP AT gt_classes INTO ls_class.
IF sy-tabix MOD 20 = 0.
li_progress->show(
iv_current = sy-tabix
iv_text = 'Updating where-used lists' ).
ENDIF.
CASE ls_class-object.
WHEN 'CLAS'.
lv_include = cl_oo_classname_service=>get_classpool_name( ls_class-clsname ).
WHEN 'INTF'.
lv_include = cl_oo_classname_service=>get_interfacepool_name( ls_class-clsname ).
ENDCASE.
CREATE OBJECT lo_cross
EXPORTING
p_name = lv_include
p_include = lv_include.
lo_cross->index_actualize( ).
ENDLOOP.
ENDMETHOD.
METHOD use_new_activation_logic.
CALL FUNCTION 'FUNCTION_EXISTS'
EXPORTING
funcname = 'DD_MASS_ACT_C3'
EXCEPTIONS
function_not_exist = 1
OTHERS = 2.
IF sy-subrc = 0.
rv_use_new_activation_logic = abap_true.
ENDIF.
ENDMETHOD.
ENDCLASS.
|
Add DRUL and DTDC to mass activation (#5156)
|
Add DRUL and DTDC to mass activation (#5156)
* Add DRUL and DTDC to mass activation
DDIC mass activation supports Dependency Rules (DRUL) and Dynamic Cache (DTDC) object
* Len
* Update abap_transpile.json
|
ABAP
|
mit
|
larshp/abapGit,sbcgua/abapGit,larshp/abapGit,sbcgua/abapGit
|
f2afde5b49aa897f9d5bb42fcc7ddeca8de5208e
|
src/backend/zcl_ags_obj_commit.clas.abap
|
src/backend/zcl_ags_obj_commit.clas.abap
|
CLASS zcl_ags_obj_commit DEFINITION
PUBLIC
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES zif_ags_object .
ALIASES c_newline
FOR zif_ags_object~c_newline .
ALIASES deserialize
FOR zif_ags_object~deserialize .
ALIASES save
FOR zif_ags_object~save .
ALIASES serialize
FOR zif_ags_object~serialize .
ALIASES sha1
FOR zif_ags_object~sha1 .
TYPES:
BEGIN OF ty_commit,
tree TYPE zags_sha1,
parent TYPE zags_sha1,
author TYPE string,
committer TYPE string,
body TYPE string,
END OF ty_commit .
METHODS get_tree
RETURNING
VALUE(rv_tree) TYPE ty_commit-tree .
METHODS get_parent
RETURNING
VALUE(rv_parent) TYPE ty_commit-parent .
METHODS get_author
RETURNING
VALUE(rv_author) TYPE ty_commit-author .
METHODS get_committer
RETURNING
VALUE(rv_committer) TYPE ty_commit-committer .
METHODS get_body
RETURNING
VALUE(rv_body) TYPE ty_commit-body .
METHODS set_tree
IMPORTING
!iv_tree TYPE zags_sha1 .
METHODS set_parent
IMPORTING
!iv_parent TYPE ty_commit-parent .
METHODS set_author
IMPORTING
!iv_author TYPE ty_commit-author .
METHODS set_committer
IMPORTING
!iv_committer TYPE ty_commit-committer .
METHODS set_body
IMPORTING
!iv_body TYPE ty_commit-body .
protected section.
private section.
data MS_DATA type TY_COMMIT .
ENDCLASS.
CLASS ZCL_AGS_OBJ_COMMIT IMPLEMENTATION.
METHOD get_author.
rv_author = ms_data-author.
ENDMETHOD.
METHOD get_body.
rv_body = ms_data-body.
ENDMETHOD.
METHOD get_committer.
rv_committer = ms_data-committer.
ENDMETHOD.
METHOD get_parent.
rv_parent = ms_data-parent.
ENDMETHOD.
METHOD get_tree.
rv_tree = ms_data-tree.
ENDMETHOD.
METHOD set_author.
ms_data-author = iv_author.
ENDMETHOD.
METHOD set_body.
ms_data-body = iv_body.
ENDMETHOD.
METHOD set_committer.
ms_data-committer = iv_committer.
ENDMETHOD.
METHOD set_parent.
ms_data-parent = iv_parent.
ENDMETHOD.
METHOD set_tree.
ms_data-tree = iv_tree.
ENDMETHOD.
METHOD zif_ags_object~deserialize.
DATA: lv_string TYPE string,
lv_char40 TYPE c LENGTH 40,
lv_mode TYPE string,
lv_len TYPE i,
lt_string TYPE TABLE OF string.
FIELD-SYMBOLS: <lv_string> LIKE LINE OF lt_string.
lv_string = zcl_ags_util=>xstring_to_string_utf8( iv_data ).
SPLIT lv_string AT c_newline INTO TABLE lt_string.
lv_mode = 'tree'. "#EC NOTEXT
LOOP AT lt_string ASSIGNING <lv_string>.
lv_len = strlen( lv_mode ).
IF NOT lv_mode IS INITIAL AND <lv_string>(lv_len) = lv_mode.
CASE lv_mode.
WHEN 'tree'.
lv_char40 = <lv_string>+5.
TRANSLATE lv_char40 TO UPPER CASE.
ms_data-tree = lv_char40.
lv_mode = 'parent'. "#EC NOTEXT
WHEN 'parent'.
lv_char40 = <lv_string>+7.
TRANSLATE lv_char40 TO UPPER CASE.
ms_data-parent = lv_char40.
lv_mode = 'author'. "#EC NOTEXT
WHEN 'author'.
ms_data-author = <lv_string>+7.
lv_mode = 'committer'. "#EC NOTEXT
WHEN 'committer'.
ms_data-committer = <lv_string>+10.
CLEAR lv_mode.
ENDCASE.
ELSEIF lv_mode = 'parent' AND <lv_string>(6) = 'author'. "#EC NOTEXT
* first commit doesnt have parent
ms_data-author = <lv_string>+7.
lv_mode = 'committer'. "#EC NOTEXT
ELSE.
* body
CONCATENATE ms_data-body <lv_string> INTO ms_data-body
SEPARATED BY c_newline.
ENDIF.
ENDLOOP.
* strip first newline
IF strlen( ms_data-body ) >= 2.
ms_data-body = ms_data-body+2.
ENDIF.
IF ms_data-author IS INITIAL
OR ms_data-committer IS INITIAL
OR ms_data-tree IS INITIAL.
* multiple parents? not supported
ASSERT 1 = 2.
ENDIF.
ENDMETHOD.
METHOD zif_ags_object~save.
DATA: ls_object TYPE zags_objects.
ls_object-sha1 = sha1( ).
ls_object-type = 'commit' ##NO_TEXT.
ls_object-data = serialize( ).
MODIFY zags_objects FROM ls_object.
ENDMETHOD.
METHOD zif_ags_object~serialize.
DATA: lv_string TYPE string,
lv_tmp TYPE string,
lv_tree_lower TYPE string,
lv_parent_lower TYPE string.
lv_tree_lower = ms_data-tree.
TRANSLATE lv_tree_lower TO LOWER CASE.
lv_parent_lower = ms_data-parent.
TRANSLATE lv_parent_lower TO LOWER CASE.
lv_string = ''.
CONCATENATE 'tree' lv_tree_lower INTO lv_tmp SEPARATED BY space. "#EC NOTEXT
CONCATENATE lv_string lv_tmp c_newline INTO lv_string.
IF NOT ms_data-parent IS INITIAL.
CONCATENATE 'parent' lv_parent_lower
INTO lv_tmp SEPARATED BY space. "#EC NOTEXT
CONCATENATE lv_string lv_tmp c_newline INTO lv_string.
ENDIF.
CONCATENATE 'author' ms_data-author
INTO lv_tmp SEPARATED BY space. "#EC NOTEXT
CONCATENATE lv_string lv_tmp c_newline INTO lv_string.
CONCATENATE 'committer' ms_data-committer
INTO lv_tmp SEPARATED BY space. "#EC NOTEXT
CONCATENATE lv_string lv_tmp c_newline INTO lv_string.
CONCATENATE lv_string c_newline ms_data-body INTO lv_string.
rv_data = zcl_ags_util=>string_to_xstring_utf8( lv_string ).
ENDMETHOD.
METHOD zif_ags_object~sha1.
rv_sha1 = zcl_ags_util=>sha1(
iv_type = 'commit'
iv_data = serialize( ) ) ##NO_TEXT.
ENDMETHOD.
ENDCLASS.
|
CLASS zcl_ags_obj_commit DEFINITION
PUBLIC
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES zif_ags_object .
ALIASES c_newline
FOR zif_ags_object~c_newline .
ALIASES deserialize
FOR zif_ags_object~deserialize .
ALIASES save
FOR zif_ags_object~save .
ALIASES serialize
FOR zif_ags_object~serialize .
ALIASES sha1
FOR zif_ags_object~sha1 .
TYPES:
BEGIN OF ty_commit,
tree TYPE zags_sha1,
parent TYPE zags_sha1,
author TYPE string,
committer TYPE string,
body TYPE string,
END OF ty_commit .
METHODS get_tree
RETURNING
VALUE(rv_tree) TYPE ty_commit-tree .
METHODS get_parent
RETURNING
VALUE(rv_parent) TYPE ty_commit-parent .
METHODS get_author
RETURNING
VALUE(rv_author) TYPE ty_commit-author .
METHODS get_committer
RETURNING
VALUE(rv_committer) TYPE ty_commit-committer .
METHODS get_body
RETURNING
VALUE(rv_body) TYPE ty_commit-body .
METHODS set_tree
IMPORTING
!iv_tree TYPE zags_sha1 .
METHODS set_parent
IMPORTING
!iv_parent TYPE ty_commit-parent .
METHODS set_author
IMPORTING
!iv_author TYPE ty_commit-author .
METHODS set_committer
IMPORTING
!iv_committer TYPE ty_commit-committer .
METHODS set_body
IMPORTING
!iv_body TYPE ty_commit-body .
protected section.
private section.
data MS_DATA type TY_COMMIT .
ENDCLASS.
CLASS ZCL_AGS_OBJ_COMMIT IMPLEMENTATION.
METHOD get_author.
rv_author = ms_data-author.
ENDMETHOD.
METHOD get_body.
rv_body = ms_data-body.
ENDMETHOD.
METHOD get_committer.
rv_committer = ms_data-committer.
ENDMETHOD.
METHOD get_parent.
rv_parent = ms_data-parent.
ENDMETHOD.
METHOD get_tree.
rv_tree = ms_data-tree.
ENDMETHOD.
METHOD set_author.
ms_data-author = iv_author.
ENDMETHOD.
METHOD set_body.
ms_data-body = iv_body.
ENDMETHOD.
METHOD set_committer.
ms_data-committer = iv_committer.
ENDMETHOD.
METHOD set_parent.
ms_data-parent = iv_parent.
ENDMETHOD.
METHOD set_tree.
ms_data-tree = iv_tree.
ENDMETHOD.
METHOD zif_ags_object~deserialize.
DATA: lv_string TYPE string,
lv_char40 TYPE c LENGTH 40,
lv_mode TYPE string,
lv_len TYPE i,
lt_string TYPE TABLE OF string.
FIELD-SYMBOLS: <lv_string> LIKE LINE OF lt_string.
lv_string = zcl_ags_util=>xstring_to_string_utf8( iv_data ).
SPLIT lv_string AT c_newline INTO TABLE lt_string.
lv_mode = 'tree'. "#EC NOTEXT
LOOP AT lt_string ASSIGNING <lv_string>.
lv_len = strlen( lv_mode ).
IF NOT lv_mode IS INITIAL AND <lv_string>(lv_len) = lv_mode.
CASE lv_mode.
WHEN 'tree'.
lv_char40 = <lv_string>+5.
TRANSLATE lv_char40 TO UPPER CASE.
ms_data-tree = lv_char40.
lv_mode = 'parent'. "#EC NOTEXT
WHEN 'parent'.
lv_char40 = <lv_string>+7.
TRANSLATE lv_char40 TO UPPER CASE.
ms_data-parent = lv_char40.
lv_mode = 'author'. "#EC NOTEXT
WHEN 'author'.
ms_data-author = <lv_string>+7.
lv_mode = 'committer'. "#EC NOTEXT
WHEN 'committer'.
ms_data-committer = <lv_string>+10.
CLEAR lv_mode.
ENDCASE.
ELSEIF lv_mode = 'parent' AND <lv_string>(6) = 'author'. "#EC NOTEXT
* first commit doesnt have parent
ms_data-author = <lv_string>+7.
lv_mode = 'committer'. "#EC NOTEXT
ELSE.
* body
CONCATENATE ms_data-body <lv_string> INTO ms_data-body
SEPARATED BY c_newline.
ENDIF.
ENDLOOP.
* strip first newline
IF strlen( ms_data-body ) >= 2.
ms_data-body = ms_data-body+2.
ENDIF.
IF ms_data-author IS INITIAL
OR ms_data-committer IS INITIAL
OR ms_data-tree IS INITIAL.
* multiple parents? not supported
ASSERT 1 = 2.
ENDIF.
ENDMETHOD.
METHOD zif_ags_object~save.
DATA: ls_object TYPE zags_objects.
ls_object-sha1 = sha1( ).
ls_object-type = 'commit' ##NO_TEXT.
ls_object-data = serialize( ).
MODIFY zags_objects FROM ls_object.
ENDMETHOD.
METHOD zif_ags_object~serialize.
DATA: lv_string TYPE string,
lv_tmp TYPE string,
lv_tree_lower TYPE string,
lv_parent_lower TYPE string.
lv_tree_lower = ms_data-tree.
TRANSLATE lv_tree_lower TO LOWER CASE.
lv_parent_lower = ms_data-parent.
TRANSLATE lv_parent_lower TO LOWER CASE.
lv_string = ''.
CONCATENATE 'tree' lv_tree_lower INTO lv_tmp SEPARATED BY space. "#EC NOTEXT
CONCATENATE lv_string lv_tmp c_newline INTO lv_string.
IF NOT ms_data-parent IS INITIAL.
CONCATENATE 'parent' lv_parent_lower
INTO lv_tmp SEPARATED BY space. "#EC NOTEXT
CONCATENATE lv_string lv_tmp c_newline INTO lv_string.
ENDIF.
CONCATENATE 'author' ms_data-author
INTO lv_tmp SEPARATED BY space. "#EC NOTEXT
CONCATENATE lv_string lv_tmp c_newline INTO lv_string.
CONCATENATE 'committer' ms_data-committer
INTO lv_tmp SEPARATED BY space. "#EC NOTEXT
CONCATENATE lv_string lv_tmp c_newline INTO lv_string.
CONCATENATE lv_string c_newline ms_data-body INTO lv_string.
rv_data = zcl_ags_util=>string_to_xstring_utf8( lv_string ).
ENDMETHOD.
METHOD zif_ags_object~sha1.
rv_sha1 = zcl_ags_util=>sha1(
iv_type = 'commit'
iv_data = serialize( ) ) ##NO_TEXT.
ENDMETHOD.
ENDCLASS.
|
remove whitespace
|
remove whitespace
|
ABAP
|
mit
|
larshp/abapGitServer,larshp/abapGitServer
|
2415a5c0c0907af0f49bb373f1fa67d737c45f27
|
src/objects/texts/zcl_abapgit_sotr_handler.clas.abap
|
src/objects/texts/zcl_abapgit_sotr_handler.clas.abap
|
CLASS zcl_abapgit_sotr_handler DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
CLASS-METHODS read_sotr
IMPORTING
!iv_pgmid TYPE pgmid DEFAULT 'R3TR'
!iv_object TYPE trobjtype
!iv_obj_name TYPE csequence
!io_xml TYPE REF TO zif_abapgit_xml_output OPTIONAL
!iv_language TYPE spras OPTIONAL
EXPORTING
!et_sotr TYPE zif_abapgit_definitions=>ty_sotr_tt
!et_sotr_use TYPE zif_abapgit_definitions=>ty_sotr_use_tt
RAISING
zcx_abapgit_exception .
CLASS-METHODS create_sotr
IMPORTING
!iv_package TYPE devclass
!io_xml TYPE REF TO zif_abapgit_xml_input
RAISING
zcx_abapgit_exception .
CLASS-METHODS create_sotr_from_data
IMPORTING
!iv_package TYPE devclass
!it_sotr TYPE zif_abapgit_definitions=>ty_sotr_tt
!it_sotr_use TYPE zif_abapgit_definitions=>ty_sotr_use_tt
RAISING
zcx_abapgit_exception .
CLASS-METHODS delete_sotr
IMPORTING
!iv_pgmid TYPE pgmid DEFAULT 'R3TR'
!iv_object TYPE trobjtype
!iv_obj_name TYPE csequence
RAISING
zcx_abapgit_exception .
CLASS-METHODS delete_sotr_package
IMPORTING
!iv_package TYPE devclass
RAISING
zcx_abapgit_exception .
PROTECTED SECTION.
CLASS-METHODS get_sotr_usage
IMPORTING
!iv_pgmid TYPE pgmid
!iv_object TYPE trobjtype
!iv_obj_name TYPE csequence
RETURNING
VALUE(rt_sotr_use) TYPE zif_abapgit_definitions=>ty_sotr_use_tt.
CLASS-METHODS get_sotr_4_concept
IMPORTING
!iv_concept TYPE sotr_conc
RETURNING
VALUE(rs_sotr) TYPE zif_abapgit_definitions=>ty_sotr .
PRIVATE SECTION.
ENDCLASS.
CLASS zcl_abapgit_sotr_handler IMPLEMENTATION.
METHOD create_sotr.
DATA:
lt_sotr TYPE zif_abapgit_definitions=>ty_sotr_tt,
lt_sotr_use TYPE zif_abapgit_definitions=>ty_sotr_use_tt.
io_xml->read( EXPORTING iv_name = 'SOTR'
CHANGING cg_data = lt_sotr ).
io_xml->read( EXPORTING iv_name = 'SOTR_USE'
CHANGING cg_data = lt_sotr_use ).
create_sotr_from_data(
iv_package = iv_package
it_sotr = lt_sotr
it_sotr_use = lt_sotr_use ).
ENDMETHOD.
METHOD create_sotr_from_data.
DATA:
lt_objects TYPE sotr_objects,
ls_paket TYPE sotr_pack,
lv_object LIKE LINE OF lt_objects.
FIELD-SYMBOLS: <ls_sotr> LIKE LINE OF it_sotr.
LOOP AT it_sotr ASSIGNING <ls_sotr>.
CALL FUNCTION 'SOTR_OBJECT_GET_OBJECTS'
EXPORTING
object_vector = <ls_sotr>-header-objid_vec
IMPORTING
objects = lt_objects
EXCEPTIONS
object_not_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
READ TABLE lt_objects INDEX 1 INTO lv_object.
ASSERT sy-subrc = 0.
ls_paket-paket = iv_package.
CALL FUNCTION 'SOTR_CREATE_CONCEPT'
EXPORTING
paket = ls_paket
crea_lan = <ls_sotr>-header-crea_lan
alias_name = <ls_sotr>-header-alias_name
object = lv_object
entries = <ls_sotr>-entries
concept_default = <ls_sotr>-header-concept
EXCEPTIONS
package_missing = 1
crea_lan_missing = 2
object_missing = 3
paket_does_not_exist = 4
alias_already_exist = 5
object_type_not_found = 6
langu_missing = 7
identical_context_not_allowed = 8
text_too_long = 9
error_in_update = 10
no_master_langu = 11
error_in_concept_id = 12
alias_not_allowed = 13
tadir_entry_creation_failed = 14
internal_error = 15
error_in_correction = 16
user_cancelled = 17
no_entry_found = 18
OTHERS = 19.
IF sy-subrc <> 0 AND sy-subrc <> 5.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
ENDLOOP.
CALL FUNCTION 'SOTR_USAGE_MODIFY'
EXPORTING
sotr_usage = it_sotr_use.
ENDMETHOD.
METHOD delete_sotr.
DATA lt_sotr_use TYPE zif_abapgit_definitions=>ty_sotr_use_tt.
FIELD-SYMBOLS <ls_sotr_use> LIKE LINE OF lt_sotr_use.
lt_sotr_use = get_sotr_usage( iv_pgmid = iv_pgmid
iv_object = iv_object
iv_obj_name = iv_obj_name ).
LOOP AT lt_sotr_use ASSIGNING <ls_sotr_use> WHERE concept IS NOT INITIAL.
CALL FUNCTION 'SOTR_DELETE_CONCEPT'
EXPORTING
concept = <ls_sotr_use>-concept
EXCEPTIONS
no_entry_found = 1
text_not_found = 2
invalid_package = 3
text_not_changeable = 4
text_enqueued = 5
no_correction = 6
parameter_error = 7
OTHERS = 8.
IF sy-subrc > 2.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
ENDLOOP.
ENDMETHOD.
METHOD delete_sotr_package.
DATA lt_sotr_head TYPE STANDARD TABLE OF sotr_head WITH DEFAULT KEY.
FIELD-SYMBOLS <ls_sotr_head> LIKE LINE OF lt_sotr_head.
SELECT * FROM sotr_head INTO TABLE lt_sotr_head WHERE paket = iv_package.
LOOP AT lt_sotr_head ASSIGNING <ls_sotr_head> WHERE concept IS NOT INITIAL.
CALL FUNCTION 'SOTR_DELETE_CONCEPT'
EXPORTING
concept = <ls_sotr_head>-concept
EXCEPTIONS
no_entry_found = 1
text_not_found = 2
invalid_package = 3
text_not_changeable = 4
text_enqueued = 5
no_correction = 6
parameter_error = 7
OTHERS = 8.
IF sy-subrc > 2.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
ENDLOOP.
ENDMETHOD.
METHOD get_sotr_4_concept.
DATA: ls_header TYPE zif_abapgit_definitions=>ty_sotr-header,
lt_entries TYPE zif_abapgit_definitions=>ty_sotr-entries.
FIELD-SYMBOLS: <ls_entry> LIKE LINE OF lt_entries.
CALL FUNCTION 'SOTR_GET_CONCEPT'
EXPORTING
concept = iv_concept
IMPORTING
header = ls_header
TABLES
entries = lt_entries
EXCEPTIONS
no_entry_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
RETURN.
ENDIF.
CLEAR: ls_header-paket,
ls_header-crea_name,
ls_header-crea_tstut,
ls_header-chan_name,
ls_header-chan_tstut,
ls_header-system_id.
LOOP AT lt_entries ASSIGNING <ls_entry>.
CLEAR: <ls_entry>-version,
<ls_entry>-crea_name,
<ls_entry>-crea_tstut,
<ls_entry>-chan_name,
<ls_entry>-chan_tstut.
ENDLOOP.
rs_sotr-header = ls_header.
rs_sotr-entries = lt_entries.
ENDMETHOD.
METHOD get_sotr_usage.
DATA: lv_obj_name TYPE trobj_name.
lv_obj_name = iv_obj_name.
" Objects with multiple components
IF iv_pgmid = 'LIMU' AND ( iv_object CP 'WDY*' OR iv_object = 'WAPP' ).
lv_obj_name+30 = '%'.
ENDIF.
CALL FUNCTION 'SOTR_USAGE_READ'
EXPORTING
pgmid = iv_pgmid
object = iv_object
obj_name = lv_obj_name
IMPORTING
sotr_usage = rt_sotr_use
EXCEPTIONS
no_entry_found = 1
error_in_pgmid = 2
OTHERS = 3.
IF sy-subrc = 0.
SORT rt_sotr_use.
ENDIF.
ENDMETHOD.
METHOD read_sotr.
FIELD-SYMBOLS <ls_sotr_use> LIKE LINE OF et_sotr_use.
DATA: lv_sotr TYPE zif_abapgit_definitions=>ty_sotr,
lt_language_filter TYPE zif_abapgit_environment=>ty_system_language_filter.
" SOTR usage (see LSOTR_SYSTEM_SETTINGSF01, FORM GET_OBJECT_TABLE)
" LIMU: CPUB, WAPP, WDYC, WDYD, WDYV
" R3TR: ENHC, ENHD, ENHO, ENHS, ENSC, SCGR, SICF, WDCA, WDCC, WDYA, WEBI, WEBS, XSLT
et_sotr_use = get_sotr_usage( iv_pgmid = iv_pgmid
iv_object = iv_object
iv_obj_name = iv_obj_name ).
LOOP AT et_sotr_use ASSIGNING <ls_sotr_use> WHERE concept IS NOT INITIAL.
lv_sotr = get_sotr_4_concept( <ls_sotr_use>-concept ).
IF io_xml IS BOUND AND
io_xml->i18n_params( )-main_language_only = abap_true AND
iv_language IS SUPPLIED.
DELETE lv_sotr-entries WHERE langu <> iv_language.
CHECK lv_sotr-entries IS NOT INITIAL.
ENDIF.
lt_language_filter = zcl_abapgit_factory=>get_environment( )->get_system_language_filter( ).
DELETE lv_sotr-entries WHERE NOT langu IN lt_language_filter.
CHECK lv_sotr-entries IS NOT INITIAL.
INSERT lv_sotr INTO TABLE et_sotr.
ENDLOOP.
IF io_xml IS BOUND.
io_xml->add( iv_name = 'SOTR'
ig_data = et_sotr ).
io_xml->add( iv_name = 'SOTR_USE'
ig_data = et_sotr_use ).
ENDIF.
ENDMETHOD.
ENDCLASS.
|
CLASS zcl_abapgit_sotr_handler DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
CLASS-METHODS read_sotr
IMPORTING
!iv_pgmid TYPE pgmid DEFAULT 'R3TR'
!iv_object TYPE trobjtype
!iv_obj_name TYPE csequence
!io_xml TYPE REF TO zif_abapgit_xml_output OPTIONAL
!iv_language TYPE spras OPTIONAL
EXPORTING
!et_sotr TYPE zif_abapgit_definitions=>ty_sotr_tt
!et_sotr_use TYPE zif_abapgit_definitions=>ty_sotr_use_tt
RAISING
zcx_abapgit_exception .
CLASS-METHODS create_sotr
IMPORTING
!iv_package TYPE devclass
!io_xml TYPE REF TO zif_abapgit_xml_input
RAISING
zcx_abapgit_exception .
CLASS-METHODS create_sotr_from_data
IMPORTING
!iv_package TYPE devclass
!it_sotr TYPE zif_abapgit_definitions=>ty_sotr_tt
!it_sotr_use TYPE zif_abapgit_definitions=>ty_sotr_use_tt
RAISING
zcx_abapgit_exception .
CLASS-METHODS delete_sotr
IMPORTING
!iv_pgmid TYPE pgmid DEFAULT 'R3TR'
!iv_object TYPE trobjtype
!iv_obj_name TYPE csequence
RAISING
zcx_abapgit_exception .
CLASS-METHODS delete_sotr_package
IMPORTING
!iv_package TYPE devclass
RAISING
zcx_abapgit_exception .
PROTECTED SECTION.
CLASS-METHODS get_sotr_usage
IMPORTING
!iv_pgmid TYPE pgmid
!iv_object TYPE trobjtype
!iv_obj_name TYPE csequence
RETURNING
VALUE(rt_sotr_use) TYPE zif_abapgit_definitions=>ty_sotr_use_tt.
CLASS-METHODS get_sotr_4_concept
IMPORTING
!iv_concept TYPE sotr_conc
RETURNING
VALUE(rs_sotr) TYPE zif_abapgit_definitions=>ty_sotr .
PRIVATE SECTION.
ENDCLASS.
CLASS zcl_abapgit_sotr_handler IMPLEMENTATION.
METHOD create_sotr.
DATA:
lt_sotr TYPE zif_abapgit_definitions=>ty_sotr_tt,
lt_sotr_use TYPE zif_abapgit_definitions=>ty_sotr_use_tt.
io_xml->read( EXPORTING iv_name = 'SOTR'
CHANGING cg_data = lt_sotr ).
io_xml->read( EXPORTING iv_name = 'SOTR_USE'
CHANGING cg_data = lt_sotr_use ).
create_sotr_from_data(
iv_package = iv_package
it_sotr = lt_sotr
it_sotr_use = lt_sotr_use ).
ENDMETHOD.
METHOD create_sotr_from_data.
DATA:
lt_objects TYPE sotr_objects,
ls_paket TYPE sotr_pack,
lv_object LIKE LINE OF lt_objects.
FIELD-SYMBOLS: <ls_sotr> LIKE LINE OF it_sotr.
LOOP AT it_sotr ASSIGNING <ls_sotr>.
CALL FUNCTION 'SOTR_OBJECT_GET_OBJECTS'
EXPORTING
object_vector = <ls_sotr>-header-objid_vec
IMPORTING
objects = lt_objects
EXCEPTIONS
object_not_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
READ TABLE lt_objects INDEX 1 INTO lv_object.
ASSERT sy-subrc = 0.
ls_paket-paket = iv_package.
CALL FUNCTION 'SOTR_CREATE_CONCEPT'
EXPORTING
paket = ls_paket
crea_lan = <ls_sotr>-header-crea_lan
alias_name = <ls_sotr>-header-alias_name
object = lv_object
entries = <ls_sotr>-entries
concept_default = <ls_sotr>-header-concept
EXCEPTIONS
package_missing = 1
crea_lan_missing = 2
object_missing = 3
paket_does_not_exist = 4
alias_already_exist = 5
object_type_not_found = 6
langu_missing = 7
identical_context_not_allowed = 8
text_too_long = 9
error_in_update = 10
no_master_langu = 11
error_in_concept_id = 12
alias_not_allowed = 13
tadir_entry_creation_failed = 14
internal_error = 15
error_in_correction = 16
user_cancelled = 17
no_entry_found = 18
OTHERS = 19.
IF sy-subrc <> 0 AND sy-subrc <> 5.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
ENDLOOP.
CALL FUNCTION 'SOTR_USAGE_MODIFY'
EXPORTING
sotr_usage = it_sotr_use.
ENDMETHOD.
METHOD delete_sotr.
DATA lt_sotr_use TYPE zif_abapgit_definitions=>ty_sotr_use_tt.
FIELD-SYMBOLS <ls_sotr_use> LIKE LINE OF lt_sotr_use.
lt_sotr_use = get_sotr_usage( iv_pgmid = iv_pgmid
iv_object = iv_object
iv_obj_name = iv_obj_name ).
LOOP AT lt_sotr_use ASSIGNING <ls_sotr_use> WHERE concept IS NOT INITIAL.
CALL FUNCTION 'SOTR_DELETE_CONCEPT'
EXPORTING
concept = <ls_sotr_use>-concept
EXCEPTIONS
no_entry_found = 1
text_not_found = 2
invalid_package = 3
text_not_changeable = 4
text_enqueued = 5
no_correction = 6
parameter_error = 7
OTHERS = 8.
IF sy-subrc > 2.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
ENDLOOP.
ENDMETHOD.
METHOD delete_sotr_package.
DATA lt_sotr_head TYPE STANDARD TABLE OF sotr_head WITH DEFAULT KEY.
DATA lv_obj_name TYPE tadir-obj_name.
FIELD-SYMBOLS <ls_sotr_head> LIKE LINE OF lt_sotr_head.
SELECT * FROM sotr_head INTO TABLE lt_sotr_head WHERE paket = iv_package.
LOOP AT lt_sotr_head ASSIGNING <ls_sotr_head> WHERE concept IS NOT INITIAL.
CALL FUNCTION 'SOTR_DELETE_CONCEPT'
EXPORTING
concept = <ls_sotr_head>-concept
EXCEPTIONS
no_entry_found = 1
text_not_found = 2
invalid_package = 3
text_not_changeable = 4
text_enqueued = 5
no_correction = 6
parameter_error = 7
OTHERS = 8.
IF sy-subrc > 2.
zcx_abapgit_exception=>raise_t100( ).
ENDIF.
ENDLOOP.
" Nothing left, then delete SOTR from TADIR
SELECT * FROM sotr_head INTO TABLE lt_sotr_head WHERE paket = iv_package.
IF sy-subrc <> 0.
SELECT SINGLE obj_name FROM tadir INTO lv_obj_name
WHERE pgmid = 'R3TR' AND object = 'SOTR' AND obj_name = iv_package.
IF sy-subrc = 0.
CALL FUNCTION 'TR_TADIR_INTERFACE'
EXPORTING
wi_delete_tadir_entry = abap_true
wi_test_modus = abap_false
wi_tadir_pgmid = 'R3TR'
wi_tadir_object = 'SOTR'
wi_tadir_obj_name = lv_obj_name
EXCEPTIONS
OTHERS = 1 ##FM_SUBRC_OK.
IF zcl_abapgit_factory=>get_sap_package( iv_package )->are_changes_recorded_in_tr_req( ) = abap_true.
CALL FUNCTION 'RS_CORR_INSERT'
EXPORTING
object = lv_obj_name
object_class = 'SOTR'
mode = 'D'
global_lock = abap_true
devclass = iv_package
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.
ENDIF.
ENDIF.
ENDIF.
ENDMETHOD.
METHOD get_sotr_4_concept.
DATA: ls_header TYPE zif_abapgit_definitions=>ty_sotr-header,
lt_entries TYPE zif_abapgit_definitions=>ty_sotr-entries.
FIELD-SYMBOLS: <ls_entry> LIKE LINE OF lt_entries.
CALL FUNCTION 'SOTR_GET_CONCEPT'
EXPORTING
concept = iv_concept
IMPORTING
header = ls_header
TABLES
entries = lt_entries
EXCEPTIONS
no_entry_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
RETURN.
ENDIF.
CLEAR: ls_header-paket,
ls_header-crea_name,
ls_header-crea_tstut,
ls_header-chan_name,
ls_header-chan_tstut,
ls_header-system_id.
LOOP AT lt_entries ASSIGNING <ls_entry>.
CLEAR: <ls_entry>-version,
<ls_entry>-crea_name,
<ls_entry>-crea_tstut,
<ls_entry>-chan_name,
<ls_entry>-chan_tstut.
ENDLOOP.
rs_sotr-header = ls_header.
rs_sotr-entries = lt_entries.
ENDMETHOD.
METHOD get_sotr_usage.
DATA: lv_obj_name TYPE trobj_name.
lv_obj_name = iv_obj_name.
" Objects with multiple components
IF iv_pgmid = 'LIMU' AND ( iv_object CP 'WDY*' OR iv_object = 'WAPP' ).
lv_obj_name+30 = '%'.
ENDIF.
CALL FUNCTION 'SOTR_USAGE_READ'
EXPORTING
pgmid = iv_pgmid
object = iv_object
obj_name = lv_obj_name
IMPORTING
sotr_usage = rt_sotr_use
EXCEPTIONS
no_entry_found = 1
error_in_pgmid = 2
OTHERS = 3.
IF sy-subrc = 0.
SORT rt_sotr_use.
ENDIF.
ENDMETHOD.
METHOD read_sotr.
FIELD-SYMBOLS <ls_sotr_use> LIKE LINE OF et_sotr_use.
DATA: lv_sotr TYPE zif_abapgit_definitions=>ty_sotr,
lt_language_filter TYPE zif_abapgit_environment=>ty_system_language_filter.
" SOTR usage (see LSOTR_SYSTEM_SETTINGSF01, FORM GET_OBJECT_TABLE)
" LIMU: CPUB, WAPP, WDYC, WDYD, WDYV
" R3TR: ENHC, ENHD, ENHO, ENHS, ENSC, SCGR, SICF, WDCA, WDCC, WDYA, WEBI, WEBS, XSLT
et_sotr_use = get_sotr_usage( iv_pgmid = iv_pgmid
iv_object = iv_object
iv_obj_name = iv_obj_name ).
LOOP AT et_sotr_use ASSIGNING <ls_sotr_use> WHERE concept IS NOT INITIAL.
lv_sotr = get_sotr_4_concept( <ls_sotr_use>-concept ).
IF io_xml IS BOUND AND
io_xml->i18n_params( )-main_language_only = abap_true AND
iv_language IS SUPPLIED.
DELETE lv_sotr-entries WHERE langu <> iv_language.
CHECK lv_sotr-entries IS NOT INITIAL.
ENDIF.
lt_language_filter = zcl_abapgit_factory=>get_environment( )->get_system_language_filter( ).
DELETE lv_sotr-entries WHERE NOT langu IN lt_language_filter.
CHECK lv_sotr-entries IS NOT INITIAL.
INSERT lv_sotr INTO TABLE et_sotr.
ENDLOOP.
IF io_xml IS BOUND.
io_xml->add( iv_name = 'SOTR'
ig_data = et_sotr ).
io_xml->add( iv_name = 'SOTR_USE'
ig_data = et_sotr_use ).
ENDIF.
ENDMETHOD.
ENDCLASS.
|
Fix uninstall (#5558)
|
SOTR: Fix uninstall (#5558)
After all OTR usage has been removed, uninstall will now also delete the TADIR entry for SOTR. This is necessary in order to delete the corresponding package.
|
ABAP
|
mit
|
sbcgua/abapGit,sbcgua/abapGit
|
5ed2f5bb2257afa6ee9299a471a6370476a6aa36
|
src/objects/zcl_abapgit_object_doma.clas.abap
|
src/objects/zcl_abapgit_object_doma.clas.abap
|
CLASS zcl_abapgit_object_doma 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.
PRIVATE SECTION.
TYPES:
BEGIN OF ty_dd01_text,
ddlanguage TYPE dd01v-ddlanguage,
ddtext TYPE dd01v-ddtext,
END OF ty_dd01_text .
TYPES:
BEGIN OF ty_dd07_text,
valpos TYPE dd07v-valpos,
ddlanguage TYPE dd07v-ddlanguage,
domvalue_l TYPE dd07v-domvalue_l,
domvalue_h TYPE dd07v-domvalue_h,
ddtext TYPE dd07v-ddtext,
domval_ld TYPE dd07v-domval_ld,
domval_hd TYPE dd07v-domval_hd,
END OF ty_dd07_text .
TYPES:
ty_dd01_texts TYPE STANDARD TABLE OF ty_dd01_text .
TYPES:
ty_dd07_texts TYPE STANDARD TABLE OF ty_dd07_text .
CONSTANTS c_longtext_id_doma TYPE dokil-id VALUE 'DO' ##NO_TEXT.
METHODS serialize_texts
IMPORTING
!ii_xml TYPE REF TO zif_abapgit_xml_output
!it_dd07v TYPE dd07v_tab
RAISING
zcx_abapgit_exception .
METHODS deserialize_texts
IMPORTING
!ii_xml TYPE REF TO zif_abapgit_xml_input
!is_dd01v TYPE dd01v
!it_dd07v TYPE dd07v_tab
RAISING
zcx_abapgit_exception .
ENDCLASS.
CLASS zcl_abapgit_object_doma IMPLEMENTATION.
METHOD deserialize_texts.
DATA: lv_name TYPE ddobjname,
lv_valpos TYPE valpos,
ls_dd01v_tmp TYPE dd01v,
lt_dd07v_tmp TYPE TABLE OF dd07v,
lt_i18n_langs TYPE TABLE OF langu,
lt_dd01_texts TYPE ty_dd01_texts,
lt_dd07_texts TYPE ty_dd07_texts.
FIELD-SYMBOLS: <lv_lang> LIKE LINE OF lt_i18n_langs,
<ls_dd07v> LIKE LINE OF it_dd07v,
<ls_dd01_text> LIKE LINE OF lt_dd01_texts,
<ls_dd07_text> LIKE LINE OF lt_dd07_texts.
lv_name = ms_item-obj_name.
ii_xml->read( EXPORTING iv_name = 'I18N_LANGS'
CHANGING cg_data = lt_i18n_langs ).
ii_xml->read( EXPORTING iv_name = 'DD01_TEXTS'
CHANGING cg_data = lt_dd01_texts ).
ii_xml->read( EXPORTING iv_name = 'DD07_TEXTS'
CHANGING cg_data = lt_dd07_texts ).
SORT lt_i18n_langs.
SORT lt_dd07_texts BY ddlanguage. " Optimization
LOOP AT lt_i18n_langs ASSIGNING <lv_lang>.
" Domain description
ls_dd01v_tmp = is_dd01v.
READ TABLE lt_dd01_texts ASSIGNING <ls_dd01_text> WITH KEY ddlanguage = <lv_lang>.
IF sy-subrc > 0.
zcx_abapgit_exception=>raise( |DD01_TEXTS cannot find lang { <lv_lang> } in XML| ).
ENDIF.
MOVE-CORRESPONDING <ls_dd01_text> TO ls_dd01v_tmp.
" Domain values
lt_dd07v_tmp = it_dd07v.
LOOP AT lt_dd07v_tmp ASSIGNING <ls_dd07v>.
lv_valpos = <ls_dd07v>-valpos.
" it_dd07v was potentially renumbered so lookup by value
READ TABLE lt_dd07_texts ASSIGNING <ls_dd07_text>
WITH KEY ddlanguage = <lv_lang> domvalue_l = <ls_dd07v>-domvalue_l domvalue_h = <ls_dd07v>-domvalue_h.
IF sy-subrc = 0.
MOVE-CORRESPONDING <ls_dd07_text> TO <ls_dd07v>.
<ls_dd07v>-valpos = lv_valpos.
DELETE lt_dd07_texts INDEX sy-tabix. " Optimization
ELSE.
" no translation -> keep entry but clear texts
<ls_dd07v>-ddlanguage = <lv_lang>.
CLEAR: <ls_dd07v>-ddtext, <ls_dd07v>-domval_ld, <ls_dd07v>-domval_hd.
ENDIF.
ENDLOOP.
CALL FUNCTION 'DDIF_DOMA_PUT'
EXPORTING
name = lv_name
dd01v_wa = ls_dd01v_tmp
TABLES
dd07v_tab = lt_dd07v_tmp
EXCEPTIONS
doma_not_found = 1
name_inconsistent = 2
doma_inconsistent = 3
put_failure = 4
put_refused = 5
OTHERS = 6.
IF sy-subrc <> 0.
zcx_abapgit_exception=>raise( 'error from DDIF_DOMA_PUT @TEXTS' ).
ENDIF.
ENDLOOP.
ENDMETHOD.
METHOD serialize_texts.
DATA: lv_name TYPE ddobjname,
lv_index TYPE i,
ls_dd01v TYPE dd01v,
lt_dd07v TYPE TABLE OF dd07v,
lt_i18n_langs TYPE TABLE OF langu,
lt_dd01_texts TYPE ty_dd01_texts,
lt_dd07_texts TYPE ty_dd07_texts.
FIELD-SYMBOLS: <lv_lang> LIKE LINE OF lt_i18n_langs,
<ls_dd07v> LIKE LINE OF lt_dd07v,
<ls_dd07v_tmp> LIKE LINE OF lt_dd07v,
<ls_dd01_text> LIKE LINE OF lt_dd01_texts,
<ls_dd07_text> LIKE LINE OF lt_dd07_texts.
IF ii_xml->i18n_params( )-serialize_master_lang_only = abap_true.
RETURN.
ENDIF.
lv_name = ms_item-obj_name.
" Collect additional languages, skip main lang - it was serialized already
SELECT DISTINCT ddlanguage AS langu INTO TABLE lt_i18n_langs
FROM dd01v
WHERE domname = lv_name
AND ddlanguage <> mv_language. "#EC CI_SUBRC
LOOP AT lt_i18n_langs ASSIGNING <lv_lang>.
lv_index = sy-tabix.
CALL FUNCTION 'DDIF_DOMA_GET'
EXPORTING
name = lv_name
langu = <lv_lang>
IMPORTING
dd01v_wa = ls_dd01v
TABLES
dd07v_tab = lt_dd07v
EXCEPTIONS
illegal_input = 1
OTHERS = 2.
IF sy-subrc <> 0 OR ls_dd01v-ddlanguage IS INITIAL.
DELETE lt_i18n_langs INDEX lv_index. " Don't save this lang
CONTINUE.
ENDIF.
APPEND INITIAL LINE TO lt_dd01_texts ASSIGNING <ls_dd01_text>.
MOVE-CORRESPONDING ls_dd01v TO <ls_dd01_text>.
" Process main language entries and find corresponding translation
LOOP AT it_dd07v ASSIGNING <ls_dd07v> WHERE NOT ddlanguage IS INITIAL.
APPEND INITIAL LINE TO lt_dd07_texts ASSIGNING <ls_dd07_text>.
READ TABLE lt_dd07v ASSIGNING <ls_dd07v_tmp>
WITH KEY ddlanguage = <lv_lang> domvalue_l = <ls_dd07v>-domvalue_l domvalue_h = <ls_dd07v>-domvalue_h.
IF sy-subrc = 0.
MOVE-CORRESPONDING <ls_dd07v_tmp> TO <ls_dd07_text>.
ELSE.
" no translation -> keep entry but clear texts
<ls_dd07_text>-ddlanguage = <lv_lang>.
CLEAR: <ls_dd07_text>-ddtext, <ls_dd07_text>-domval_ld, <ls_dd07_text>-domval_hd.
ENDIF.
ENDLOOP.
ENDLOOP.
SORT lt_i18n_langs ASCENDING.
SORT lt_dd01_texts BY ddlanguage ASCENDING.
SORT lt_dd07_texts BY valpos ASCENDING ddlanguage ASCENDING.
IF lines( lt_i18n_langs ) > 0.
ii_xml->add( iv_name = 'I18N_LANGS'
ig_data = lt_i18n_langs ).
ii_xml->add( iv_name = 'DD01_TEXTS'
ig_data = lt_dd01_texts ).
ii_xml->add( iv_name = 'DD07_TEXTS'
ig_data = lt_dd07_texts ).
ENDIF.
ENDMETHOD.
METHOD zif_abapgit_object~changed_by.
SELECT SINGLE as4user FROM dd01l INTO rv_user
WHERE domname = ms_item-obj_name
AND as4local = 'A'
AND as4vers = '0000'.
IF sy-subrc <> 0.
rv_user = c_user_unknown.
ENDIF.
ENDMETHOD.
METHOD zif_abapgit_object~delete.
IF zif_abapgit_object~exists( ) = abap_false.
RETURN.
ENDIF.
delete_ddic( iv_objtype = 'D'
iv_no_ask_delete_append = abap_true ).
delete_longtexts( c_longtext_id_doma ).
ENDMETHOD.
METHOD zif_abapgit_object~deserialize.
* package SEDD
* package SDIC
* fm TR_TADIR_INTERFACE
* fm RS_CORR_INSERT ?
DATA: lv_name TYPE ddobjname,
ls_dd01v TYPE dd01v,
lt_dd07v TYPE TABLE OF dd07v.
FIELD-SYMBOLS <ls_dd07v> TYPE dd07v.
io_xml->read( EXPORTING iv_name = 'DD01V'
CHANGING cg_data = ls_dd01v ).
io_xml->read( EXPORTING iv_name = 'DD07V_TAB'
CHANGING cg_data = lt_dd07v ).
corr_insert( iv_package = iv_package
ig_object_class = 'DICT' ).
lv_name = ms_item-obj_name. " type conversion
LOOP AT lt_dd07v ASSIGNING <ls_dd07v>.
<ls_dd07v>-domname = lv_name.
<ls_dd07v>-valpos = sy-tabix.
ENDLOOP.
CALL FUNCTION 'DDIF_DOMA_PUT'
EXPORTING
name = lv_name
dd01v_wa = ls_dd01v
TABLES
dd07v_tab = lt_dd07v
EXCEPTIONS
doma_not_found = 1
name_inconsistent = 2
doma_inconsistent = 3
put_failure = 4
put_refused = 5
OTHERS = 6.
IF sy-subrc <> 0.
zcx_abapgit_exception=>raise( 'error from DDIF_DOMA_PUT' ).
ENDIF.
deserialize_texts( ii_xml = io_xml
is_dd01v = ls_dd01v
it_dd07v = lt_dd07v ).
deserialize_longtexts( io_xml ).
zcl_abapgit_objects_activation=>add_item( ms_item ).
ENDMETHOD.
METHOD zif_abapgit_object~exists.
DATA: lv_domname TYPE dd01l-domname.
SELECT SINGLE domname FROM dd01l INTO lv_domname
WHERE domname = ms_item-obj_name.
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-ddic 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-DOMA'
iv_field = 'RSRD1-DOMA_VAL' ).
ENDMETHOD.
METHOD zif_abapgit_object~serialize.
DATA: lv_name TYPE ddobjname,
ls_dd01v TYPE dd01v,
lv_masklen TYPE c LENGTH 4,
lt_dd07v TYPE TABLE OF dd07v.
lv_name = ms_item-obj_name.
CALL FUNCTION 'DDIF_DOMA_GET'
EXPORTING
name = lv_name
langu = mv_language
IMPORTING
dd01v_wa = ls_dd01v
TABLES
dd07v_tab = lt_dd07v
EXCEPTIONS
illegal_input = 1
OTHERS = 2.
IF sy-subrc <> 0 OR ls_dd01v IS INITIAL.
zcx_abapgit_exception=>raise( 'error from DDIF_DOMA_GET' ).
ENDIF.
CLEAR: ls_dd01v-as4user,
ls_dd01v-as4date,
ls_dd01v-as4time,
ls_dd01v-appexist.
* make sure XML serialization does not dump if the field contains invalid data
* note that this is a N field, so '' is not valid
IF ls_dd01v-authclass = ''.
CLEAR ls_dd01v-authclass.
ENDIF.
lv_masklen = ls_dd01v-masklen.
IF lv_masklen = '' OR NOT lv_masklen CO '0123456789'.
CLEAR ls_dd01v-masklen.
ENDIF.
DELETE lt_dd07v WHERE appval = abap_true.
SORT lt_dd07v BY
valpos ASCENDING
ddlanguage ASCENDING.
io_xml->add( iv_name = 'DD01V'
ig_data = ls_dd01v ).
io_xml->add( iv_name = 'DD07V_TAB'
ig_data = lt_dd07v ).
serialize_texts( ii_xml = io_xml
it_dd07v = lt_dd07v ).
serialize_longtexts( ii_xml = io_xml
iv_longtext_id = c_longtext_id_doma ).
ENDMETHOD.
ENDCLASS.
|
CLASS zcl_abapgit_object_doma 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.
PRIVATE SECTION.
TYPES:
BEGIN OF ty_dd01_text,
ddlanguage TYPE dd01v-ddlanguage,
ddtext TYPE dd01v-ddtext,
END OF ty_dd01_text .
TYPES:
BEGIN OF ty_dd07_text,
valpos TYPE dd07v-valpos,
ddlanguage TYPE dd07v-ddlanguage,
domvalue_l TYPE dd07v-domvalue_l,
domvalue_h TYPE dd07v-domvalue_h,
ddtext TYPE dd07v-ddtext,
domval_ld TYPE dd07v-domval_ld,
domval_hd TYPE dd07v-domval_hd,
END OF ty_dd07_text .
TYPES:
ty_dd01_texts TYPE STANDARD TABLE OF ty_dd01_text .
TYPES:
ty_dd07_texts TYPE STANDARD TABLE OF ty_dd07_text .
CONSTANTS c_longtext_id_doma TYPE dokil-id VALUE 'DO' ##NO_TEXT.
METHODS serialize_texts
IMPORTING
!ii_xml TYPE REF TO zif_abapgit_xml_output
!it_dd07v TYPE dd07v_tab
RAISING
zcx_abapgit_exception .
METHODS deserialize_texts
IMPORTING
!ii_xml TYPE REF TO zif_abapgit_xml_input
!is_dd01v TYPE dd01v
!it_dd07v TYPE dd07v_tab
RAISING
zcx_abapgit_exception .
ENDCLASS.
CLASS zcl_abapgit_object_doma IMPLEMENTATION.
METHOD deserialize_texts.
DATA: lv_name TYPE ddobjname,
lv_valpos TYPE valpos,
ls_dd01v_tmp TYPE dd01v,
lt_dd07v_tmp TYPE TABLE OF dd07v,
lt_i18n_langs TYPE TABLE OF langu,
lt_dd01_texts TYPE ty_dd01_texts,
lt_dd07_texts TYPE ty_dd07_texts.
FIELD-SYMBOLS: <lv_lang> LIKE LINE OF lt_i18n_langs,
<ls_dd07v> LIKE LINE OF it_dd07v,
<ls_dd01_text> LIKE LINE OF lt_dd01_texts,
<ls_dd07_text> LIKE LINE OF lt_dd07_texts.
lv_name = ms_item-obj_name.
ii_xml->read( EXPORTING iv_name = 'I18N_LANGS'
CHANGING cg_data = lt_i18n_langs ).
ii_xml->read( EXPORTING iv_name = 'DD01_TEXTS'
CHANGING cg_data = lt_dd01_texts ).
ii_xml->read( EXPORTING iv_name = 'DD07_TEXTS'
CHANGING cg_data = lt_dd07_texts ).
SORT lt_i18n_langs.
SORT lt_dd07_texts BY ddlanguage. " Optimization
LOOP AT lt_i18n_langs ASSIGNING <lv_lang>.
" Domain description
ls_dd01v_tmp = is_dd01v.
READ TABLE lt_dd01_texts ASSIGNING <ls_dd01_text> WITH KEY ddlanguage = <lv_lang>.
IF sy-subrc > 0.
zcx_abapgit_exception=>raise( |DD01_TEXTS cannot find lang { <lv_lang> } in XML| ).
ENDIF.
MOVE-CORRESPONDING <ls_dd01_text> TO ls_dd01v_tmp.
" Domain values
lt_dd07v_tmp = it_dd07v.
LOOP AT lt_dd07v_tmp ASSIGNING <ls_dd07v>.
lv_valpos = <ls_dd07v>-valpos.
" it_dd07v was potentially renumbered so lookup by value
READ TABLE lt_dd07_texts ASSIGNING <ls_dd07_text>
WITH KEY ddlanguage = <lv_lang> domvalue_l = <ls_dd07v>-domvalue_l domvalue_h = <ls_dd07v>-domvalue_h.
IF sy-subrc = 0.
MOVE-CORRESPONDING <ls_dd07_text> TO <ls_dd07v>.
<ls_dd07v>-valpos = lv_valpos.
DELETE lt_dd07_texts INDEX sy-tabix. " Optimization
ELSE.
" no translation -> keep entry but clear texts
<ls_dd07v>-ddlanguage = <lv_lang>.
CLEAR: <ls_dd07v>-ddtext, <ls_dd07v>-domval_ld, <ls_dd07v>-domval_hd.
ENDIF.
ENDLOOP.
CALL FUNCTION 'DDIF_DOMA_PUT'
EXPORTING
name = lv_name
dd01v_wa = ls_dd01v_tmp
TABLES
dd07v_tab = lt_dd07v_tmp
EXCEPTIONS
doma_not_found = 1
name_inconsistent = 2
doma_inconsistent = 3
put_failure = 4
put_refused = 5
OTHERS = 6.
IF sy-subrc <> 0.
zcx_abapgit_exception=>raise( 'error from DDIF_DOMA_PUT @TEXTS' ).
ENDIF.
ENDLOOP.
ENDMETHOD.
METHOD serialize_texts.
DATA: lv_name TYPE ddobjname,
lv_index TYPE i,
ls_dd01v TYPE dd01v,
lt_dd07v TYPE TABLE OF dd07v,
lt_i18n_langs TYPE TABLE OF langu,
lt_dd01_texts TYPE ty_dd01_texts,
lt_dd07_texts TYPE ty_dd07_texts.
FIELD-SYMBOLS: <lv_lang> LIKE LINE OF lt_i18n_langs,
<ls_dd07v> LIKE LINE OF lt_dd07v,
<ls_dd07v_tmp> LIKE LINE OF lt_dd07v,
<ls_dd01_text> LIKE LINE OF lt_dd01_texts,
<ls_dd07_text> LIKE LINE OF lt_dd07_texts.
IF ii_xml->i18n_params( )-serialize_master_lang_only = abap_true.
RETURN.
ENDIF.
lv_name = ms_item-obj_name.
" Collect additional languages, skip main lang - it was serialized already
SELECT DISTINCT ddlanguage AS langu INTO TABLE lt_i18n_langs
FROM dd01v
WHERE domname = lv_name
AND ddlanguage <> mv_language. "#EC CI_SUBRC
LOOP AT lt_i18n_langs ASSIGNING <lv_lang>.
lv_index = sy-tabix.
CALL FUNCTION 'DDIF_DOMA_GET'
EXPORTING
name = lv_name
langu = <lv_lang>
IMPORTING
dd01v_wa = ls_dd01v
TABLES
dd07v_tab = lt_dd07v
EXCEPTIONS
illegal_input = 1
OTHERS = 2.
IF sy-subrc <> 0 OR ls_dd01v-ddlanguage IS INITIAL.
DELETE lt_i18n_langs INDEX lv_index. " Don't save this lang
CONTINUE.
ENDIF.
APPEND INITIAL LINE TO lt_dd01_texts ASSIGNING <ls_dd01_text>.
MOVE-CORRESPONDING ls_dd01v TO <ls_dd01_text>.
" Process main language entries and find corresponding translation
LOOP AT it_dd07v ASSIGNING <ls_dd07v> WHERE NOT ddlanguage IS INITIAL.
APPEND INITIAL LINE TO lt_dd07_texts ASSIGNING <ls_dd07_text>.
READ TABLE lt_dd07v ASSIGNING <ls_dd07v_tmp>
WITH KEY ddlanguage = <lv_lang> domvalue_l = <ls_dd07v>-domvalue_l domvalue_h = <ls_dd07v>-domvalue_h.
IF sy-subrc = 0.
MOVE-CORRESPONDING <ls_dd07v_tmp> TO <ls_dd07_text>.
ELSE.
" no translation -> keep entry but clear texts
MOVE-CORRESPONDING <ls_dd07v> TO <ls_dd07_text>.
<ls_dd07_text>-ddlanguage = <lv_lang>.
CLEAR: <ls_dd07_text>-ddtext, <ls_dd07_text>-domval_ld, <ls_dd07_text>-domval_hd.
ENDIF.
ENDLOOP.
ENDLOOP.
SORT lt_i18n_langs ASCENDING.
SORT lt_dd01_texts BY ddlanguage ASCENDING.
SORT lt_dd07_texts BY valpos ASCENDING ddlanguage ASCENDING.
IF lines( lt_i18n_langs ) > 0.
ii_xml->add( iv_name = 'I18N_LANGS'
ig_data = lt_i18n_langs ).
ii_xml->add( iv_name = 'DD01_TEXTS'
ig_data = lt_dd01_texts ).
ii_xml->add( iv_name = 'DD07_TEXTS'
ig_data = lt_dd07_texts ).
ENDIF.
ENDMETHOD.
METHOD zif_abapgit_object~changed_by.
SELECT SINGLE as4user FROM dd01l INTO rv_user
WHERE domname = ms_item-obj_name
AND as4local = 'A'
AND as4vers = '0000'.
IF sy-subrc <> 0.
rv_user = c_user_unknown.
ENDIF.
ENDMETHOD.
METHOD zif_abapgit_object~delete.
IF zif_abapgit_object~exists( ) = abap_false.
RETURN.
ENDIF.
delete_ddic( iv_objtype = 'D'
iv_no_ask_delete_append = abap_true ).
delete_longtexts( c_longtext_id_doma ).
ENDMETHOD.
METHOD zif_abapgit_object~deserialize.
* package SEDD
* package SDIC
* fm TR_TADIR_INTERFACE
* fm RS_CORR_INSERT ?
DATA: lv_name TYPE ddobjname,
ls_dd01v TYPE dd01v,
lt_dd07v TYPE TABLE OF dd07v.
FIELD-SYMBOLS <ls_dd07v> TYPE dd07v.
io_xml->read( EXPORTING iv_name = 'DD01V'
CHANGING cg_data = ls_dd01v ).
io_xml->read( EXPORTING iv_name = 'DD07V_TAB'
CHANGING cg_data = lt_dd07v ).
corr_insert( iv_package = iv_package
ig_object_class = 'DICT' ).
lv_name = ms_item-obj_name. " type conversion
LOOP AT lt_dd07v ASSIGNING <ls_dd07v>.
<ls_dd07v>-domname = lv_name.
<ls_dd07v>-valpos = sy-tabix.
ENDLOOP.
CALL FUNCTION 'DDIF_DOMA_PUT'
EXPORTING
name = lv_name
dd01v_wa = ls_dd01v
TABLES
dd07v_tab = lt_dd07v
EXCEPTIONS
doma_not_found = 1
name_inconsistent = 2
doma_inconsistent = 3
put_failure = 4
put_refused = 5
OTHERS = 6.
IF sy-subrc <> 0.
zcx_abapgit_exception=>raise( 'error from DDIF_DOMA_PUT' ).
ENDIF.
deserialize_texts( ii_xml = io_xml
is_dd01v = ls_dd01v
it_dd07v = lt_dd07v ).
deserialize_longtexts( io_xml ).
zcl_abapgit_objects_activation=>add_item( ms_item ).
ENDMETHOD.
METHOD zif_abapgit_object~exists.
DATA: lv_domname TYPE dd01l-domname.
SELECT SINGLE domname FROM dd01l INTO lv_domname
WHERE domname = ms_item-obj_name.
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-ddic 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-DOMA'
iv_field = 'RSRD1-DOMA_VAL' ).
ENDMETHOD.
METHOD zif_abapgit_object~serialize.
DATA: lv_name TYPE ddobjname,
ls_dd01v TYPE dd01v,
lv_masklen TYPE c LENGTH 4,
lt_dd07v TYPE TABLE OF dd07v.
lv_name = ms_item-obj_name.
CALL FUNCTION 'DDIF_DOMA_GET'
EXPORTING
name = lv_name
langu = mv_language
IMPORTING
dd01v_wa = ls_dd01v
TABLES
dd07v_tab = lt_dd07v
EXCEPTIONS
illegal_input = 1
OTHERS = 2.
IF sy-subrc <> 0 OR ls_dd01v IS INITIAL.
zcx_abapgit_exception=>raise( 'error from DDIF_DOMA_GET' ).
ENDIF.
CLEAR: ls_dd01v-as4user,
ls_dd01v-as4date,
ls_dd01v-as4time,
ls_dd01v-appexist.
* make sure XML serialization does not dump if the field contains invalid data
* note that this is a N field, so '' is not valid
IF ls_dd01v-authclass = ''.
CLEAR ls_dd01v-authclass.
ENDIF.
lv_masklen = ls_dd01v-masklen.
IF lv_masklen = '' OR NOT lv_masklen CO '0123456789'.
CLEAR ls_dd01v-masklen.
ENDIF.
DELETE lt_dd07v WHERE appval = abap_true.
SORT lt_dd07v BY
valpos ASCENDING
ddlanguage ASCENDING.
io_xml->add( iv_name = 'DD01V'
ig_data = ls_dd01v ).
io_xml->add( iv_name = 'DD07V_TAB'
ig_data = lt_dd07v ).
serialize_texts( ii_xml = io_xml
it_dd07v = lt_dd07v ).
serialize_longtexts( ii_xml = io_xml
iv_longtext_id = c_longtext_id_doma ).
ENDMETHOD.
ENDCLASS.
|
Fix serialize for missing translations (#4283)
|
DOMA: Fix serialize for missing translations (#4283)
Closes #4278
Co-authored-by: Lars Hvam <[email protected]>
|
ABAP
|
mit
|
sbcgua/abapGit,larshp/abapGit,EduardoCopat/abapGit,larshp/abapGit,sbcgua/abapGit,EduardoCopat/abapGit
|
03aff682f7cd3c9d230399f39c98a29f7e6b211e
|
src/zabapgit_file_status.prog.abap
|
src/zabapgit_file_status.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_FILE_STATUS
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_file_status DEFINITION
*----------------------------------------------------------------------*
CLASS ltcl_file_status DEFINITION DEFERRED.
CLASS ltcl_file_status2 DEFINITION DEFERRED.
CLASS lcl_file_status DEFINITION FINAL
FRIENDS ltcl_file_status ltcl_file_status2.
PUBLIC SECTION.
CLASS-METHODS status
IMPORTING io_repo TYPE REF TO lcl_repo
io_log TYPE REF TO lcl_log OPTIONAL
RETURNING VALUE(rt_results) TYPE ty_results_tt
RAISING lcx_exception.
PRIVATE SECTION.
CLASS-METHODS:
calculate_status
IMPORTING iv_devclass TYPE devclass
it_local TYPE ty_files_item_tt
it_remote TYPE ty_files_tt
it_cur_state TYPE ty_file_signatures_tt
RETURNING VALUE(rt_results) TYPE ty_results_tt,
run_checks
IMPORTING io_log TYPE REF TO lcl_log
it_results TYPE ty_results_tt
io_dot TYPE REF TO lcl_dot_abapgit
iv_top TYPE devclass
RAISING lcx_exception,
build_existing
IMPORTING is_local TYPE ty_file_item
is_remote TYPE ty_file
it_state TYPE ty_file_signatures_ts
RETURNING VALUE(rs_result) TYPE ty_result,
build_new_local
IMPORTING is_local TYPE ty_file_item
RETURNING VALUE(rs_result) TYPE ty_result,
build_new_remote
IMPORTING iv_devclass TYPE devclass
is_remote TYPE ty_file
it_items TYPE ty_items_ts
it_state TYPE ty_file_signatures_ts
RETURNING VALUE(rs_result) TYPE ty_result,
identify_object
IMPORTING iv_filename TYPE string
EXPORTING es_item TYPE ty_item
ev_is_xml TYPE abap_bool.
ENDCLASS. "lcl_file_status DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_file_status IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS lcl_file_status IMPLEMENTATION.
METHOD run_checks.
DATA: lv_path TYPE string,
ls_item TYPE ty_item,
ls_file TYPE ty_file_signature,
lt_res_sort LIKE it_results,
lt_item_idx LIKE it_results.
FIELD-SYMBOLS: <ls_res1> LIKE LINE OF it_results,
<ls_res2> LIKE LINE OF it_results.
IF io_log IS INITIAL.
RETURN.
ENDIF.
" Collect object indexe
lt_res_sort = it_results.
SORT lt_res_sort BY obj_type ASCENDING obj_name ASCENDING.
LOOP AT it_results ASSIGNING <ls_res1> WHERE NOT obj_type IS INITIAL.
IF NOT ( <ls_res1>-obj_type = ls_item-obj_type
AND <ls_res1>-obj_name = ls_item-obj_name ).
APPEND INITIAL LINE TO lt_item_idx ASSIGNING <ls_res2>.
<ls_res2>-obj_type = <ls_res1>-obj_type.
<ls_res2>-obj_name = <ls_res1>-obj_name.
<ls_res2>-path = <ls_res1>-path.
MOVE-CORRESPONDING <ls_res1> TO ls_item.
ENDIF.
ENDLOOP.
" Check files for one object is in the same folder
LOOP AT it_results ASSIGNING <ls_res1> WHERE NOT obj_type IS INITIAL.
READ TABLE lt_item_idx ASSIGNING <ls_res2>
WITH KEY obj_type = <ls_res1>-obj_type obj_name = <ls_res1>-obj_name
BINARY SEARCH. " Sorted above
IF sy-subrc <> 0 OR <ls_res1>-path <> <ls_res2>-path. " All paths are same
io_log->add( iv_msg = |Files for object { <ls_res1>-obj_type }{
<ls_res1>-obj_name }are not placed in the same folder|
iv_type = 'W'
iv_rc = '1' ) ##no_text.
ENDIF.
ENDLOOP.
" Check that objects are created in package corresponding to folder
LOOP AT it_results ASSIGNING <ls_res1>
WHERE NOT package IS INITIAL AND NOT path IS INITIAL.
lv_path = lcl_folder_logic=>package_to_path( iv_top = iv_top
io_dot = io_dot
iv_package = <ls_res1>-package ).
IF lv_path <> <ls_res1>-path.
io_log->add( iv_msg = |Package and path does not match for object, {
<ls_res1>-obj_type } { <ls_res1>-obj_name }|
iv_type = 'W'
iv_rc = '2' ) ##no_text.
ENDIF.
ENDLOOP.
" Check for multiple files with same filename
SORT lt_res_sort BY filename ASCENDING.
LOOP AT lt_res_sort ASSIGNING <ls_res1>.
IF <ls_res1>-filename IS NOT INITIAL AND <ls_res1>-filename = ls_file-filename.
io_log->add( iv_msg = |Multiple files with same filename, { <ls_res1>-filename }|
iv_type = 'W'
iv_rc = '3' ) ##no_text.
ENDIF.
IF <ls_res1>-filename IS INITIAL.
io_log->add( iv_msg = |Filename is empty for object { <ls_res1>-obj_type } { <ls_res1>-obj_name }|
iv_type = 'W'
iv_rc = '4' ) ##no_text.
ENDIF.
MOVE-CORRESPONDING <ls_res1> TO ls_file.
ENDLOOP.
ENDMETHOD. "check
METHOD status.
DATA: lv_index LIKE sy-tabix,
lo_dot_abapgit TYPE REF TO lcl_dot_abapgit.
FIELD-SYMBOLS <ls_result> LIKE LINE OF rt_results.
rt_results = calculate_status(
iv_devclass = io_repo->get_package( )
it_local = io_repo->get_files_local( io_log = io_log )
it_remote = io_repo->get_files_remote( )
it_cur_state = io_repo->get_local_checksums_per_file( ) ).
lo_dot_abapgit = io_repo->get_dot_abapgit( ).
" Remove ignored files, fix .abapgit
LOOP AT rt_results ASSIGNING <ls_result>.
lv_index = sy-tabix.
IF lo_dot_abapgit->is_ignored(
iv_path = <ls_result>-path
iv_filename = <ls_result>-filename ) = abap_true.
DELETE rt_results INDEX lv_index.
ENDIF.
ENDLOOP.
run_checks(
io_log = io_log
it_results = rt_results
io_dot = lo_dot_abapgit
iv_top = io_repo->get_package( ) ).
ENDMETHOD. "status
METHOD calculate_status.
DATA: lt_remote LIKE it_remote,
lt_items TYPE ty_items_tt,
ls_item LIKE LINE OF lt_items,
lv_is_xml TYPE abap_bool,
lt_items_idx TYPE ty_items_ts,
lt_state_idx TYPE ty_file_signatures_ts. " Sorted by path+filename
FIELD-SYMBOLS: <ls_remote> LIKE LINE OF it_remote,
<ls_result> LIKE LINE OF rt_results,
<ls_local> LIKE LINE OF it_local.
lt_state_idx = it_cur_state. " Force sort it
lt_remote = it_remote.
SORT lt_remote BY path filename.
" Process local files and new local files
LOOP AT it_local ASSIGNING <ls_local>.
APPEND INITIAL LINE TO rt_results ASSIGNING <ls_result>.
IF <ls_local>-item IS NOT INITIAL.
APPEND <ls_local>-item TO lt_items. " Collect for item index
ENDIF.
READ TABLE lt_remote ASSIGNING <ls_remote>
WITH KEY path = <ls_local>-file-path filename = <ls_local>-file-filename
BINARY SEARCH.
IF sy-subrc = 0. " Exist local and remote
<ls_result> = build_existing(
is_local = <ls_local>
is_remote = <ls_remote>
it_state = lt_state_idx ).
ASSERT <ls_remote>-sha1 IS NOT INITIAL.
CLEAR <ls_remote>-sha1. " Mark as processed
ELSE. " Only L exists
<ls_result> = build_new_local( is_local = <ls_local> ).
ENDIF.
ENDLOOP.
" Complete item index for unmarked remote files
LOOP AT lt_remote ASSIGNING <ls_remote> WHERE sha1 IS NOT INITIAL.
identify_object( EXPORTING iv_filename = <ls_remote>-filename
IMPORTING es_item = ls_item
ev_is_xml = lv_is_xml ).
CHECK lv_is_xml = abap_true. " Skip all but obj definitions
ls_item-devclass = lcl_tadir=>get_object_package(
iv_object = ls_item-obj_type
iv_obj_name = ls_item-obj_name ).
APPEND ls_item TO lt_items.
ENDLOOP.
SORT lt_items. " Default key - type, name, pkg
DELETE ADJACENT DUPLICATES FROM lt_items.
lt_items_idx = lt_items. " Self protection + UNIQUE records assertion
" Process new remote files (marked above with empty SHA1)
LOOP AT lt_remote ASSIGNING <ls_remote> WHERE sha1 IS NOT INITIAL.
APPEND INITIAL LINE TO rt_results ASSIGNING <ls_result>.
<ls_result> = build_new_remote( iv_devclass = iv_devclass
is_remote = <ls_remote>
it_items = lt_items_idx
it_state = lt_state_idx ).
ENDLOOP.
SORT rt_results BY
obj_type ASCENDING
obj_name ASCENDING
filename ASCENDING.
ENDMETHOD. "calculate_status.
METHOD identify_object.
DATA: lv_name TYPE tadir-obj_name,
lv_type TYPE string,
lv_ext TYPE string.
" Guess object type and name
SPLIT to_upper( iv_filename ) AT '.' INTO lv_name lv_type lv_ext.
" Handle namespaces
REPLACE ALL OCCURRENCES OF '#' IN lv_name WITH '/'.
REPLACE ALL OCCURRENCES OF '#' IN lv_type WITH '/'.
REPLACE ALL OCCURRENCES OF '#' IN lv_ext WITH '/'.
CLEAR es_item.
es_item-obj_type = lv_type.
es_item-obj_name = lv_name.
ev_is_xml = boolc( lv_ext = 'XML' AND strlen( lv_type ) = 4 ).
ENDMETHOD. "identify_object.
METHOD build_existing.
DATA: ls_file_sig LIKE LINE OF it_state.
" Item
rs_result-obj_type = is_local-item-obj_type.
rs_result-obj_name = is_local-item-obj_name.
rs_result-package = is_local-item-devclass.
" File
rs_result-path = is_local-file-path.
rs_result-filename = is_local-file-filename.
" Match against current state
READ TABLE it_state INTO ls_file_sig
WITH KEY path = is_local-file-path
filename = is_local-file-filename
BINARY SEARCH.
IF sy-subrc = 0.
IF ls_file_sig-sha1 <> is_local-file-sha1.
rs_result-lstate = gc_state-modified.
ENDIF.
IF ls_file_sig-sha1 <> is_remote-sha1.
rs_result-rstate = gc_state-modified.
ENDIF.
rs_result-match = boolc( rs_result-lstate IS INITIAL
AND rs_result-rstate IS INITIAL ).
ELSE.
" This is a strange situation. As both local and remote exist
" the state should also be present. Maybe this is a first run of the code.
" In this case just compare hashes directly and mark both changed
" the user will presumably decide what to do after checking the actual diff
rs_result-match = boolc( is_local-file-sha1 = is_remote-sha1 ).
IF rs_result-match = abap_false.
rs_result-lstate = gc_state-modified.
rs_result-rstate = gc_state-modified.
ENDIF.
ENDIF.
ENDMETHOD. "build_existing
METHOD build_new_local.
" Item
rs_result-obj_type = is_local-item-obj_type.
rs_result-obj_name = is_local-item-obj_name.
rs_result-package = is_local-item-devclass.
" File
rs_result-path = is_local-file-path.
rs_result-filename = is_local-file-filename.
" Match
rs_result-match = abap_false.
rs_result-lstate = gc_state-added.
ENDMETHOD. "build_new_local
METHOD build_new_remote.
DATA: ls_item LIKE LINE OF it_items,
ls_file_sig LIKE LINE OF it_state.
" Common and default part
rs_result-path = is_remote-path.
rs_result-filename = is_remote-filename.
rs_result-match = abap_false.
rs_result-rstate = gc_state-added.
identify_object( EXPORTING iv_filename = is_remote-filename
IMPORTING es_item = ls_item ).
" Check if in item index + get package
READ TABLE it_items INTO ls_item
WITH KEY obj_type = ls_item-obj_type obj_name = ls_item-obj_name
BINARY SEARCH.
IF sy-subrc = 0.
" Completely new (xml, abap) and new file in an existing object
rs_result-obj_type = ls_item-obj_type.
rs_result-obj_name = ls_item-obj_name.
rs_result-package = ls_item-devclass.
READ TABLE it_state INTO ls_file_sig
WITH KEY path = is_remote-path filename = is_remote-filename
BINARY SEARCH.
" Existing file but from another package
" was not added during local file proc as was not in tadir for repo package
IF sy-subrc = 0.
IF ls_file_sig-sha1 = is_remote-sha1.
rs_result-match = abap_true.
CLEAR rs_result-rstate.
ELSE.
rs_result-rstate = gc_state-modified.
ENDIF.
" Item is in state and in cache but with no package - it was deleted
" OR devclass is the same as repo package (see #532)
IF ls_item-devclass IS INITIAL OR ls_item-devclass = iv_devclass.
rs_result-match = abap_false.
rs_result-lstate = gc_state-deleted.
ENDIF.
ENDIF.
ELSE. " Completely unknown file, probably non-abapgit
ASSERT 1 = 1. " No action, just follow defaults
ENDIF.
ENDMETHOD. "build_new_remote
ENDCLASS. "lcl_file_status IMPLEMENTATION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_FILE_STATUS
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_file_status DEFINITION
*----------------------------------------------------------------------*
CLASS ltcl_file_status DEFINITION DEFERRED.
CLASS ltcl_file_status2 DEFINITION DEFERRED.
CLASS lcl_file_status DEFINITION FINAL
FRIENDS ltcl_file_status ltcl_file_status2.
PUBLIC SECTION.
CLASS-METHODS status
IMPORTING io_repo TYPE REF TO lcl_repo
io_log TYPE REF TO lcl_log OPTIONAL
RETURNING VALUE(rt_results) TYPE ty_results_tt
RAISING lcx_exception.
PRIVATE SECTION.
CLASS-METHODS:
calculate_status
IMPORTING iv_devclass TYPE devclass
it_local TYPE ty_files_item_tt
it_remote TYPE ty_files_tt
it_cur_state TYPE ty_file_signatures_tt
RETURNING VALUE(rt_results) TYPE ty_results_tt,
run_checks
IMPORTING io_log TYPE REF TO lcl_log
it_results TYPE ty_results_tt
io_dot TYPE REF TO lcl_dot_abapgit
iv_top TYPE devclass
RAISING lcx_exception,
build_existing
IMPORTING is_local TYPE ty_file_item
is_remote TYPE ty_file
it_state TYPE ty_file_signatures_ts
RETURNING VALUE(rs_result) TYPE ty_result,
build_new_local
IMPORTING is_local TYPE ty_file_item
RETURNING VALUE(rs_result) TYPE ty_result,
build_new_remote
IMPORTING iv_devclass TYPE devclass
is_remote TYPE ty_file
it_items TYPE ty_items_ts
it_state TYPE ty_file_signatures_ts
RETURNING VALUE(rs_result) TYPE ty_result,
identify_object
IMPORTING iv_filename TYPE string
EXPORTING es_item TYPE ty_item
ev_is_xml TYPE abap_bool.
ENDCLASS. "lcl_file_status DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_file_status IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS lcl_file_status IMPLEMENTATION.
METHOD run_checks.
DATA: lv_path TYPE string,
ls_item TYPE ty_item,
ls_file TYPE ty_file_signature,
lt_res_sort LIKE it_results,
lt_item_idx LIKE it_results.
FIELD-SYMBOLS: <ls_res1> LIKE LINE OF it_results,
<ls_res2> LIKE LINE OF it_results.
IF io_log IS INITIAL.
RETURN.
ENDIF.
" Collect object indexe
lt_res_sort = it_results.
SORT lt_res_sort BY obj_type ASCENDING obj_name ASCENDING.
LOOP AT it_results ASSIGNING <ls_res1> WHERE NOT obj_type IS INITIAL.
IF NOT ( <ls_res1>-obj_type = ls_item-obj_type
AND <ls_res1>-obj_name = ls_item-obj_name ).
APPEND INITIAL LINE TO lt_item_idx ASSIGNING <ls_res2>.
<ls_res2>-obj_type = <ls_res1>-obj_type.
<ls_res2>-obj_name = <ls_res1>-obj_name.
<ls_res2>-path = <ls_res1>-path.
MOVE-CORRESPONDING <ls_res1> TO ls_item.
ENDIF.
ENDLOOP.
" Check files for one object is in the same folder
LOOP AT it_results ASSIGNING <ls_res1> WHERE NOT obj_type IS INITIAL.
READ TABLE lt_item_idx ASSIGNING <ls_res2>
WITH KEY obj_type = <ls_res1>-obj_type obj_name = <ls_res1>-obj_name
BINARY SEARCH. " Sorted above
IF sy-subrc <> 0 OR <ls_res1>-path <> <ls_res2>-path. " All paths are same
io_log->add( iv_msg = |Files for object { <ls_res1>-obj_type } {
<ls_res1>-obj_name } are not placed in the same folder|
iv_type = 'W'
iv_rc = '1' ) ##no_text.
ENDIF.
ENDLOOP.
" Check that objects are created in package corresponding to folder
LOOP AT it_results ASSIGNING <ls_res1>
WHERE NOT package IS INITIAL AND NOT path IS INITIAL.
lv_path = lcl_folder_logic=>package_to_path( iv_top = iv_top
io_dot = io_dot
iv_package = <ls_res1>-package ).
IF lv_path <> <ls_res1>-path.
io_log->add( iv_msg = |Package and path does not match for object, {
<ls_res1>-obj_type } { <ls_res1>-obj_name }|
iv_type = 'W'
iv_rc = '2' ) ##no_text.
ENDIF.
ENDLOOP.
" Check for multiple files with same filename
SORT lt_res_sort BY filename ASCENDING.
LOOP AT lt_res_sort ASSIGNING <ls_res1>.
IF <ls_res1>-filename IS NOT INITIAL AND <ls_res1>-filename = ls_file-filename.
io_log->add( iv_msg = |Multiple files with same filename, { <ls_res1>-filename }|
iv_type = 'W'
iv_rc = '3' ) ##no_text.
ENDIF.
IF <ls_res1>-filename IS INITIAL.
io_log->add( iv_msg = |Filename is empty for object { <ls_res1>-obj_type } { <ls_res1>-obj_name }|
iv_type = 'W'
iv_rc = '4' ) ##no_text.
ENDIF.
MOVE-CORRESPONDING <ls_res1> TO ls_file.
ENDLOOP.
ENDMETHOD. "check
METHOD status.
DATA: lv_index LIKE sy-tabix,
lo_dot_abapgit TYPE REF TO lcl_dot_abapgit.
FIELD-SYMBOLS <ls_result> LIKE LINE OF rt_results.
rt_results = calculate_status(
iv_devclass = io_repo->get_package( )
it_local = io_repo->get_files_local( io_log = io_log )
it_remote = io_repo->get_files_remote( )
it_cur_state = io_repo->get_local_checksums_per_file( ) ).
lo_dot_abapgit = io_repo->get_dot_abapgit( ).
" Remove ignored files, fix .abapgit
LOOP AT rt_results ASSIGNING <ls_result>.
lv_index = sy-tabix.
IF lo_dot_abapgit->is_ignored(
iv_path = <ls_result>-path
iv_filename = <ls_result>-filename ) = abap_true.
DELETE rt_results INDEX lv_index.
ENDIF.
ENDLOOP.
run_checks(
io_log = io_log
it_results = rt_results
io_dot = lo_dot_abapgit
iv_top = io_repo->get_package( ) ).
ENDMETHOD. "status
METHOD calculate_status.
DATA: lt_remote LIKE it_remote,
lt_items TYPE ty_items_tt,
ls_item LIKE LINE OF lt_items,
lv_is_xml TYPE abap_bool,
lt_items_idx TYPE ty_items_ts,
lt_state_idx TYPE ty_file_signatures_ts. " Sorted by path+filename
FIELD-SYMBOLS: <ls_remote> LIKE LINE OF it_remote,
<ls_result> LIKE LINE OF rt_results,
<ls_local> LIKE LINE OF it_local.
lt_state_idx = it_cur_state. " Force sort it
lt_remote = it_remote.
SORT lt_remote BY path filename.
" Process local files and new local files
LOOP AT it_local ASSIGNING <ls_local>.
APPEND INITIAL LINE TO rt_results ASSIGNING <ls_result>.
IF <ls_local>-item IS NOT INITIAL.
APPEND <ls_local>-item TO lt_items. " Collect for item index
ENDIF.
READ TABLE lt_remote ASSIGNING <ls_remote>
WITH KEY path = <ls_local>-file-path filename = <ls_local>-file-filename
BINARY SEARCH.
IF sy-subrc = 0. " Exist local and remote
<ls_result> = build_existing(
is_local = <ls_local>
is_remote = <ls_remote>
it_state = lt_state_idx ).
ASSERT <ls_remote>-sha1 IS NOT INITIAL.
CLEAR <ls_remote>-sha1. " Mark as processed
ELSE. " Only L exists
<ls_result> = build_new_local( is_local = <ls_local> ).
ENDIF.
ENDLOOP.
" Complete item index for unmarked remote files
LOOP AT lt_remote ASSIGNING <ls_remote> WHERE sha1 IS NOT INITIAL.
identify_object( EXPORTING iv_filename = <ls_remote>-filename
IMPORTING es_item = ls_item
ev_is_xml = lv_is_xml ).
CHECK lv_is_xml = abap_true. " Skip all but obj definitions
ls_item-devclass = lcl_tadir=>get_object_package(
iv_object = ls_item-obj_type
iv_obj_name = ls_item-obj_name ).
APPEND ls_item TO lt_items.
ENDLOOP.
SORT lt_items. " Default key - type, name, pkg
DELETE ADJACENT DUPLICATES FROM lt_items.
lt_items_idx = lt_items. " Self protection + UNIQUE records assertion
" Process new remote files (marked above with empty SHA1)
LOOP AT lt_remote ASSIGNING <ls_remote> WHERE sha1 IS NOT INITIAL.
APPEND INITIAL LINE TO rt_results ASSIGNING <ls_result>.
<ls_result> = build_new_remote( iv_devclass = iv_devclass
is_remote = <ls_remote>
it_items = lt_items_idx
it_state = lt_state_idx ).
ENDLOOP.
SORT rt_results BY
obj_type ASCENDING
obj_name ASCENDING
filename ASCENDING.
ENDMETHOD. "calculate_status.
METHOD identify_object.
DATA: lv_name TYPE tadir-obj_name,
lv_type TYPE string,
lv_ext TYPE string.
" Guess object type and name
SPLIT to_upper( iv_filename ) AT '.' INTO lv_name lv_type lv_ext.
" Handle namespaces
REPLACE ALL OCCURRENCES OF '#' IN lv_name WITH '/'.
REPLACE ALL OCCURRENCES OF '#' IN lv_type WITH '/'.
REPLACE ALL OCCURRENCES OF '#' IN lv_ext WITH '/'.
CLEAR es_item.
es_item-obj_type = lv_type.
es_item-obj_name = lv_name.
ev_is_xml = boolc( lv_ext = 'XML' AND strlen( lv_type ) = 4 ).
ENDMETHOD. "identify_object.
METHOD build_existing.
DATA: ls_file_sig LIKE LINE OF it_state.
" Item
rs_result-obj_type = is_local-item-obj_type.
rs_result-obj_name = is_local-item-obj_name.
rs_result-package = is_local-item-devclass.
" File
rs_result-path = is_local-file-path.
rs_result-filename = is_local-file-filename.
" Match against current state
READ TABLE it_state INTO ls_file_sig
WITH KEY path = is_local-file-path
filename = is_local-file-filename
BINARY SEARCH.
IF sy-subrc = 0.
IF ls_file_sig-sha1 <> is_local-file-sha1.
rs_result-lstate = gc_state-modified.
ENDIF.
IF ls_file_sig-sha1 <> is_remote-sha1.
rs_result-rstate = gc_state-modified.
ENDIF.
rs_result-match = boolc( rs_result-lstate IS INITIAL
AND rs_result-rstate IS INITIAL ).
ELSE.
" This is a strange situation. As both local and remote exist
" the state should also be present. Maybe this is a first run of the code.
" In this case just compare hashes directly and mark both changed
" the user will presumably decide what to do after checking the actual diff
rs_result-match = boolc( is_local-file-sha1 = is_remote-sha1 ).
IF rs_result-match = abap_false.
rs_result-lstate = gc_state-modified.
rs_result-rstate = gc_state-modified.
ENDIF.
ENDIF.
ENDMETHOD. "build_existing
METHOD build_new_local.
" Item
rs_result-obj_type = is_local-item-obj_type.
rs_result-obj_name = is_local-item-obj_name.
rs_result-package = is_local-item-devclass.
" File
rs_result-path = is_local-file-path.
rs_result-filename = is_local-file-filename.
" Match
rs_result-match = abap_false.
rs_result-lstate = gc_state-added.
ENDMETHOD. "build_new_local
METHOD build_new_remote.
DATA: ls_item LIKE LINE OF it_items,
ls_file_sig LIKE LINE OF it_state.
" Common and default part
rs_result-path = is_remote-path.
rs_result-filename = is_remote-filename.
rs_result-match = abap_false.
rs_result-rstate = gc_state-added.
identify_object( EXPORTING iv_filename = is_remote-filename
IMPORTING es_item = ls_item ).
" Check if in item index + get package
READ TABLE it_items INTO ls_item
WITH KEY obj_type = ls_item-obj_type obj_name = ls_item-obj_name
BINARY SEARCH.
IF sy-subrc = 0.
" Completely new (xml, abap) and new file in an existing object
rs_result-obj_type = ls_item-obj_type.
rs_result-obj_name = ls_item-obj_name.
rs_result-package = ls_item-devclass.
READ TABLE it_state INTO ls_file_sig
WITH KEY path = is_remote-path filename = is_remote-filename
BINARY SEARCH.
" Existing file but from another package
" was not added during local file proc as was not in tadir for repo package
IF sy-subrc = 0.
IF ls_file_sig-sha1 = is_remote-sha1.
rs_result-match = abap_true.
CLEAR rs_result-rstate.
ELSE.
rs_result-rstate = gc_state-modified.
ENDIF.
" Item is in state and in cache but with no package - it was deleted
" OR devclass is the same as repo package (see #532)
IF ls_item-devclass IS INITIAL OR ls_item-devclass = iv_devclass.
rs_result-match = abap_false.
rs_result-lstate = gc_state-deleted.
ENDIF.
ENDIF.
ELSE. " Completely unknown file, probably non-abapgit
ASSERT 1 = 1. " No action, just follow defaults
ENDIF.
ENDMETHOD. "build_new_remote
ENDCLASS. "lcl_file_status IMPLEMENTATION
|
fix spaces in error message
|
fix spaces in error message
|
ABAP
|
mit
|
sbcgua/abapGit,sbcgua/abapGit,EduardoCopat/abapGit,larshp/abapGit,apex8/abapGit,EduardoCopat/abapGit,apex8/abapGit,larshp/abapGit
|
30c6b9dbfafe92123aefc83eb25911fa99912ab2
|
src/zabapgit_object_prag.prog.abap
|
src/zabapgit_object_prag.prog.abap
|
*&---------------------------------------------------------------------*
*& Include zabapgit_object_prag
*&---------------------------------------------------------------------*
CLASS lcl_object_prag DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
PRIVATE SECTION.
TYPES: BEGIN OF ty_pragma,
pragma TYPE c LENGTH 40,
extension TYPE c LENGTH 1,
signature TYPE c LENGTH 10,
description TYPE c LENGTH 255,
END OF ty_pragma.
METHODS:
_raise_pragma_not_exists
RAISING
lcx_exception,
_raise_pragma_exists
RAISING
lcx_exception,
_raise_pragma_enqueue
RAISING
lcx_exception.
ENDCLASS.
CLASS lcl_object_prag IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD.
METHOD lif_object~changed_by.
rv_user = sy-uname.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
rs_metadata-delete_tadir = abap_true.
ENDMETHOD.
METHOD lif_object~exists.
TRY.
cl_abap_pragma=>get_ref( ms_item-obj_name ).
CATCH cx_abap_pragma_not_exists.
rv_bool = abap_false.
RETURN.
ENDTRY.
rv_bool = abap_true.
ENDMETHOD.
METHOD lif_object~serialize.
DATA: lo_pragma TYPE REF TO cl_abap_pragma,
pragma TYPE lcl_object_prag=>ty_pragma.
TRY.
lo_pragma = cl_abap_pragma=>get_ref( ms_item-obj_name ).
pragma-pragma = lo_pragma->pragma.
pragma-extension = lo_pragma->extension.
pragma-signature = lo_pragma->signature.
pragma-description = lo_pragma->description.
io_xml->add( iv_name = 'PRAG'
ig_data = pragma ).
CATCH cx_abap_pragma_not_exists.
_raise_pragma_not_exists( ).
ENDTRY.
ENDMETHOD.
METHOD lif_object~deserialize.
DATA: pragma TYPE ty_pragma,
lo_pragma TYPE REF TO cl_abap_pragma.
TRY.
io_xml->read(
EXPORTING
iv_name = 'PRAG'
CHANGING
cg_data = pragma ).
lo_pragma = cl_abap_pragma=>create( p_pragma = ms_item-obj_name
p_package = iv_package ).
lo_pragma->set_info( p_description = pragma-description
p_signature = pragma-signature
p_extension = pragma-extension ).
lo_pragma->save( ).
CATCH cx_abap_pragma_not_exists.
_raise_pragma_not_exists( ).
CATCH cx_abap_pragma_exists.
_raise_pragma_exists( ).
CATCH cx_abap_pragma_enqueue.
_raise_pragma_enqueue( ).
ENDTRY.
ENDMETHOD.
METHOD lif_object~delete.
DATA: lo_pragma TYPE REF TO cl_abap_pragma.
TRY.
lo_pragma = cl_abap_pragma=>get_ref( ms_item-obj_name ).
lo_pragma->delete( ).
CATCH cx_abap_pragma_not_exists.
_raise_pragma_not_exists( ).
CATCH cx_abap_pragma_enqueue.
_raise_pragma_enqueue( ).
ENDTRY.
ENDMETHOD.
METHOD lif_object~jump.
CALL FUNCTION 'RS_TOOL_ACCESS'
EXPORTING
operation = 'SHOW'
object_name = ms_item-obj_name
object_type = ms_item-obj_type
EXCEPTIONS
not_executed = 1
invalid_object_type = 2
OTHERS = 3.
ENDMETHOD.
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_comparison_null.
ENDMETHOD.
METHOD _raise_pragma_enqueue.
lcx_exception=>raise( |Pragma { ms_item-obj_name } enqueue error| ).
ENDMETHOD.
METHOD _raise_pragma_exists.
lcx_exception=>raise( |Pragma { ms_item-obj_name } exists| ).
ENDMETHOD.
METHOD _raise_pragma_not_exists.
lcx_exception=>raise( |Pragma { ms_item-obj_name } doesn't exist| ).
ENDMETHOD.
ENDCLASS.
|
*&---------------------------------------------------------------------*
*& Include zabapgit_object_prag
*&---------------------------------------------------------------------*
CLASS lcl_object_prag DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
PRIVATE SECTION.
TYPES: BEGIN OF ty_pragma,
pragma TYPE c LENGTH 40,
extension TYPE c LENGTH 1,
signature TYPE c LENGTH 10,
description TYPE c LENGTH 255,
END OF ty_pragma.
METHODS:
_raise_pragma_not_exists
RAISING
lcx_exception,
_raise_pragma_exists
RAISING
lcx_exception,
_raise_pragma_enqueue
RAISING
lcx_exception.
ENDCLASS.
CLASS lcl_object_prag IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD.
METHOD lif_object~changed_by.
rv_user = c_user_unknown.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
rs_metadata-delete_tadir = abap_true.
ENDMETHOD.
METHOD lif_object~exists.
TRY.
cl_abap_pragma=>get_ref( ms_item-obj_name ).
CATCH cx_abap_pragma_not_exists.
rv_bool = abap_false.
RETURN.
ENDTRY.
rv_bool = abap_true.
ENDMETHOD.
METHOD lif_object~serialize.
DATA: lo_pragma TYPE REF TO cl_abap_pragma,
pragma TYPE lcl_object_prag=>ty_pragma.
TRY.
lo_pragma = cl_abap_pragma=>get_ref( ms_item-obj_name ).
pragma-pragma = lo_pragma->pragma.
pragma-extension = lo_pragma->extension.
pragma-signature = lo_pragma->signature.
pragma-description = lo_pragma->description.
io_xml->add( iv_name = 'PRAG'
ig_data = pragma ).
CATCH cx_abap_pragma_not_exists.
_raise_pragma_not_exists( ).
ENDTRY.
ENDMETHOD.
METHOD lif_object~deserialize.
DATA: pragma TYPE ty_pragma,
lo_pragma TYPE REF TO cl_abap_pragma.
TRY.
io_xml->read(
EXPORTING
iv_name = 'PRAG'
CHANGING
cg_data = pragma ).
lo_pragma = cl_abap_pragma=>create( p_pragma = ms_item-obj_name
p_package = iv_package ).
lo_pragma->set_info( p_description = pragma-description
p_signature = pragma-signature
p_extension = pragma-extension ).
lo_pragma->save( ).
CATCH cx_abap_pragma_not_exists.
_raise_pragma_not_exists( ).
CATCH cx_abap_pragma_exists.
_raise_pragma_exists( ).
CATCH cx_abap_pragma_enqueue.
_raise_pragma_enqueue( ).
ENDTRY.
ENDMETHOD.
METHOD lif_object~delete.
DATA: lo_pragma TYPE REF TO cl_abap_pragma.
TRY.
lo_pragma = cl_abap_pragma=>get_ref( ms_item-obj_name ).
lo_pragma->delete( ).
CATCH cx_abap_pragma_not_exists.
_raise_pragma_not_exists( ).
CATCH cx_abap_pragma_enqueue.
_raise_pragma_enqueue( ).
ENDTRY.
ENDMETHOD.
METHOD lif_object~jump.
CALL FUNCTION 'RS_TOOL_ACCESS'
EXPORTING
operation = 'SHOW'
object_name = ms_item-obj_name
object_type = ms_item-obj_type
EXCEPTIONS
not_executed = 1
invalid_object_type = 2
OTHERS = 3.
ENDMETHOD.
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_comparison_null.
ENDMETHOD.
METHOD _raise_pragma_enqueue.
lcx_exception=>raise( |Pragma { ms_item-obj_name } enqueue error| ).
ENDMETHOD.
METHOD _raise_pragma_exists.
lcx_exception=>raise( |Pragma { ms_item-obj_name } exists| ).
ENDMETHOD.
METHOD _raise_pragma_not_exists.
lcx_exception=>raise( |Pragma { ms_item-obj_name } doesn't exist| ).
ENDMETHOD.
ENDCLASS.
|
change 'changed_by' to user_unknown
|
change 'changed_by' to user_unknown
|
ABAP
|
mit
|
EduardoCopat/abapGit,sbcgua/abapGit,larshp/abapGit,EduardoCopat/abapGit,apex8/abapGit,larshp/abapGit,apex8/abapGit,sbcgua/abapGit
|
68c51626a3d33e88c8f38a240791a9fbad68aca2
|
src/zabapgit_html_action_utils.prog.abap
|
src/zabapgit_html_action_utils.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_HTML_ACTION_UTILS
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_html_action_utils DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_html_action_utils DEFINITION FINAL.
PUBLIC SECTION.
CLASS-METHODS field_keys_to_upper
CHANGING ct_fields TYPE tihttpnvp.
CLASS-METHODS add_field
IMPORTING name TYPE string
iv TYPE any
CHANGING ct TYPE tihttpnvp.
CLASS-METHODS get_field
IMPORTING name TYPE string
it TYPE tihttpnvp
CHANGING cv TYPE any.
CLASS-METHODS jump_encode
IMPORTING iv_obj_type TYPE tadir-object
iv_obj_name TYPE tadir-obj_name
RETURNING VALUE(rv_string) TYPE string.
CLASS-METHODS jump_decode
IMPORTING iv_string TYPE clike
EXPORTING ev_obj_type TYPE tadir-object
ev_obj_name TYPE tadir-obj_name
RAISING lcx_exception.
CLASS-METHODS dir_encode
IMPORTING iv_path TYPE string
RETURNING VALUE(rv_string) TYPE string.
CLASS-METHODS dir_decode
IMPORTING iv_string TYPE clike
RETURNING VALUE(rv_path) TYPE string
RAISING lcx_exception.
CLASS-METHODS file_encode
IMPORTING iv_key TYPE lcl_persistence_repo=>ty_repo-key
ig_file TYPE any "assuming ty_file
RETURNING VALUE(rv_string) TYPE string.
CLASS-METHODS obj_encode
IMPORTING iv_key TYPE lcl_persistence_repo=>ty_repo-key
ig_object TYPE any "assuming ty_item
RETURNING VALUE(rv_string) TYPE string.
CLASS-METHODS file_obj_decode
IMPORTING iv_string TYPE clike
EXPORTING ev_key TYPE lcl_persistence_repo=>ty_repo-key
eg_file TYPE any "assuming ty_file
eg_object TYPE any "assuming ty_item
RAISING lcx_exception.
CLASS-METHODS dbkey_encode
IMPORTING is_key TYPE lcl_persistence_db=>ty_content
RETURNING VALUE(rv_string) TYPE string.
CLASS-METHODS dbkey_decode
IMPORTING iv_string TYPE clike
RETURNING VALUE(rs_key) TYPE lcl_persistence_db=>ty_content.
CLASS-METHODS dbcontent_decode
IMPORTING it_postdata TYPE cnht_post_data_tab
RETURNING VALUE(rs_content) TYPE lcl_persistence_db=>ty_content.
CLASS-METHODS parse_commit_request
IMPORTING it_postdata TYPE cnht_post_data_tab
EXPORTING es_fields TYPE any.
CLASS-METHODS decode_bg_update
IMPORTING iv_getdata TYPE clike
RETURNING VALUE(rs_fields) TYPE lcl_persistence_background=>ty_background.
ENDCLASS. "lcl_html_action_utils DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_html_action_utils IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS lcl_html_action_utils IMPLEMENTATION.
METHOD field_keys_to_upper.
FIELD-SYMBOLS <field> LIKE LINE OF ct_fields.
LOOP AT ct_fields ASSIGNING <field>.
<field>-name = to_upper( <field>-name ).
ENDLOOP.
ENDMETHOD. "field_keys_to_upper
METHOD add_field.
DATA ls_field LIKE LINE OF ct.
FIELD-SYMBOLS <src> TYPE any.
ls_field-name = name.
CASE cl_abap_typedescr=>describe_by_data( iv )->kind.
WHEN cl_abap_typedescr=>kind_elem.
ls_field-value = iv.
WHEN cl_abap_typedescr=>kind_struct.
ASSIGN COMPONENT name OF STRUCTURE iv TO <src>.
ASSERT <src> IS ASSIGNED.
ls_field-value = <src>.
WHEN OTHERS.
ASSERT 0 = 1.
ENDCASE.
APPEND ls_field TO ct.
ENDMETHOD. "add_field
METHOD get_field.
FIELD-SYMBOLS: <ls_field> LIKE LINE OF it,
<dest> TYPE any.
READ TABLE it ASSIGNING <ls_field> WITH KEY name = name.
IF sy-subrc IS NOT INITIAL.
RETURN.
ENDIF.
CASE cl_abap_typedescr=>describe_by_data( cv )->kind.
WHEN cl_abap_typedescr=>kind_elem.
cv = <ls_field>-value.
WHEN cl_abap_typedescr=>kind_struct.
ASSIGN COMPONENT name OF STRUCTURE cv TO <dest>.
ASSERT <dest> IS ASSIGNED.
<dest> = <ls_field>-value.
WHEN OTHERS.
ASSERT 0 = 1.
ENDCASE.
ENDMETHOD. "get_field
METHOD jump_encode.
DATA: lt_fields TYPE tihttpnvp.
add_field( EXPORTING name = 'TYPE' iv = iv_obj_type CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'NAME' iv = iv_obj_name CHANGING ct = lt_fields ).
rv_string = cl_http_utility=>if_http_utility~fields_to_string( lt_fields ).
ENDMETHOD. "jump_encode
METHOD jump_decode.
DATA: lt_fields TYPE tihttpnvp.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( |{ iv_string }| ).
get_field( EXPORTING name = 'TYPE' it = lt_fields CHANGING cv = ev_obj_type ).
get_field( EXPORTING name = 'NAME' it = lt_fields CHANGING cv = ev_obj_name ).
ENDMETHOD. "jump_decode
METHOD dir_encode.
DATA: lt_fields TYPE tihttpnvp.
add_field( EXPORTING name = 'PATH' iv = iv_path CHANGING ct = lt_fields ).
rv_string = cl_http_utility=>if_http_utility~fields_to_string( lt_fields ).
ENDMETHOD. "dir_encode
METHOD dir_decode.
DATA: lt_fields TYPE tihttpnvp.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( |{ iv_string }| ).
get_field( EXPORTING name = 'PATH' it = lt_fields CHANGING cv = rv_path ).
ENDMETHOD. "dir_decode
METHOD file_encode.
DATA: lt_fields TYPE tihttpnvp.
add_field( EXPORTING name = 'KEY' iv = iv_key CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'PATH' iv = ig_file CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'FILENAME' iv = ig_file CHANGING ct = lt_fields ).
rv_string = cl_http_utility=>if_http_utility~fields_to_string( lt_fields ).
ENDMETHOD. "file_encode
METHOD obj_encode.
DATA: lt_fields TYPE tihttpnvp.
add_field( EXPORTING name = 'KEY' iv = iv_key CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'OBJ_TYPE' iv = ig_object CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'OBJ_NAME' iv = ig_object CHANGING ct = lt_fields ).
rv_string = cl_http_utility=>if_http_utility~fields_to_string( lt_fields ).
ENDMETHOD. "obj_encode
METHOD file_obj_decode.
DATA: lt_fields TYPE tihttpnvp.
ASSERT eg_file IS SUPPLIED OR eg_object IS SUPPLIED.
CLEAR: ev_key, eg_file, eg_object.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( |{ iv_string }| ).
field_keys_to_upper( CHANGING ct_fields = lt_fields ).
get_field( EXPORTING name = 'KEY' it = lt_fields CHANGING cv = ev_key ).
IF eg_file IS SUPPLIED.
get_field( EXPORTING name = 'PATH' it = lt_fields CHANGING cv = eg_file ).
get_field( EXPORTING name = 'FILENAME' it = lt_fields CHANGING cv = eg_file ).
ENDIF.
IF eg_object IS SUPPLIED.
get_field( EXPORTING name = 'OBJ_TYPE' it = lt_fields CHANGING cv = eg_object ).
get_field( EXPORTING name = 'OBJ_NAME' it = lt_fields CHANGING cv = eg_object ).
ENDIF.
ENDMETHOD. "file_decode
METHOD dbkey_encode.
DATA: lt_fields TYPE tihttpnvp.
add_field( EXPORTING name = 'TYPE' iv = is_key-type CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'VALUE' iv = is_key-value CHANGING ct = lt_fields ).
rv_string = cl_http_utility=>if_http_utility~fields_to_string( lt_fields ).
ENDMETHOD. "dbkey_encode
METHOD dbkey_decode.
DATA: lt_fields TYPE tihttpnvp.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( |{ iv_string }| ).
field_keys_to_upper( CHANGING ct_fields = lt_fields ).
get_field( EXPORTING name = 'TYPE' it = lt_fields CHANGING cv = rs_key-type ).
get_field( EXPORTING name = 'VALUE' it = lt_fields CHANGING cv = rs_key-value ).
ENDMETHOD. "dbkey_decode
METHOD dbcontent_decode.
DATA: lt_fields TYPE tihttpnvp,
lv_string TYPE string.
CONCATENATE LINES OF it_postdata INTO lv_string.
rs_content = dbkey_decode( lv_string ).
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( lv_string ).
field_keys_to_upper( CHANGING ct_fields = lt_fields ).
get_field( EXPORTING name = 'XMLDATA' it = lt_fields CHANGING cv = rs_content-data_str ).
IF rs_content-data_str(1) <> '<' AND rs_content-data_str+1(1) = '<'. " Hmmm ???
rs_content-data_str = rs_content-data_str+1.
ELSE.
CLEAR rs_content-data_str.
ENDIF.
ENDMETHOD. "dbcontent_decode
METHOD parse_commit_request.
CONSTANTS: lc_replace TYPE string VALUE '<<new>>'.
DATA: lv_string TYPE string,
lt_fields TYPE tihttpnvp.
FIELD-SYMBOLS <body> TYPE string.
CLEAR es_fields.
CONCATENATE LINES OF it_postdata INTO lv_string.
REPLACE ALL OCCURRENCES OF gc_newline IN lv_string WITH lc_replace.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( lv_string ).
field_keys_to_upper( CHANGING ct_fields = lt_fields ).
get_field( EXPORTING name = 'REPO_KEY' it = lt_fields CHANGING cv = es_fields ).
get_field( EXPORTING name = 'USERNAME' it = lt_fields CHANGING cv = es_fields ).
get_field( EXPORTING name = 'EMAIL' it = lt_fields CHANGING cv = es_fields ).
get_field( EXPORTING name = 'COMMENT' it = lt_fields CHANGING cv = es_fields ).
get_field( EXPORTING name = 'BODY' it = lt_fields CHANGING cv = es_fields ).
ASSIGN COMPONENT 'BODY' OF STRUCTURE es_fields TO <body>.
ASSERT <body> IS ASSIGNED.
REPLACE ALL OCCURRENCES OF lc_replace IN <body> WITH gc_newline.
ASSERT es_fields IS NOT INITIAL.
ENDMETHOD. "parse_commit_request
METHOD decode_bg_update.
DATA: lt_fields TYPE tihttpnvp.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( |{ iv_getdata }| ).
field_keys_to_upper( CHANGING ct_fields = lt_fields ).
get_field( EXPORTING name = 'METHOD' it = lt_fields CHANGING cv = rs_fields ).
get_field( EXPORTING name = 'USERNAME' it = lt_fields CHANGING cv = rs_fields ).
get_field( EXPORTING name = 'PASSWORD' it = lt_fields CHANGING cv = rs_fields ).
get_field( EXPORTING name = 'AMETHOD' it = lt_fields CHANGING cv = rs_fields ).
get_field( EXPORTING name = 'ANAME' it = lt_fields CHANGING cv = rs_fields ).
get_field( EXPORTING name = 'AMAIL' it = lt_fields CHANGING cv = rs_fields ).
ASSERT NOT rs_fields IS INITIAL.
ENDMETHOD. "decode_bg_update
ENDCLASS. "lcl_html_action_utils IMPLEMENTATION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_HTML_ACTION_UTILS
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_html_action_utils DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_html_action_utils DEFINITION FINAL.
PUBLIC SECTION.
CLASS-METHODS field_keys_to_upper
CHANGING ct_fields TYPE tihttpnvp.
CLASS-METHODS add_field
IMPORTING name TYPE string
iv TYPE any
CHANGING ct TYPE tihttpnvp.
CLASS-METHODS get_field
IMPORTING name TYPE string
it TYPE tihttpnvp
CHANGING cv TYPE any.
CLASS-METHODS jump_encode
IMPORTING iv_obj_type TYPE tadir-object
iv_obj_name TYPE tadir-obj_name
RETURNING VALUE(rv_string) TYPE string.
CLASS-METHODS jump_decode
IMPORTING iv_string TYPE clike
EXPORTING ev_obj_type TYPE tadir-object
ev_obj_name TYPE tadir-obj_name
RAISING lcx_exception.
CLASS-METHODS dir_encode
IMPORTING iv_path TYPE string
RETURNING VALUE(rv_string) TYPE string.
CLASS-METHODS dir_decode
IMPORTING iv_string TYPE clike
RETURNING VALUE(rv_path) TYPE string
RAISING lcx_exception.
CLASS-METHODS file_encode
IMPORTING iv_key TYPE lcl_persistence_repo=>ty_repo-key
ig_file TYPE any "assuming ty_file
RETURNING VALUE(rv_string) TYPE string.
CLASS-METHODS obj_encode
IMPORTING iv_key TYPE lcl_persistence_repo=>ty_repo-key
ig_object TYPE any "assuming ty_item
RETURNING VALUE(rv_string) TYPE string.
CLASS-METHODS file_obj_decode
IMPORTING iv_string TYPE clike
EXPORTING ev_key TYPE lcl_persistence_repo=>ty_repo-key
eg_file TYPE any "assuming ty_file
eg_object TYPE any "assuming ty_item
RAISING lcx_exception.
CLASS-METHODS dbkey_encode
IMPORTING is_key TYPE lcl_persistence_db=>ty_content
RETURNING VALUE(rv_string) TYPE string.
CLASS-METHODS dbkey_decode
IMPORTING iv_string TYPE clike
RETURNING VALUE(rs_key) TYPE lcl_persistence_db=>ty_content.
CLASS-METHODS dbcontent_decode
IMPORTING it_postdata TYPE cnht_post_data_tab
RETURNING VALUE(rs_content) TYPE lcl_persistence_db=>ty_content.
CLASS-METHODS parse_commit_request
IMPORTING it_postdata TYPE cnht_post_data_tab
EXPORTING es_fields TYPE any.
CLASS-METHODS decode_bg_update
IMPORTING iv_getdata TYPE clike
RETURNING VALUE(rs_fields) TYPE lcl_persistence_background=>ty_background.
ENDCLASS. "lcl_html_action_utils DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_html_action_utils IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS lcl_html_action_utils IMPLEMENTATION.
METHOD field_keys_to_upper.
FIELD-SYMBOLS <field> LIKE LINE OF ct_fields.
LOOP AT ct_fields ASSIGNING <field>.
<field>-name = to_upper( <field>-name ).
ENDLOOP.
ENDMETHOD. "field_keys_to_upper
METHOD add_field.
DATA ls_field LIKE LINE OF ct.
FIELD-SYMBOLS <src> TYPE any.
ls_field-name = name.
CASE cl_abap_typedescr=>describe_by_data( iv )->kind.
WHEN cl_abap_typedescr=>kind_elem.
ls_field-value = iv.
WHEN cl_abap_typedescr=>kind_struct.
ASSIGN COMPONENT name OF STRUCTURE iv TO <src>.
ASSERT <src> IS ASSIGNED.
ls_field-value = <src>.
WHEN OTHERS.
ASSERT 0 = 1.
ENDCASE.
APPEND ls_field TO ct.
ENDMETHOD. "add_field
METHOD get_field.
FIELD-SYMBOLS: <ls_field> LIKE LINE OF it,
<dest> TYPE any.
READ TABLE it ASSIGNING <ls_field> WITH KEY name = name.
IF sy-subrc IS NOT INITIAL.
RETURN.
ENDIF.
CASE cl_abap_typedescr=>describe_by_data( cv )->kind.
WHEN cl_abap_typedescr=>kind_elem.
cv = <ls_field>-value.
WHEN cl_abap_typedescr=>kind_struct.
ASSIGN COMPONENT name OF STRUCTURE cv TO <dest>.
ASSERT <dest> IS ASSIGNED.
<dest> = <ls_field>-value.
WHEN OTHERS.
ASSERT 0 = 1.
ENDCASE.
ENDMETHOD. "get_field
METHOD jump_encode.
DATA: lt_fields TYPE tihttpnvp.
add_field( EXPORTING name = 'TYPE' iv = iv_obj_type CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'NAME' iv = iv_obj_name CHANGING ct = lt_fields ).
rv_string = cl_http_utility=>if_http_utility~fields_to_string( lt_fields ).
ENDMETHOD. "jump_encode
METHOD jump_decode.
DATA: lt_fields TYPE tihttpnvp.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( |{ iv_string }| ).
get_field( EXPORTING name = 'TYPE' it = lt_fields CHANGING cv = ev_obj_type ).
get_field( EXPORTING name = 'NAME' it = lt_fields CHANGING cv = ev_obj_name ).
ENDMETHOD. "jump_decode
METHOD dir_encode.
DATA: lt_fields TYPE tihttpnvp.
add_field( EXPORTING name = 'PATH' iv = iv_path CHANGING ct = lt_fields ).
rv_string = cl_http_utility=>if_http_utility~fields_to_string( lt_fields ).
ENDMETHOD. "dir_encode
METHOD dir_decode.
DATA: lt_fields TYPE tihttpnvp.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( |{ iv_string }| ).
get_field( EXPORTING name = 'PATH' it = lt_fields CHANGING cv = rv_path ).
ENDMETHOD. "dir_decode
METHOD file_encode.
DATA: lt_fields TYPE tihttpnvp.
add_field( EXPORTING name = 'KEY' iv = iv_key CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'PATH' iv = ig_file CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'FILENAME' iv = ig_file CHANGING ct = lt_fields ).
rv_string = cl_http_utility=>if_http_utility~fields_to_string( lt_fields ).
ENDMETHOD. "file_encode
METHOD obj_encode.
DATA: lt_fields TYPE tihttpnvp.
add_field( EXPORTING name = 'KEY' iv = iv_key CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'OBJ_TYPE' iv = ig_object CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'OBJ_NAME' iv = ig_object CHANGING ct = lt_fields ).
rv_string = cl_http_utility=>if_http_utility~fields_to_string( lt_fields ).
ENDMETHOD. "obj_encode
METHOD file_obj_decode.
DATA: lt_fields TYPE tihttpnvp.
ASSERT eg_file IS SUPPLIED OR eg_object IS SUPPLIED.
CLEAR: ev_key, eg_file, eg_object.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( |{ iv_string }| ).
field_keys_to_upper( CHANGING ct_fields = lt_fields ).
get_field( EXPORTING name = 'KEY' it = lt_fields CHANGING cv = ev_key ).
IF eg_file IS SUPPLIED.
get_field( EXPORTING name = 'PATH' it = lt_fields CHANGING cv = eg_file ).
get_field( EXPORTING name = 'FILENAME' it = lt_fields CHANGING cv = eg_file ).
ENDIF.
IF eg_object IS SUPPLIED.
get_field( EXPORTING name = 'OBJ_TYPE' it = lt_fields CHANGING cv = eg_object ).
get_field( EXPORTING name = 'OBJ_NAME' it = lt_fields CHANGING cv = eg_object ).
ENDIF.
ENDMETHOD. "file_decode
METHOD dbkey_encode.
DATA: lt_fields TYPE tihttpnvp.
add_field( EXPORTING name = 'TYPE' iv = is_key-type CHANGING ct = lt_fields ).
add_field( EXPORTING name = 'VALUE' iv = is_key-value CHANGING ct = lt_fields ).
rv_string = cl_http_utility=>if_http_utility~fields_to_string( lt_fields ).
ENDMETHOD. "dbkey_encode
METHOD dbkey_decode.
DATA: lt_fields TYPE tihttpnvp.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( |{ iv_string }| ).
field_keys_to_upper( CHANGING ct_fields = lt_fields ).
get_field( EXPORTING name = 'TYPE' it = lt_fields CHANGING cv = rs_key-type ).
get_field( EXPORTING name = 'VALUE' it = lt_fields CHANGING cv = rs_key-value ).
ENDMETHOD. "dbkey_decode
METHOD dbcontent_decode.
DATA: lt_fields TYPE tihttpnvp,
lv_string TYPE string.
CONCATENATE LINES OF it_postdata INTO lv_string.
rs_content = dbkey_decode( lv_string ).
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( lv_string ).
field_keys_to_upper( CHANGING ct_fields = lt_fields ).
get_field( EXPORTING name = 'XMLDATA' it = lt_fields CHANGING cv = rs_content-data_str ).
IF rs_content-data_str(1) <> '<' AND rs_content-data_str+1(1) = '<'. " Hmmm ???
rs_content-data_str = rs_content-data_str+1.
* ELSE.
* CLEAR rs_content-data_str.
ENDIF.
ENDMETHOD. "dbcontent_decode
METHOD parse_commit_request.
CONSTANTS: lc_replace TYPE string VALUE '<<new>>'.
DATA: lv_string TYPE string,
lt_fields TYPE tihttpnvp.
FIELD-SYMBOLS <body> TYPE string.
CLEAR es_fields.
CONCATENATE LINES OF it_postdata INTO lv_string.
REPLACE ALL OCCURRENCES OF gc_newline IN lv_string WITH lc_replace.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( lv_string ).
field_keys_to_upper( CHANGING ct_fields = lt_fields ).
get_field( EXPORTING name = 'REPO_KEY' it = lt_fields CHANGING cv = es_fields ).
get_field( EXPORTING name = 'USERNAME' it = lt_fields CHANGING cv = es_fields ).
get_field( EXPORTING name = 'EMAIL' it = lt_fields CHANGING cv = es_fields ).
get_field( EXPORTING name = 'COMMENT' it = lt_fields CHANGING cv = es_fields ).
get_field( EXPORTING name = 'BODY' it = lt_fields CHANGING cv = es_fields ).
ASSIGN COMPONENT 'BODY' OF STRUCTURE es_fields TO <body>.
ASSERT <body> IS ASSIGNED.
REPLACE ALL OCCURRENCES OF lc_replace IN <body> WITH gc_newline.
ASSERT es_fields IS NOT INITIAL.
ENDMETHOD. "parse_commit_request
METHOD decode_bg_update.
DATA: lt_fields TYPE tihttpnvp.
lt_fields = cl_http_utility=>if_http_utility~string_to_fields( |{ iv_getdata }| ).
field_keys_to_upper( CHANGING ct_fields = lt_fields ).
get_field( EXPORTING name = 'METHOD' it = lt_fields CHANGING cv = rs_fields ).
get_field( EXPORTING name = 'USERNAME' it = lt_fields CHANGING cv = rs_fields ).
get_field( EXPORTING name = 'PASSWORD' it = lt_fields CHANGING cv = rs_fields ).
get_field( EXPORTING name = 'AMETHOD' it = lt_fields CHANGING cv = rs_fields ).
get_field( EXPORTING name = 'ANAME' it = lt_fields CHANGING cv = rs_fields ).
get_field( EXPORTING name = 'AMAIL' it = lt_fields CHANGING cv = rs_fields ).
ASSERT NOT rs_fields IS INITIAL.
ENDMETHOD. "decode_bg_update
ENDCLASS. "lcl_html_action_utils IMPLEMENTATION
|
edit xml - fix dump, close #539
|
edit xml - fix dump, close #539
|
ABAP
|
mit
|
apex8/abapGit,apex8/abapGit,sbcgua/abapGit,sbcgua/abapGit,nununo/abapGit,larshp/abapGit,EduardoCopat/abapGit,larshp/abapGit,EduardoCopat/abapGit,nununo/abapGit
|
258414aba6cb9341d59d44098f70eabab015c32e
|
src/zabapgit_object_sicf.prog.abap
|
src/zabapgit_object_sicf.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_SICF
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_sicf DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_sicf DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
PRIVATE SECTION.
TYPES: ty_icfhandler_tt TYPE STANDARD TABLE OF icfhandler WITH DEFAULT KEY.
TYPES: BEGIN OF ty_sicf_key,
icf_name TYPE icfservice-icf_name,
icfparguid TYPE icfservice-icfparguid,
END OF ty_sicf_key.
METHODS read
IMPORTING iv_clear TYPE abap_bool DEFAULT abap_true
EXPORTING es_icfservice TYPE icfservice
es_icfdocu TYPE icfdocu
et_icfhandler TYPE ty_icfhandler_tt
ev_url TYPE string
RAISING lcx_exception.
METHODS insert_sicf
IMPORTING is_icfservice TYPE icfservice
is_icfdocu TYPE icfdocu
it_icfhandler TYPE ty_icfhandler_tt
iv_package TYPE devclass
iv_url TYPE string
RAISING lcx_exception.
METHODS change_sicf
IMPORTING is_icfservice TYPE icfservice
is_icfdocu TYPE icfdocu
it_icfhandler TYPE ty_icfhandler_tt
iv_package TYPE devclass
iv_parent TYPE icfparguid
RAISING lcx_exception.
METHODS to_icfhndlist
IMPORTING it_list TYPE ty_icfhandler_tt
RETURNING VALUE(rt_list) TYPE icfhndlist.
METHODS find_parent
IMPORTING iv_url TYPE string
RETURNING VALUE(rv_parent) TYPE icfparguid
RAISING lcx_exception.
ENDCLASS. "lcl_object_sicf DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_sicf IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_sicf IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
DATA: ls_icfservice TYPE icfservice.
read( EXPORTING iv_clear = abap_false
IMPORTING es_icfservice = ls_icfservice ).
rv_user = ls_icfservice-icf_muser.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD lif_object~exists.
DATA: ls_icfservice TYPE icfservice.
read( IMPORTING es_icfservice = ls_icfservice ).
rv_bool = boolc( NOT ls_icfservice IS INITIAL ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~serialize.
DATA: ls_icfservice TYPE icfservice,
ls_icfdocu TYPE icfdocu,
lv_url TYPE string,
lt_icfhandler TYPE TABLE OF icfhandler.
read( IMPORTING es_icfservice = ls_icfservice
es_icfdocu = ls_icfdocu
et_icfhandler = lt_icfhandler
ev_url = lv_url ).
IF ls_icfservice IS INITIAL.
RETURN.
ENDIF.
CLEAR ls_icfservice-icfnodguid.
CLEAR ls_icfservice-icfparguid.
CLEAR ls_icfservice-icf_user.
CLEAR ls_icfservice-icf_cclnt.
CLEAR ls_icfservice-icf_mclnt.
io_xml->add( iv_name = 'URL'
ig_data = lv_url ).
io_xml->add( iv_name = 'ICFSERVICE'
ig_data = ls_icfservice ).
io_xml->add( iv_name = 'ICFDOCU'
ig_data = ls_icfdocu ).
io_xml->add( iv_name = 'ICFHANDLER_TABLE'
ig_data = lt_icfhandler ).
ENDMETHOD. "serialize
METHOD read.
DATA: lt_serv_info TYPE icfservtbl,
ls_serv_info LIKE LINE OF lt_serv_info,
ls_key TYPE ty_sicf_key.
FIELD-SYMBOLS: <ls_icfhandler> LIKE LINE OF et_icfhandler.
CLEAR es_icfservice.
CLEAR es_icfdocu.
CLEAR et_icfhandler.
CLEAR ev_url.
ls_key = ms_item-obj_name.
IF ls_key-icfparguid IS INITIAL.
* limitation: name must be unique
SELECT SINGLE icfparguid FROM icfservice
INTO ls_key-icfparguid
WHERE icf_name = ls_key-icf_name
AND icf_cuser <> 'SAP' ##warn_ok.
IF sy-subrc <> 0.
RETURN.
ENDIF.
ENDIF.
cl_icf_tree=>if_icf_tree~get_info_from_serv(
EXPORTING
icf_name = ls_key-icf_name
icfparguid = ls_key-icfparguid
icf_langu = mv_language
IMPORTING
serv_info = lt_serv_info
icfdocu = es_icfdocu
url = ev_url
EXCEPTIONS
wrong_name = 1
wrong_parguid = 2
incorrect_service = 3
no_authority = 4
OTHERS = 5 ).
IF sy-subrc <> 0.
lcx_exception=>raise( 'SICF - error from get_info_from_serv' ).
ENDIF.
ASSERT lines( lt_serv_info ) = 1.
READ TABLE lt_serv_info INDEX 1 INTO ls_serv_info.
ASSERT sy-subrc = 0.
MOVE-CORRESPONDING ls_serv_info-service TO es_icfservice.
IF iv_clear = abap_true.
CLEAR es_icfservice-icf_cuser.
CLEAR es_icfservice-icf_cdate.
CLEAR es_icfservice-icf_muser.
CLEAR es_icfservice-icf_mdate.
ENDIF.
CLEAR es_icfdocu-icfparguid.
APPEND LINES OF ls_serv_info-handlertbl TO et_icfhandler.
LOOP AT et_icfhandler ASSIGNING <ls_icfhandler>.
CLEAR <ls_icfhandler>-icfparguid.
ENDLOOP.
ENDMETHOD. "read
METHOD lif_object~deserialize.
DATA: ls_icfservice TYPE icfservice,
ls_read TYPE icfservice,
ls_icfdocu TYPE icfdocu,
lv_url TYPE string,
lt_icfhandler TYPE TABLE OF icfhandler.
io_xml->read( EXPORTING iv_name = 'URL'
CHANGING cg_data = lv_url ).
io_xml->read( EXPORTING iv_name = 'ICFSERVICE'
CHANGING cg_data = ls_icfservice ).
io_xml->read( EXPORTING iv_name = 'ICFDOCU'
CHANGING cg_data = ls_icfdocu ).
io_xml->read( EXPORTING iv_name = 'ICFHANDLER_TABLE'
CHANGING cg_data = lt_icfhandler ).
read( IMPORTING es_icfservice = ls_read ).
IF ls_read IS INITIAL.
insert_sicf( is_icfservice = ls_icfservice
is_icfdocu = ls_icfdocu
it_icfhandler = lt_icfhandler
iv_package = iv_package
iv_url = lv_url ).
ELSE.
change_sicf( is_icfservice = ls_icfservice
is_icfdocu = ls_icfdocu
it_icfhandler = lt_icfhandler
iv_package = iv_package
iv_parent = ls_read-icfparguid ).
ENDIF.
ENDMETHOD. "deserialize
METHOD to_icfhndlist.
FIELD-SYMBOLS: <ls_list> LIKE LINE OF it_list.
* convert to sorted table
LOOP AT it_list ASSIGNING <ls_list>.
INSERT <ls_list>-icfhandler INTO TABLE rt_list.
ENDLOOP.
ENDMETHOD. "to_icfhndlist
METHOD find_parent.
cl_icf_tree=>if_icf_tree~service_from_url(
EXPORTING
url = iv_url
hostnumber = 0
IMPORTING
icfnodguid = rv_parent
EXCEPTIONS
wrong_application = 1
no_application = 2
not_allow_application = 3
wrong_url = 4
no_authority = 5
OTHERS = 6 ).
IF sy-subrc <> 0.
lcx_exception=>raise( 'SICF - error from service_from_url' ).
ENDIF.
ENDMETHOD. "find_parent
METHOD insert_sicf.
DATA: lt_icfhndlist TYPE icfhndlist,
ls_icfserdesc TYPE icfserdesc,
ls_icfdocu TYPE icfdocu,
lv_parent TYPE icfparguid.
lt_icfhndlist = to_icfhndlist( it_icfhandler ).
lv_parent = find_parent( iv_url ).
* nice, it seems that the structure should be mistreated
ls_icfdocu = is_icfdocu-icf_docu.
MOVE-CORRESPONDING is_icfservice TO ls_icfserdesc.
cl_icf_tree=>if_icf_tree~insert_node(
EXPORTING
icf_name = is_icfservice-orig_name
icfparguid = lv_parent
icfdocu = ls_icfdocu
doculang = mv_language
icfhandlst = lt_icfhndlist
package = iv_package
application = space
icfserdesc = ls_icfserdesc
icfactive = abap_true
EXCEPTIONS
empty_icf_name = 1
no_new_virtual_host = 2
special_service_error = 3
parent_not_existing = 4
enqueue_error = 5
node_already_existing = 6
empty_docu = 7
doculang_not_installed = 8
security_info_error = 9
user_password_error = 10
password_encryption_error = 11
invalid_url = 12
invalid_otr_concept = 13
formflg401_error = 14
handler_error = 15
transport_error = 16
tadir_error = 17
package_not_found = 18
wrong_application = 19
not_allow_application = 20
no_application = 21
invalid_icfparguid = 22
alt_name_invalid = 23
alternate_name_exist = 24
wrong_icf_name = 25
no_authority = 26
OTHERS = 27 ).
IF sy-subrc <> 0.
lcx_exception=>raise( |SICF - error from insert_node: { sy-subrc }| ).
ENDIF.
ENDMETHOD. "insert_sicf
METHOD change_sicf.
DATA: lt_icfhndlist TYPE icfhndlist,
lt_existing TYPE TABLE OF icfhandler,
ls_icfserdesc TYPE icfserdesc.
FIELD-SYMBOLS: <ls_existing> LIKE LINE OF lt_existing.
lt_icfhndlist = to_icfhndlist( it_icfhandler ).
* Do not add handlers if they already exist, it will make the below
* call to SAP standard code raise an exception
SELECT * FROM icfhandler INTO TABLE lt_existing
WHERE icf_name = is_icfservice-icf_name.
LOOP AT lt_existing ASSIGNING <ls_existing>.
DELETE TABLE lt_icfhndlist FROM <ls_existing>-icfhandler.
ENDLOOP.
MOVE-CORRESPONDING is_icfservice TO ls_icfserdesc.
cl_icf_tree=>if_icf_tree~change_node(
EXPORTING
icf_name = is_icfservice-orig_name
icfparguid = iv_parent
icfdocu = is_icfdocu
doculang = mv_language
icfhandlst = lt_icfhndlist
package = iv_package
application = space
icfserdesc = ls_icfserdesc
icfactive = abap_true
EXCEPTIONS
empty_icf_name = 1
no_new_virtual_host = 2
special_service_error = 3
parent_not_existing = 4
enqueue_error = 5
node_already_existing = 6
empty_docu = 7
doculang_not_installed = 8
security_info_error = 9
user_password_error = 10
password_encryption_error = 11
invalid_url = 12
invalid_otr_concept = 13
formflg401_error = 14
handler_error = 15
transport_error = 16
tadir_error = 17
package_not_found = 18
wrong_application = 19
not_allow_application = 20
no_application = 21
invalid_icfparguid = 22
alt_name_invalid = 23
alternate_name_exist = 24
wrong_icf_name = 25
no_authority = 26
OTHERS = 27 ).
IF sy-subrc <> 0.
lcx_exception=>raise( 'SICF - error from change_node' ).
ENDIF.
ENDMETHOD. "change_sicf
METHOD lif_object~delete.
DATA: ls_icfservice TYPE icfservice.
read( IMPORTING es_icfservice = ls_icfservice ).
cl_icf_tree=>if_icf_tree~delete_node(
EXPORTING
icfparguid = ls_icfservice-icfparguid
CHANGING
icf_name = ls_icfservice-icf_name
EXCEPTIONS
no_virtual_host_delete = 1
special_service_error = 2
enqueue_error = 3
node_not_existing = 4
node_has_childs = 5
node_is_aliased = 6
node_not_in_original_system = 7
transport_error = 8
tadir_error = 9
db_error = 10
no_authority = 11
OTHERS = 12 ).
IF sy-subrc <> 0.
lcx_exception=>raise( 'SICF - error from delete_node' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~jump.
lcx_exception=>raise( 'todo, SICF, jump' ).
ENDMETHOD. "jump
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_comparison_null.
ENDMETHOD.
ENDCLASS. "lcl_object_sicf IMPLEMENTATION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_SICF
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_sicf DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_sicf DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
PRIVATE SECTION.
TYPES: ty_icfhandler_tt TYPE STANDARD TABLE OF icfhandler WITH DEFAULT KEY.
TYPES: BEGIN OF ty_sicf_key,
icf_name TYPE icfservice-icf_name,
icfparguid TYPE icfservice-icfparguid,
END OF ty_sicf_key.
METHODS read
IMPORTING iv_clear TYPE abap_bool DEFAULT abap_true
EXPORTING es_icfservice TYPE icfservice
es_icfdocu TYPE icfdocu
et_icfhandler TYPE ty_icfhandler_tt
ev_url TYPE string
RAISING lcx_exception.
METHODS insert_sicf
IMPORTING is_icfservice TYPE icfservice
is_icfdocu TYPE icfdocu
it_icfhandler TYPE ty_icfhandler_tt
iv_package TYPE devclass
iv_url TYPE string
RAISING lcx_exception.
METHODS change_sicf
IMPORTING is_icfservice TYPE icfservice
is_icfdocu TYPE icfdocu
it_icfhandler TYPE ty_icfhandler_tt
iv_package TYPE devclass
iv_parent TYPE icfparguid
RAISING lcx_exception.
METHODS to_icfhndlist
IMPORTING it_list TYPE ty_icfhandler_tt
RETURNING VALUE(rt_list) TYPE icfhndlist.
METHODS find_parent
IMPORTING iv_url TYPE string
RETURNING VALUE(rv_parent) TYPE icfparguid
RAISING lcx_exception.
ENDCLASS. "lcl_object_sicf DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_sicf IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_sicf IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
DATA: ls_icfservice TYPE icfservice.
read( EXPORTING iv_clear = abap_false
IMPORTING es_icfservice = ls_icfservice ).
rv_user = ls_icfservice-icf_muser.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD lif_object~exists.
DATA: ls_icfservice TYPE icfservice.
read( IMPORTING es_icfservice = ls_icfservice ).
rv_bool = boolc( NOT ls_icfservice IS INITIAL ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~serialize.
DATA: ls_icfservice TYPE icfservice,
ls_icfdocu TYPE icfdocu,
lv_url TYPE string,
lt_icfhandler TYPE TABLE OF icfhandler.
read( IMPORTING es_icfservice = ls_icfservice
es_icfdocu = ls_icfdocu
et_icfhandler = lt_icfhandler
ev_url = lv_url ).
IF ls_icfservice IS INITIAL.
RETURN.
ENDIF.
CLEAR ls_icfservice-icfnodguid.
CLEAR ls_icfservice-icfparguid.
CLEAR ls_icfservice-icf_user.
CLEAR ls_icfservice-icf_cclnt.
CLEAR ls_icfservice-icf_mclnt.
io_xml->add( iv_name = 'URL'
ig_data = lv_url ).
io_xml->add( iv_name = 'ICFSERVICE'
ig_data = ls_icfservice ).
io_xml->add( iv_name = 'ICFDOCU'
ig_data = ls_icfdocu ).
io_xml->add( iv_name = 'ICFHANDLER_TABLE'
ig_data = lt_icfhandler ).
ENDMETHOD. "serialize
METHOD read.
DATA: lt_serv_info TYPE icfservtbl,
ls_serv_info LIKE LINE OF lt_serv_info,
ls_key TYPE ty_sicf_key.
FIELD-SYMBOLS: <ls_icfhandler> LIKE LINE OF et_icfhandler.
CLEAR es_icfservice.
CLEAR es_icfdocu.
CLEAR et_icfhandler.
CLEAR ev_url.
ls_key = ms_item-obj_name.
IF ls_key-icfparguid IS INITIAL.
* limitation: name must be unique
SELECT SINGLE icfparguid FROM icfservice
INTO ls_key-icfparguid
WHERE icf_name = ls_key-icf_name
AND icf_cuser <> 'SAP' ##warn_ok.
IF sy-subrc <> 0.
RETURN.
ENDIF.
ENDIF.
cl_icf_tree=>if_icf_tree~get_info_from_serv(
EXPORTING
icf_name = ls_key-icf_name
icfparguid = ls_key-icfparguid
icf_langu = mv_language
IMPORTING
serv_info = lt_serv_info
icfdocu = es_icfdocu
url = ev_url
EXCEPTIONS
wrong_name = 1
wrong_parguid = 2
incorrect_service = 3
no_authority = 4
OTHERS = 5 ).
IF sy-subrc <> 0.
lcx_exception=>raise( 'SICF - error from get_info_from_serv' ).
ENDIF.
ASSERT lines( lt_serv_info ) = 1.
READ TABLE lt_serv_info INDEX 1 INTO ls_serv_info.
ASSERT sy-subrc = 0.
MOVE-CORRESPONDING ls_serv_info-service TO es_icfservice.
IF iv_clear = abap_true.
CLEAR es_icfservice-icf_cuser.
CLEAR es_icfservice-icf_cdate.
CLEAR es_icfservice-icf_muser.
CLEAR es_icfservice-icf_mdate.
ENDIF.
CLEAR es_icfdocu-icfparguid.
APPEND LINES OF ls_serv_info-handlertbl TO et_icfhandler.
LOOP AT et_icfhandler ASSIGNING <ls_icfhandler>.
CLEAR <ls_icfhandler>-icfparguid.
ENDLOOP.
ENDMETHOD. "read
METHOD lif_object~deserialize.
DATA: ls_icfservice TYPE icfservice,
ls_read TYPE icfservice,
ls_icfdocu TYPE icfdocu,
lv_url TYPE string,
lt_icfhandler TYPE TABLE OF icfhandler.
io_xml->read( EXPORTING iv_name = 'URL'
CHANGING cg_data = lv_url ).
io_xml->read( EXPORTING iv_name = 'ICFSERVICE'
CHANGING cg_data = ls_icfservice ).
io_xml->read( EXPORTING iv_name = 'ICFDOCU'
CHANGING cg_data = ls_icfdocu ).
io_xml->read( EXPORTING iv_name = 'ICFHANDLER_TABLE'
CHANGING cg_data = lt_icfhandler ).
read( IMPORTING es_icfservice = ls_read ).
IF ls_read IS INITIAL.
insert_sicf( is_icfservice = ls_icfservice
is_icfdocu = ls_icfdocu
it_icfhandler = lt_icfhandler
iv_package = iv_package
iv_url = lv_url ).
ELSE.
change_sicf( is_icfservice = ls_icfservice
is_icfdocu = ls_icfdocu
it_icfhandler = lt_icfhandler
iv_package = iv_package
iv_parent = ls_read-icfparguid ).
ENDIF.
ENDMETHOD. "deserialize
METHOD to_icfhndlist.
FIELD-SYMBOLS: <ls_list> LIKE LINE OF it_list.
* convert to sorted table
LOOP AT it_list ASSIGNING <ls_list>.
INSERT <ls_list>-icfhandler INTO TABLE rt_list.
ENDLOOP.
ENDMETHOD. "to_icfhndlist
METHOD find_parent.
cl_icf_tree=>if_icf_tree~service_from_url(
EXPORTING
url = iv_url
hostnumber = 0
IMPORTING
icfnodguid = rv_parent
EXCEPTIONS
wrong_application = 1
no_application = 2
not_allow_application = 3
wrong_url = 4
no_authority = 5
OTHERS = 6 ).
IF sy-subrc <> 0.
lcx_exception=>raise( 'SICF - error from service_from_url' ).
ENDIF.
ENDMETHOD. "find_parent
METHOD insert_sicf.
DATA: lt_icfhndlist TYPE icfhndlist,
ls_icfserdesc TYPE icfserdesc,
ls_icfdocu TYPE icfdocu,
lv_parent TYPE icfparguid.
lt_icfhndlist = to_icfhndlist( it_icfhandler ).
lv_parent = find_parent( iv_url ).
* nice, it seems that the structure should be mistreated
ls_icfdocu = is_icfdocu-icf_docu.
MOVE-CORRESPONDING is_icfservice TO ls_icfserdesc.
cl_icf_tree=>if_icf_tree~insert_node(
EXPORTING
icf_name = is_icfservice-orig_name
icfparguid = lv_parent
icfdocu = ls_icfdocu
doculang = mv_language
icfhandlst = lt_icfhndlist
package = iv_package
application = space
icfserdesc = ls_icfserdesc
icfactive = abap_true
EXCEPTIONS
empty_icf_name = 1
no_new_virtual_host = 2
special_service_error = 3
parent_not_existing = 4
enqueue_error = 5
node_already_existing = 6
empty_docu = 7
doculang_not_installed = 8
security_info_error = 9
user_password_error = 10
password_encryption_error = 11
invalid_url = 12
invalid_otr_concept = 13
formflg401_error = 14
handler_error = 15
transport_error = 16
tadir_error = 17
package_not_found = 18
wrong_application = 19
not_allow_application = 20
no_application = 21
invalid_icfparguid = 22
alt_name_invalid = 23
alternate_name_exist = 24
wrong_icf_name = 25
no_authority = 26
OTHERS = 27 ).
IF sy-subrc <> 0.
lcx_exception=>raise( |SICF - error from insert_node: { sy-subrc }| ).
ENDIF.
ENDMETHOD. "insert_sicf
METHOD change_sicf.
DATA: lt_icfhndlist TYPE icfhndlist,
lt_existing TYPE TABLE OF icfhandler,
ls_icfserdesc TYPE icfserdesc.
FIELD-SYMBOLS: <ls_existing> LIKE LINE OF lt_existing.
lt_icfhndlist = to_icfhndlist( it_icfhandler ).
* Do not add handlers if they already exist, it will make the below
* call to SAP standard code raise an exception
SELECT * FROM icfhandler INTO TABLE lt_existing
WHERE icf_name = is_icfservice-icf_name.
LOOP AT lt_existing ASSIGNING <ls_existing>.
DELETE TABLE lt_icfhndlist FROM <ls_existing>-icfhandler.
ENDLOOP.
MOVE-CORRESPONDING is_icfservice TO ls_icfserdesc.
cl_icf_tree=>if_icf_tree~change_node(
EXPORTING
icf_name = is_icfservice-orig_name
icfparguid = iv_parent
icfdocu = is_icfdocu
doculang = mv_language
icfhandlst = lt_icfhndlist
package = iv_package
application = space
icfserdesc = ls_icfserdesc
icfactive = abap_true
EXCEPTIONS
empty_icf_name = 1
no_new_virtual_host = 2
special_service_error = 3
parent_not_existing = 4
enqueue_error = 5
node_already_existing = 6
empty_docu = 7
doculang_not_installed = 8
security_info_error = 9
user_password_error = 10
password_encryption_error = 11
invalid_url = 12
invalid_otr_concept = 13
formflg401_error = 14
handler_error = 15
transport_error = 16
tadir_error = 17
package_not_found = 18
wrong_application = 19
not_allow_application = 20
no_application = 21
invalid_icfparguid = 22
alt_name_invalid = 23
alternate_name_exist = 24
wrong_icf_name = 25
no_authority = 26
OTHERS = 27 ).
IF sy-subrc <> 0.
lcx_exception=>raise( 'SICF - error from change_node' ).
ENDIF.
ENDMETHOD. "change_sicf
METHOD lif_object~delete.
DATA: ls_icfservice TYPE icfservice.
read( IMPORTING es_icfservice = ls_icfservice ).
cl_icf_tree=>if_icf_tree~delete_node(
EXPORTING
icfparguid = ls_icfservice-icfparguid
CHANGING
icf_name = ls_icfservice-icf_name
EXCEPTIONS
no_virtual_host_delete = 1
special_service_error = 2
enqueue_error = 3
node_not_existing = 4
node_has_childs = 5
node_is_aliased = 6
node_not_in_original_system = 7
transport_error = 8
tadir_error = 9
db_error = 10
no_authority = 11
OTHERS = 12 ).
IF sy-subrc <> 0.
lcx_exception=>raise( 'SICF - error from delete_node' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~jump.
DATA: ls_bcdata TYPE bdcdata,
lt_bcdata TYPE STANDARD TABLE OF bdcdata.
ls_bcdata-program = 'RSICFTREE'.
ls_bcdata-dynpro = '1000'.
ls_bcdata-dynbegin = 'X'.
APPEND ls_bcdata TO lt_bcdata.
ls_bcdata-dynpro = space.
ls_bcdata-dynbegin = space.
ls_bcdata-fnam = 'ICF_SERV'.
ls_bcdata-fval = ms_item-obj_name.
APPEND ls_bcdata TO lt_bcdata.
ls_bcdata-fnam = 'BDC_OKCODE'.
ls_bcdata-fval = '=ONLI'.
APPEND ls_bcdata TO lt_bcdata.
CALL FUNCTION 'ABAP4_CALL_TRANSACTION'
STARTING NEW TASK 'GIT'
EXPORTING
tcode = 'SICF'
mode_val = 'E'
TABLES
using_tab = lt_bcdata
EXCEPTIONS
OTHERS = 1.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from ABAP4_CALL_TRANSACTION, SICF' ).
ENDIF.
ENDMETHOD. "jump
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_comparison_null.
ENDMETHOD.
ENDCLASS. "lcl_object_sicf IMPLEMENTATION
|
add SICF jump
|
add SICF jump
|
ABAP
|
mit
|
EduardoCopat/abapGit,sbcgua/abapGit,larshp/abapGit,EduardoCopat/abapGit,apex8/abapGit,apex8/abapGit,sbcgua/abapGit,larshp/abapGit
|
e136414c51ce9a25105b1af06d361f6caeda130b
|
src/zabapgit_object_ttyp.prog.abap
|
src/zabapgit_object_ttyp.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_TTYP
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_ttyp DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_ttyp DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
ENDCLASS. "lcl_object_dtel DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_ttyp IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_ttyp IMPLEMENTATION.
METHOD lif_object~has_changed_since.
DATA: lv_date TYPE dats,
lv_time TYPE tims,
lv_ts TYPE timestamp.
SELECT SINGLE as4date as4time FROM dd40l
INTO (lv_date, lv_time)
WHERE typename = ms_item-obj_name
AND as4local = 'A'.
_object_check_timestamp lv_date lv_time.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
SELECT SINGLE as4user FROM dd40l INTO rv_user
WHERE typename = ms_item-obj_name
AND as4local = 'A'.
IF sy-subrc <> 0.
rv_user = c_user_unknown.
ENDIF.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD lif_object~exists.
DATA: lv_typename TYPE dd40l-typename.
SELECT SINGLE typename FROM dd40l INTO lv_typename
WHERE typename = ms_item-obj_name
AND as4local = 'A'.
rv_bool = boolc( sy-subrc = 0 ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~jump.
jump_se11( iv_radio = 'RSRD1-DDTYPE'
iv_field = 'RSRD1-DDTYPE_VAL' ).
ENDMETHOD. "jump
METHOD lif_object~delete.
DATA: lv_objname TYPE rsedd0-ddobjname.
lv_objname = ms_item-obj_name.
CALL FUNCTION 'RS_DD_DELETE_OBJ'
EXPORTING
no_ask = abap_true
objname = lv_objname
objtype = 'A'
EXCEPTIONS
not_executed = 1
object_not_found = 2
object_not_specified = 3
permission_failure = 4.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from RS_DD_DELETE_OBJ, TTYP' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~serialize.
DATA: lv_name TYPE ddobjname,
lt_dd42v TYPE dd42v_tab,
lt_dd43v TYPE dd43v_tab,
ls_dd40v TYPE dd40v.
lv_name = ms_item-obj_name.
CALL FUNCTION 'DDIF_TTYP_GET'
EXPORTING
name = lv_name
state = 'A'
langu = mv_language
IMPORTING
dd40v_wa = ls_dd40v
TABLES
dd42v_tab = lt_dd42v
dd43v_tab = lt_dd43v
EXCEPTIONS
illegal_input = 1
OTHERS = 2.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DDIF_TTYP_GET' ).
ENDIF.
IF ls_dd40v IS INITIAL.
RETURN. " does not exist in system
ENDIF.
CLEAR: ls_dd40v-as4user,
ls_dd40v-as4date,
ls_dd40v-as4time.
io_xml->add( iv_name = 'DD40V'
ig_data = ls_dd40v ).
io_xml->add( iv_name = 'DD42V'
ig_data = lt_dd42v ).
io_xml->add( iv_name = 'DD43V'
ig_data = lt_dd43v ).
ENDMETHOD. "serialize
METHOD lif_object~deserialize.
DATA: lv_name TYPE ddobjname,
lt_dd42v TYPE dd42v_tab,
lt_dd43v TYPE dd43v_tab,
ls_dd40v TYPE dd40v.
io_xml->read( EXPORTING iv_name = 'DD40V'
CHANGING cg_data = ls_dd40v ).
io_xml->read( EXPORTING iv_name = 'DD42V'
CHANGING cg_data = lt_dd42v ).
io_xml->read( EXPORTING iv_name = 'DD43V'
CHANGING cg_data = lt_dd43v ).
corr_insert( iv_package ).
lv_name = ms_item-obj_name. " type conversion
CALL FUNCTION 'DDIF_TTYP_PUT'
EXPORTING
name = lv_name
dd40v_wa = ls_dd40v
TABLES
dd42v_tab = lt_dd42v
dd43v_tab = lt_dd43v
EXCEPTIONS
ttyp_not_found = 1
name_inconsistent = 2
ttyp_inconsistent = 3
put_failure = 4
put_refused = 5
OTHERS = 6.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DDIF_TTYP_PUT' ).
ENDIF.
lcl_objects_activation=>add_item( ms_item ).
ENDMETHOD. "deserialize
ENDCLASS. "lcl_object_ttyp IMPLEMENTATION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_TTYP
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_ttyp DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_ttyp DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
ENDCLASS. "lcl_object_dtel DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_ttyp IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_ttyp IMPLEMENTATION.
METHOD lif_object~has_changed_since.
DATA: lv_date TYPE dats,
lv_time TYPE tims,
lv_ts TYPE timestamp.
SELECT SINGLE as4date as4time FROM dd40l
INTO (lv_date, lv_time)
WHERE typename = ms_item-obj_name
AND as4local = 'A'.
_object_check_timestamp lv_date lv_time.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
SELECT SINGLE as4user FROM dd40l INTO rv_user
WHERE typename = ms_item-obj_name
AND as4local = 'A'.
IF sy-subrc <> 0.
rv_user = c_user_unknown.
ENDIF.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD lif_object~exists.
DATA: lv_typename TYPE dd40l-typename.
SELECT SINGLE typename FROM dd40l INTO lv_typename
WHERE typename = ms_item-obj_name
AND as4local = 'A'.
rv_bool = boolc( sy-subrc = 0 ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~jump.
jump_se11( iv_radio = 'RSRD1-DDTYPE'
iv_field = 'RSRD1-DDTYPE_VAL' ).
ENDMETHOD. "jump
METHOD lif_object~delete.
DATA: lv_objname TYPE rsedd0-ddobjname.
lv_objname = ms_item-obj_name.
CALL FUNCTION 'RS_DD_DELETE_OBJ'
EXPORTING
no_ask = abap_true
objname = lv_objname
objtype = 'A'
EXCEPTIONS
not_executed = 1
object_not_found = 2
object_not_specified = 3
permission_failure = 4.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from RS_DD_DELETE_OBJ, TTYP' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~serialize.
DATA: lv_name TYPE ddobjname,
lt_dd42v TYPE dd42v_tab,
lt_dd43v TYPE dd43v_tab,
ls_dd40v TYPE dd40v.
lv_name = ms_item-obj_name.
CALL FUNCTION 'DDIF_TTYP_GET'
EXPORTING
name = lv_name
state = 'A'
langu = mv_language
IMPORTING
dd40v_wa = ls_dd40v
TABLES
dd42v_tab = lt_dd42v
dd43v_tab = lt_dd43v
EXCEPTIONS
illegal_input = 1
OTHERS = 2.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DDIF_TTYP_GET' ).
ENDIF.
IF ls_dd40v IS INITIAL.
RETURN. " does not exist in system
ENDIF.
CLEAR: ls_dd40v-as4user,
ls_dd40v-as4date,
ls_dd40v-as4time.
IF NOT ls_dd40v-rowkind IS INITIAL.
CLEAR ls_dd40v-typelen.
ENDIF.
io_xml->add( iv_name = 'DD40V'
ig_data = ls_dd40v ).
io_xml->add( iv_name = 'DD42V'
ig_data = lt_dd42v ).
io_xml->add( iv_name = 'DD43V'
ig_data = lt_dd43v ).
ENDMETHOD. "serialize
METHOD lif_object~deserialize.
DATA: lv_name TYPE ddobjname,
lt_dd42v TYPE dd42v_tab,
lt_dd43v TYPE dd43v_tab,
ls_dd40v TYPE dd40v.
io_xml->read( EXPORTING iv_name = 'DD40V'
CHANGING cg_data = ls_dd40v ).
io_xml->read( EXPORTING iv_name = 'DD42V'
CHANGING cg_data = lt_dd42v ).
io_xml->read( EXPORTING iv_name = 'DD43V'
CHANGING cg_data = lt_dd43v ).
corr_insert( iv_package ).
lv_name = ms_item-obj_name. " type conversion
CALL FUNCTION 'DDIF_TTYP_PUT'
EXPORTING
name = lv_name
dd40v_wa = ls_dd40v
TABLES
dd42v_tab = lt_dd42v
dd43v_tab = lt_dd43v
EXCEPTIONS
ttyp_not_found = 1
name_inconsistent = 2
ttyp_inconsistent = 3
put_failure = 4
put_refused = 5
OTHERS = 6.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DDIF_TTYP_PUT' ).
ENDIF.
lcl_objects_activation=>add_item( ms_item ).
ENDMETHOD. "deserialize
ENDCLASS. "lcl_object_ttyp IMPLEMENTATION
|
clear TYPELEN
|
TTYP: clear TYPELEN
|
ABAP
|
mit
|
nununo/abapGit,sbcgua/abapGit,larshp/abapGit,apex8/abapGit,apex8/abapGit,sbcgua/abapGit,EduardoCopat/abapGit,EduardoCopat/abapGit,larshp/abapGit,nununo/abapGit
|
70550822601c08cbde92a185f5f8fd0a5cd57c41
|
src/zabapgit_object_shi3.prog.abap
|
src/zabapgit_object_shi3.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_SHI3
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_shi3 DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_object_shi3 DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
METHODS constructor
IMPORTING
is_item TYPE ty_item
iv_language TYPE spras.
PRIVATE SECTION.
TYPES: BEGIN OF ty_id_map,
old TYPE ttree-id,
new TYPE ttree-id,
END OF ty_id_map.
TYPES tt_id_map TYPE STANDARD TABLE OF ty_id_map.
TYPES ts_id_map TYPE SORTED TABLE OF ty_id_map WITH UNIQUE KEY old.
DATA: mv_tree_id TYPE ttree-id,
mt_map TYPE ts_id_map. " SORTED !
METHODS jump_se43
RAISING lcx_exception.
METHODS strip_stamps
CHANGING cs_head TYPE ttree
ct_nodes TYPE hier_iface_t.
METHODS regenerate_ids
CHANGING ct_nodes TYPE hier_iface_t
ct_refs TYPE hier_ref_t
ct_texts TYPE hier_texts_t
RAISING lcx_exception.
METHODS replace_id
IMPORTING iv_id TYPE clike
RETURNING VALUE(rv_new_id) TYPE ttree-id
RAISING lcx_exception.
ENDCLASS. "lcl_object_shi3 DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_shi3 IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS lcl_object_shi3 IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
rv_user = c_user_unknown. " todo
ENDMETHOD.
METHOD constructor.
super->constructor( is_item = is_item iv_language = iv_language ).
mv_tree_id = ms_item-obj_name.
ENDMETHOD. "constructor
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD jump_se43.
DATA: lt_bdcdata TYPE TABLE OF bdcdata.
FIELD-SYMBOLS: <ls_bdcdata> LIKE LINE OF lt_bdcdata.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-program = 'SAPLBMEN'.
<ls_bdcdata>-dynpro = '0200'.
<ls_bdcdata>-dynbegin = abap_true.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'BDC_OKCODE'.
<ls_bdcdata>-fval = '=SHOW'.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'BMENUNAME-ID'.
<ls_bdcdata>-fval = ms_item-obj_name.
CALL FUNCTION 'ABAP4_CALL_TRANSACTION'
STARTING NEW TASK 'GIT'
EXPORTING
tcode = 'SE43'
mode_val = 'E'
TABLES
using_tab = lt_bdcdata
EXCEPTIONS
system_failure = 1
communication_failure = 2
resource_failure = 3
OTHERS = 4.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from ABAP4_CALL_TRANSACTION, SHI3' ).
ENDIF.
ENDMETHOD. "jump_se43
METHOD lif_object~jump.
jump_se43( ).
ENDMETHOD. "jump
METHOD lif_object~exists.
DATA: ls_msg TYPE hier_mess,
ls_header TYPE ttree,
ls_tadir TYPE tadir.
CALL FUNCTION 'STREE_STRUCTURE_EXIST'
EXPORTING
structure_id = mv_tree_id
do_not_read_devclass = ''
IMPORTING
message = ls_msg
structure_header = ls_header
structure_tadir = ls_tadir.
rv_bool = boolc( ls_header-id IS NOT INITIAL ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~delete.
CALL FUNCTION 'BMENU_DELETE_TREE'
EXPORTING
tree_id = mv_tree_id
EXCEPTIONS
trees_do_not_exist = 1
no_authority = 2
canceled = 3
OTHERS = 4.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from BMENU_DELETE_TREE, SHI3' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~serialize.
DATA: ls_msg TYPE hier_mess,
ls_head TYPE ttree,
lt_titles TYPE TABLE OF ttreet,
lt_nodes TYPE TABLE OF hier_iface,
lt_texts TYPE TABLE OF hier_texts,
lt_refs TYPE TABLE OF hier_ref.
CALL FUNCTION 'STREE_STRUCTURE_READ'
EXPORTING
structure_id = mv_tree_id
IMPORTING
message = ls_msg
structure_header = ls_head
TABLES
description = lt_titles.
CALL FUNCTION 'STREE_HIERARCHY_READ'
EXPORTING
structure_id = mv_tree_id
read_also_texts = 'X'
all_languages = 'X'
IMPORTING
message = ls_msg
TABLES
list_of_nodes = lt_nodes
list_of_references = lt_refs
list_of_texts = lt_texts.
strip_stamps( CHANGING cs_head = ls_head
ct_nodes = lt_nodes ).
io_xml->add( iv_name = 'TREE_HEAD'
ig_data = ls_head ).
io_xml->add( iv_name = 'TREE_TITLES'
ig_data = lt_titles ).
io_xml->add( iv_name = 'TREE_NODES'
ig_data = lt_nodes ).
io_xml->add( iv_name = 'TREE_REFS'
ig_data = lt_refs ).
io_xml->add( iv_name = 'TREE_TEXTS'
ig_data = lt_texts ).
ENDMETHOD. "serialize
METHOD strip_stamps.
FIELD-SYMBOLS <ls_node> LIKE LINE OF ct_nodes.
CLEAR: cs_head-luser, cs_head-ldate, cs_head-ltime.
CLEAR: cs_head-fuser, cs_head-fdate, cs_head-ftime.
CLEAR: cs_head-responsibl.
LOOP AT ct_nodes ASSIGNING <ls_node>.
CLEAR: <ls_node>-luser, <ls_node>-ldate, <ls_node>-ltime.
CLEAR: <ls_node>-fuser, <ls_node>-fdate, <ls_node>-ftime.
ENDLOOP.
ENDMETHOD. "strip_stamps
METHOD regenerate_ids.
DATA: ls_uid TYPE sys_uid,
lt_map TYPE tt_id_map.
FIELD-SYMBOLS: <ls_node> LIKE LINE OF ct_nodes,
<ls_ref> LIKE LINE OF ct_refs,
<ls_text> LIKE LINE OF ct_texts,
<ls_map> LIKE LINE OF mt_map.
"Build map
LOOP AT ct_nodes ASSIGNING <ls_node>.
APPEND INITIAL LINE TO lt_map ASSIGNING <ls_map>.
IF <ls_node>-parent_id IS INITIAL.
<ls_map>-old = <ls_node>-node_id.
<ls_map>-new = <ls_node>-node_id. "Root node
ELSE.
CALL FUNCTION 'STREE_GET_UNIQUE_ID'
IMPORTING
unique_id = ls_uid.
<ls_map>-old = <ls_node>-node_id.
<ls_map>-new = ls_uid-id.
ENDIF.
<ls_node>-node_id = <ls_map>-new. "Replace id
ENDLOOP.
mt_map = lt_map. "Sort
LOOP AT ct_nodes ASSIGNING <ls_node>.
<ls_node>-parent_id = replace_id( <ls_node>-parent_id ).
<ls_node>-brother_id = replace_id( <ls_node>-brother_id ).
ENDLOOP.
LOOP AT ct_refs ASSIGNING <ls_ref>.
<ls_ref>-node_id = replace_id( <ls_ref>-node_id ).
ENDLOOP.
LOOP AT ct_texts ASSIGNING <ls_text>.
<ls_text>-node_id = replace_id( <ls_text>-node_id ).
ENDLOOP.
ENDMETHOD. "regenerate_ids
METHOD replace_id.
DATA ls_map LIKE LINE OF mt_map.
IF iv_id IS INITIAL.
RETURN. "No substitution for empty values
ENDIF.
READ TABLE mt_map WITH TABLE KEY old = iv_id INTO ls_map.
IF sy-subrc <> 0.
lcx_exception=>raise( 'Cannot replace id, SHI3' ).
ENDIF.
rv_new_id = ls_map-new.
ENDMETHOD. "replace_id
METHOD lif_object~deserialize.
DATA: ls_msg TYPE hier_mess,
ls_head TYPE ttree,
lt_titles TYPE TABLE OF ttreet,
lt_nodes TYPE TABLE OF hier_iface,
lt_texts TYPE TABLE OF hier_texts,
lt_refs TYPE TABLE OF hier_ref.
io_xml->read( EXPORTING iv_name = 'TREE_HEAD'
CHANGING cg_data = ls_head ).
io_xml->read( EXPORTING iv_name = 'TREE_TITLES'
CHANGING cg_data = lt_titles ).
io_xml->read( EXPORTING iv_name = 'TREE_NODES'
CHANGING cg_data = lt_nodes ).
io_xml->read( EXPORTING iv_name = 'TREE_REFS'
CHANGING cg_data = lt_refs ).
io_xml->read( EXPORTING iv_name = 'TREE_TEXTS'
CHANGING cg_data = lt_texts ).
regenerate_ids( CHANGING ct_nodes = lt_nodes
ct_refs = lt_refs
ct_texts = lt_texts ).
IF lif_object~exists( ) = abap_true.
lif_object~delete( ).
ENDIF.
CALL FUNCTION 'STREE_HIERARCHY_SAVE'
EXPORTING
structure_id = mv_tree_id
structure_type = 'BMENU'
structure_description = space
structure_masterlanguage = mv_language
structure_responsible = sy-uname
development_class = iv_package
IMPORTING
message = ls_msg
TABLES
list_of_nodes = lt_nodes
list_of_references = lt_refs
list_of_texts = lt_texts
structure_descriptions = lt_titles
EXCEPTIONS
no_nodes_given = 1
OTHERS = 2.
IF sy-subrc <> 0.
lcx_exception=>raise( 'Error from STREE_HIERARCHY_SAVE, SHI3' ).
ENDIF.
ENDMETHOD. "deserialize
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_null_comparison_result.
ENDMETHOD.
ENDCLASS. "lcl_object_shi3 IMPLEMENTATION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_SHI3
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_shi3 DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_object_shi3 DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
METHODS constructor
IMPORTING
is_item TYPE ty_item
iv_language TYPE spras.
PRIVATE SECTION.
TYPES: BEGIN OF ty_id_map,
old TYPE ttree-id,
new TYPE ttree-id,
END OF ty_id_map.
TYPES tt_id_map TYPE STANDARD TABLE OF ty_id_map.
TYPES ts_id_map TYPE SORTED TABLE OF ty_id_map WITH UNIQUE KEY old.
DATA: mv_tree_id TYPE ttree-id,
mt_map TYPE ts_id_map. " SORTED !
METHODS jump_se43
RAISING lcx_exception.
METHODS clear_fields
CHANGING cs_head TYPE ttree
ct_nodes TYPE hier_iface_t.
* METHODS regenerate_ids
* CHANGING ct_nodes TYPE hier_iface_t
* ct_refs TYPE hier_ref_t
* ct_texts TYPE hier_texts_t
* RAISING lcx_exception.
*
* METHODS replace_id
* IMPORTING iv_id TYPE clike
* RETURNING VALUE(rv_new_id) TYPE ttree-id
* RAISING lcx_exception.
ENDCLASS. "lcl_object_shi3 DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_shi3 IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS lcl_object_shi3 IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
DATA: ls_head TYPE ttree.
CALL FUNCTION 'STREE_STRUCTURE_READ'
EXPORTING
structure_id = mv_tree_id
IMPORTING
structure_header = ls_head.
rv_user = ls_head-luser.
ENDMETHOD.
METHOD constructor.
super->constructor( is_item = is_item iv_language = iv_language ).
mv_tree_id = ms_item-obj_name.
ENDMETHOD. "constructor
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD jump_se43.
DATA: lt_bdcdata TYPE TABLE OF bdcdata.
FIELD-SYMBOLS: <ls_bdcdata> LIKE LINE OF lt_bdcdata.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-program = 'SAPLBMEN'.
<ls_bdcdata>-dynpro = '0200'.
<ls_bdcdata>-dynbegin = abap_true.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'BDC_OKCODE'.
<ls_bdcdata>-fval = '=SHOW'.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'BMENUNAME-ID'.
<ls_bdcdata>-fval = ms_item-obj_name.
CALL FUNCTION 'ABAP4_CALL_TRANSACTION'
STARTING NEW TASK 'GIT'
EXPORTING
tcode = 'SE43'
mode_val = 'E'
TABLES
using_tab = lt_bdcdata
EXCEPTIONS
system_failure = 1
communication_failure = 2
resource_failure = 3
OTHERS = 4.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from ABAP4_CALL_TRANSACTION, SHI3' ).
ENDIF.
ENDMETHOD. "jump_se43
METHOD lif_object~jump.
jump_se43( ).
ENDMETHOD. "jump
METHOD lif_object~exists.
DATA: ls_msg TYPE hier_mess,
ls_header TYPE ttree,
ls_tadir TYPE tadir.
CALL FUNCTION 'STREE_STRUCTURE_EXIST'
EXPORTING
structure_id = mv_tree_id
do_not_read_devclass = ''
IMPORTING
message = ls_msg
structure_header = ls_header
structure_tadir = ls_tadir.
rv_bool = boolc( ls_header-id IS NOT INITIAL ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~delete.
CALL FUNCTION 'BMENU_DELETE_TREE'
EXPORTING
tree_id = mv_tree_id
EXCEPTIONS
trees_do_not_exist = 1
no_authority = 2
canceled = 3
OTHERS = 4.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from BMENU_DELETE_TREE, SHI3' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~serialize.
DATA: ls_msg TYPE hier_mess,
ls_head TYPE ttree,
lt_titles TYPE TABLE OF ttreet,
lt_nodes TYPE TABLE OF hier_iface,
lt_texts TYPE TABLE OF hier_texts,
lt_refs TYPE TABLE OF hier_ref.
CALL FUNCTION 'STREE_STRUCTURE_READ'
EXPORTING
structure_id = mv_tree_id
IMPORTING
message = ls_msg
structure_header = ls_head
TABLES
description = lt_titles.
CALL FUNCTION 'STREE_HIERARCHY_READ'
EXPORTING
structure_id = mv_tree_id
read_also_texts = 'X'
all_languages = 'X'
IMPORTING
message = ls_msg
TABLES
list_of_nodes = lt_nodes
list_of_references = lt_refs
list_of_texts = lt_texts.
clear_fields( CHANGING cs_head = ls_head
ct_nodes = lt_nodes ).
io_xml->add( iv_name = 'TREE_HEAD'
ig_data = ls_head ).
io_xml->add( iv_name = 'TREE_TITLES'
ig_data = lt_titles ).
io_xml->add( iv_name = 'TREE_NODES'
ig_data = lt_nodes ).
io_xml->add( iv_name = 'TREE_REFS'
ig_data = lt_refs ).
io_xml->add( iv_name = 'TREE_TEXTS'
ig_data = lt_texts ).
ENDMETHOD. "serialize
METHOD clear_fields.
FIELD-SYMBOLS <ls_node> LIKE LINE OF ct_nodes.
CLEAR: cs_head-luser, cs_head-ldate, cs_head-ltime.
CLEAR: cs_head-fuser, cs_head-fdate, cs_head-ftime.
CLEAR: cs_head-frelease, cs_head-lrelease.
CLEAR: cs_head-responsibl.
LOOP AT ct_nodes ASSIGNING <ls_node>.
CLEAR: <ls_node>-luser, <ls_node>-ldate, <ls_node>-ltime.
CLEAR: <ls_node>-fuser, <ls_node>-fdate, <ls_node>-ftime.
CLEAR: <ls_node>-frelease, <ls_node>-lrelease.
ENDLOOP.
ENDMETHOD. "strip_stamps
* METHOD regenerate_ids.
*
* DATA: ls_uid TYPE sys_uid,
* lt_map TYPE tt_id_map.
*
* FIELD-SYMBOLS: <ls_node> LIKE LINE OF ct_nodes,
* <ls_ref> LIKE LINE OF ct_refs,
* <ls_text> LIKE LINE OF ct_texts,
* <ls_map> LIKE LINE OF mt_map.
*
* "Build map
* LOOP AT ct_nodes ASSIGNING <ls_node>.
* APPEND INITIAL LINE TO lt_map ASSIGNING <ls_map>.
* IF <ls_node>-parent_id IS INITIAL.
* <ls_map>-old = <ls_node>-node_id.
* <ls_map>-new = <ls_node>-node_id. "Root node
* ELSE.
* CALL FUNCTION 'STREE_GET_UNIQUE_ID'
* IMPORTING
* unique_id = ls_uid.
*
* <ls_map>-old = <ls_node>-node_id.
* <ls_map>-new = ls_uid-id.
* ENDIF.
* <ls_node>-node_id = <ls_map>-new. "Replace id
* ENDLOOP.
*
* mt_map = lt_map. "Sort
*
* LOOP AT ct_nodes ASSIGNING <ls_node>.
* <ls_node>-parent_id = replace_id( <ls_node>-parent_id ).
* <ls_node>-brother_id = replace_id( <ls_node>-brother_id ).
* ENDLOOP.
*
* LOOP AT ct_refs ASSIGNING <ls_ref>.
* <ls_ref>-node_id = replace_id( <ls_ref>-node_id ).
* ENDLOOP.
*
* LOOP AT ct_texts ASSIGNING <ls_text>.
* <ls_text>-node_id = replace_id( <ls_text>-node_id ).
* ENDLOOP.
*
* ENDMETHOD. "regenerate_ids
*
* METHOD replace_id.
*
* DATA ls_map LIKE LINE OF mt_map.
*
* IF iv_id IS INITIAL.
* RETURN. "No substitution for empty values
* ENDIF.
*
* READ TABLE mt_map WITH TABLE KEY old = iv_id INTO ls_map.
* IF sy-subrc <> 0.
* lcx_exception=>raise( 'Cannot replace id, SHI3' ).
* ENDIF.
*
* rv_new_id = ls_map-new.
*
* ENDMETHOD. "replace_id
METHOD lif_object~deserialize.
DATA: ls_msg TYPE hier_mess,
ls_head TYPE ttree,
lt_titles TYPE TABLE OF ttreet,
lt_nodes TYPE TABLE OF hier_iface,
lt_texts TYPE TABLE OF hier_texts,
lt_refs TYPE TABLE OF hier_ref.
io_xml->read( EXPORTING iv_name = 'TREE_HEAD'
CHANGING cg_data = ls_head ).
io_xml->read( EXPORTING iv_name = 'TREE_TITLES'
CHANGING cg_data = lt_titles ).
io_xml->read( EXPORTING iv_name = 'TREE_NODES'
CHANGING cg_data = lt_nodes ).
io_xml->read( EXPORTING iv_name = 'TREE_REFS'
CHANGING cg_data = lt_refs ).
io_xml->read( EXPORTING iv_name = 'TREE_TEXTS'
CHANGING cg_data = lt_texts ).
* regenerate_ids( CHANGING ct_nodes = lt_nodes
* ct_refs = lt_refs
* ct_texts = lt_texts ).
IF lif_object~exists( ) = abap_true.
lif_object~delete( ).
ENDIF.
CALL FUNCTION 'STREE_HIERARCHY_SAVE'
EXPORTING
structure_id = mv_tree_id
structure_type = 'BMENU'
structure_description = space
structure_masterlanguage = mv_language
structure_responsible = sy-uname
development_class = iv_package
IMPORTING
message = ls_msg
TABLES
list_of_nodes = lt_nodes
list_of_references = lt_refs
list_of_texts = lt_texts
structure_descriptions = lt_titles
EXCEPTIONS
no_nodes_given = 1
OTHERS = 2.
IF sy-subrc <> 0.
lcx_exception=>raise( 'Error from STREE_HIERARCHY_SAVE, SHI3' ).
ENDIF.
ENDMETHOD. "deserialize
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_null_comparison_result.
ENDMETHOD.
ENDCLASS. "lcl_object_shi3 IMPLEMENTATION
|
fix SHI3 diffs #483
|
fix SHI3 diffs #483
|
ABAP
|
mit
|
larshp/abapGit,larshp/abapGit,EduardoCopat/abapGit,apex8/abapGit,sbcgua/abapGit,apex8/abapGit,EduardoCopat/abapGit,sbcgua/abapGit
|
f8f46c4f9e36239e259622e163298096bb2d1da2
|
src/zabapgit_sap_package.prog.abap
|
src/zabapgit_sap_package.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_SAP_PACKAGE
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_package DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_sap_package DEFINITION FINAL.
PUBLIC SECTION.
TYPES: ty_devclass_tt TYPE STANDARD TABLE OF devclass WITH DEFAULT KEY.
CLASS-METHODS:
check
IMPORTING io_log TYPE REF TO lcl_log
it_results TYPE ty_results_tt
iv_start TYPE string
iv_top TYPE devclass,
list_subpackages IMPORTING iv_package TYPE devclass
RETURNING VALUE(rt_list) TYPE ty_devclass_tt,
list_superpackages IMPORTING iv_package TYPE devclass
RETURNING VALUE(rt_list) TYPE ty_devclass_tt,
create_local
IMPORTING iv_package TYPE devclass
RAISING lcx_exception,
create
IMPORTING is_package TYPE scompkdtln
RETURNING VALUE(ri_package) TYPE REF TO if_package
RAISING lcx_exception,
create_child
IMPORTING iv_parent TYPE devclass
iv_child TYPE devclass
RAISING lcx_exception,
exists
IMPORTING iv_package TYPE devclass
RETURNING VALUE(rv_bool) TYPE abap_bool.
PRIVATE SECTION.
CLASS-METHODS:
class_to_path
IMPORTING
iv_top TYPE devclass
iv_start TYPE string
iv_package TYPE devclass
RETURNING
VALUE(rv_path) TYPE string.
ENDCLASS. "lcl_package DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_package IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_sap_package IMPLEMENTATION.
METHOD class_to_path.
DATA: lv_len TYPE i,
lv_path TYPE string,
lv_parentcl TYPE tdevc-parentcl.
IF iv_top = iv_package.
rv_path = iv_start.
ELSE.
SELECT SINGLE parentcl FROM tdevc INTO lv_parentcl
WHERE devclass = iv_package. "#EC CI_SUBRC "#EC CI_GENBUFF
ASSERT sy-subrc = 0.
IF lv_parentcl IS INITIAL.
rv_path = 'error' ##no_text.
ELSE.
lv_len = strlen( lv_parentcl ).
lv_path = iv_package+lv_len.
IF strlen( lv_path ) = 0.
RETURN. " prevent dump
ENDIF.
IF lv_path(1) = '_'.
lv_path = lv_path+1.
ENDIF.
TRANSLATE lv_path TO LOWER CASE.
CONCATENATE lv_path '/' INTO lv_path.
rv_path = class_to_path( iv_top = iv_top
iv_start = iv_start
iv_package = lv_parentcl ).
CONCATENATE rv_path lv_path INTO rv_path.
ENDIF.
ENDIF.
ENDMETHOD. "class_to_path
METHOD check.
DATA: lv_path TYPE string,
ls_item TYPE ty_item,
ls_file TYPE ty_file_signature,
lt_res_sort LIKE it_results,
lt_item_idx LIKE it_results.
FIELD-SYMBOLS: <ls_res1> LIKE LINE OF it_results,
<ls_res2> LIKE LINE OF it_results.
IF io_log IS INITIAL.
RETURN.
ENDIF.
" Collect object indexe
lt_res_sort = it_results.
SORT lt_res_sort BY obj_type ASCENDING obj_name ASCENDING.
LOOP AT it_results ASSIGNING <ls_res1> WHERE NOT obj_type IS INITIAL.
IF NOT ( <ls_res1>-obj_type = ls_item-obj_type AND <ls_res1>-obj_name = ls_item-obj_name ).
APPEND INITIAL LINE TO lt_item_idx ASSIGNING <ls_res2>.
<ls_res2>-obj_type = <ls_res1>-obj_type.
<ls_res2>-obj_name = <ls_res1>-obj_name.
<ls_res2>-path = <ls_res1>-path.
MOVE-CORRESPONDING <ls_res1> TO ls_item.
ENDIF.
ENDLOOP.
" Check files for one object is in the same folder
LOOP AT it_results ASSIGNING <ls_res1> WHERE NOT obj_type IS INITIAL.
READ TABLE lt_item_idx ASSIGNING <ls_res2>
WITH KEY obj_type = <ls_res1>-obj_type obj_name = <ls_res1>-obj_name
BINARY SEARCH. " Sorted above
IF sy-subrc <> 0 OR <ls_res1>-path <> <ls_res2>-path. " All paths are same
io_log->add( iv_msgv1 = 'Files for object'
iv_msgv2 = <ls_res1>-obj_type
iv_msgv3 = <ls_res1>-obj_name
iv_msgv4 = 'are not placed in the same folder'
iv_rc = '1' ) ##no_text.
ENDIF.
ENDLOOP.
" Check that objects are created in package corresponding to folder
LOOP AT it_results ASSIGNING <ls_res1>
WHERE NOT package IS INITIAL AND NOT path IS INITIAL.
lv_path = class_to_path( iv_top = iv_top
iv_start = iv_start
iv_package = <ls_res1>-package ).
IF lv_path <> <ls_res1>-path.
io_log->add( iv_msgv1 = 'Package and path does not match for object,'
iv_msgv2 = <ls_res1>-obj_type
iv_msgv3 = <ls_res1>-obj_name
iv_rc = '2' ) ##no_text.
ENDIF.
ENDLOOP.
" Check for multiple files with same filename
SORT lt_res_sort BY filename ASCENDING.
LOOP AT lt_res_sort ASSIGNING <ls_res1>.
IF <ls_res1>-filename IS NOT INITIAL AND <ls_res1>-filename = ls_file-filename.
io_log->add( iv_msgv1 = 'Multiple files with same filename,'
iv_msgv2 = <ls_res1>-filename
iv_rc = '3' ) ##no_text.
ENDIF.
IF <ls_res1>-filename IS INITIAL.
io_log->add( iv_msgv1 = 'Filename is empty for object'
iv_msgv2 = <ls_res1>-obj_type
iv_msgv3 = <ls_res1>-obj_name
iv_rc = '4' ) ##no_text.
ENDIF.
MOVE-CORRESPONDING <ls_res1> TO ls_file.
ENDLOOP.
ENDMETHOD. "check
METHOD exists.
cl_package_factory=>load_package(
EXPORTING
i_package_name = iv_package
EXCEPTIONS
object_not_existing = 1
unexpected_error = 2
intern_err = 3
no_access = 4
object_locked_and_modified = 5 ).
rv_bool = boolc( sy-subrc <> 1 ).
ENDMETHOD.
METHOD create_child.
DATA: li_parent TYPE REF TO if_package,
ls_child TYPE scompkdtln.
cl_package_factory=>load_package(
EXPORTING
i_package_name = iv_parent
IMPORTING
e_package = li_parent
EXCEPTIONS
object_not_existing = 1
unexpected_error = 2
intern_err = 3
no_access = 4
object_locked_and_modified = 5 ).
IF sy-subrc <> 0.
lcx_exception=>raise( 'error reading parent package' ).
ENDIF.
ls_child-devclass = iv_child.
ls_child-ctext = iv_child.
ls_child-parentcl = iv_parent.
ls_child-component = li_parent->transport_layer.
ls_child-as4user = sy-uname.
create( ls_child ).
ENDMETHOD.
METHOD create.
DATA: lv_err TYPE string,
ls_package LIKE is_package.
ASSERT NOT is_package-devclass IS INITIAL.
cl_package_factory=>load_package(
EXPORTING
i_package_name = is_package-devclass
EXCEPTIONS
object_not_existing = 1
unexpected_error = 2
intern_err = 3
no_access = 4
object_locked_and_modified = 5 ).
IF sy-subrc = 0.
RETURN. "Package already exists. We assume this is fine
ENDIF.
ls_package = is_package.
cl_package_factory=>create_new_package(
EXPORTING
i_reuse_deleted_object = abap_true
* i_suppress_dialog = abap_true " does not exist in 730
IMPORTING
e_package = ri_package
CHANGING
c_package_data = ls_package
EXCEPTIONS
object_already_existing = 1
object_just_created = 2
not_authorized = 3
wrong_name_prefix = 4
undefined_name = 5
reserved_local_name = 6
invalid_package_name = 7
short_text_missing = 8
software_component_invalid = 9
layer_invalid = 10
author_not_existing = 11
component_not_existing = 12
component_missing = 13
prefix_in_use = 14
unexpected_error = 15
intern_err = 16
no_access = 17
* invalid_translation_depth = 18
* wrong_mainpack_value = 19
* superpackage_invalid = 20
* error_in_cts_checks = 21
OTHERS = 18 ).
IF sy-subrc <> 0.
lcx_exception=>raise( |Package { is_package-devclass } could not be created| ).
ENDIF.
ri_package->save(
* EXPORTING
* i_suppress_dialog = abap_true " Controls whether popups can be transmitted
EXCEPTIONS
object_invalid = 1
object_not_changeable = 2
cancelled_in_corr = 3
permission_failure = 4
unexpected_error = 5
intern_err = 6
OTHERS = 7 ).
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 INTO lv_err.
lcx_exception=>raise( lv_err ).
ENDIF.
ri_package->set_changeable( abap_false ).
ENDMETHOD.
METHOD list_superpackages.
DATA: lt_list LIKE rt_list,
lv_parent TYPE tdevc-parentcl,
lv_devclass LIKE LINE OF rt_list.
APPEND iv_package TO rt_list.
SELECT SINGLE parentcl INTO lv_parent
FROM tdevc WHERE devclass = iv_package. "#EC CI_GENBUFF
IF NOT lv_parent IS INITIAL.
APPEND lv_parent TO rt_list.
lt_list = list_superpackages( lv_devclass ).
APPEND LINES OF lt_list TO rt_list.
ENDIF.
ENDMETHOD.
METHOD list_subpackages.
DATA: lt_list LIKE rt_list,
lv_devclass LIKE LINE OF rt_list.
SELECT devclass INTO TABLE rt_list
FROM tdevc WHERE parentcl = iv_package. "#EC CI_GENBUFF
* note the recursion, since packages are added to the list
LOOP AT rt_list INTO lv_devclass.
lt_list = list_subpackages( lv_devclass ).
APPEND LINES OF lt_list TO rt_list.
ENDLOOP.
ENDMETHOD.
METHOD create_local.
DATA: ls_package TYPE scompkdtln.
ls_package-devclass = iv_package.
ls_package-ctext = iv_package.
ls_package-parentcl = '$TMP'.
ls_package-component = 'LOCAL'.
ls_package-as4user = sy-uname.
create( ls_package ).
ENDMETHOD. "create
ENDCLASS. "lcl_package IMPLEMENTATION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_SAP_PACKAGE
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_package DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_sap_package DEFINITION FINAL.
PUBLIC SECTION.
TYPES: ty_devclass_tt TYPE STANDARD TABLE OF devclass WITH DEFAULT KEY.
CLASS-METHODS:
check
IMPORTING io_log TYPE REF TO lcl_log
it_results TYPE ty_results_tt
iv_start TYPE string
iv_top TYPE devclass,
list_subpackages IMPORTING iv_package TYPE devclass
RETURNING VALUE(rt_list) TYPE ty_devclass_tt,
list_superpackages IMPORTING iv_package TYPE devclass
RETURNING VALUE(rt_list) TYPE ty_devclass_tt,
create_local
IMPORTING iv_package TYPE devclass
RAISING lcx_exception,
create
IMPORTING is_package TYPE scompkdtln
RETURNING VALUE(ri_package) TYPE REF TO if_package
RAISING lcx_exception,
create_child
IMPORTING iv_parent TYPE devclass
iv_child TYPE devclass
RAISING lcx_exception,
exists
IMPORTING iv_package TYPE devclass
RETURNING VALUE(rv_bool) TYPE abap_bool.
PRIVATE SECTION.
CLASS-METHODS:
class_to_path
IMPORTING
iv_top TYPE devclass
iv_start TYPE string
iv_package TYPE devclass
RETURNING
VALUE(rv_path) TYPE string.
ENDCLASS. "lcl_package DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_package IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_sap_package IMPLEMENTATION.
METHOD class_to_path.
DATA: lv_len TYPE i,
lv_path TYPE string,
lv_parentcl TYPE tdevc-parentcl.
IF iv_top = iv_package.
rv_path = iv_start.
ELSE.
SELECT SINGLE parentcl FROM tdevc INTO lv_parentcl
WHERE devclass = iv_package. "#EC CI_SUBRC "#EC CI_GENBUFF
ASSERT sy-subrc = 0.
IF lv_parentcl IS INITIAL.
rv_path = 'error' ##no_text.
ELSE.
lv_len = strlen( lv_parentcl ).
lv_path = iv_package+lv_len.
IF strlen( lv_path ) = 0.
RETURN. " prevent dump
ENDIF.
IF lv_path(1) = '_'.
lv_path = lv_path+1.
ENDIF.
TRANSLATE lv_path TO LOWER CASE.
CONCATENATE lv_path '/' INTO lv_path.
rv_path = class_to_path( iv_top = iv_top
iv_start = iv_start
iv_package = lv_parentcl ).
CONCATENATE rv_path lv_path INTO rv_path.
ENDIF.
ENDIF.
ENDMETHOD. "class_to_path
METHOD check.
DATA: lv_path TYPE string,
ls_item TYPE ty_item,
ls_file TYPE ty_file_signature,
lt_res_sort LIKE it_results,
lt_item_idx LIKE it_results.
FIELD-SYMBOLS: <ls_res1> LIKE LINE OF it_results,
<ls_res2> LIKE LINE OF it_results.
IF io_log IS INITIAL.
RETURN.
ENDIF.
" Collect object indexe
lt_res_sort = it_results.
SORT lt_res_sort BY obj_type ASCENDING obj_name ASCENDING.
LOOP AT it_results ASSIGNING <ls_res1> WHERE NOT obj_type IS INITIAL.
IF NOT ( <ls_res1>-obj_type = ls_item-obj_type AND <ls_res1>-obj_name = ls_item-obj_name ).
APPEND INITIAL LINE TO lt_item_idx ASSIGNING <ls_res2>.
<ls_res2>-obj_type = <ls_res1>-obj_type.
<ls_res2>-obj_name = <ls_res1>-obj_name.
<ls_res2>-path = <ls_res1>-path.
MOVE-CORRESPONDING <ls_res1> TO ls_item.
ENDIF.
ENDLOOP.
" Check files for one object is in the same folder
LOOP AT it_results ASSIGNING <ls_res1> WHERE NOT obj_type IS INITIAL.
READ TABLE lt_item_idx ASSIGNING <ls_res2>
WITH KEY obj_type = <ls_res1>-obj_type obj_name = <ls_res1>-obj_name
BINARY SEARCH. " Sorted above
IF sy-subrc <> 0 OR <ls_res1>-path <> <ls_res2>-path. " All paths are same
io_log->add( iv_msgv1 = 'Files for object'
iv_msgv2 = <ls_res1>-obj_type
iv_msgv3 = <ls_res1>-obj_name
iv_msgv4 = 'are not placed in the same folder'
iv_rc = '1' ) ##no_text.
ENDIF.
ENDLOOP.
" Check that objects are created in package corresponding to folder
LOOP AT it_results ASSIGNING <ls_res1>
WHERE NOT package IS INITIAL AND NOT path IS INITIAL.
lv_path = class_to_path( iv_top = iv_top
iv_start = iv_start
iv_package = <ls_res1>-package ).
IF lv_path <> <ls_res1>-path.
io_log->add( iv_msgv1 = 'Package and path does not match for object,'
iv_msgv2 = <ls_res1>-obj_type
iv_msgv3 = <ls_res1>-obj_name
iv_rc = '2' ) ##no_text.
ENDIF.
ENDLOOP.
" Check for multiple files with same filename
SORT lt_res_sort BY filename ASCENDING.
LOOP AT lt_res_sort ASSIGNING <ls_res1>.
IF <ls_res1>-filename IS NOT INITIAL AND <ls_res1>-filename = ls_file-filename.
io_log->add( iv_msgv1 = 'Multiple files with same filename,'
iv_msgv2 = <ls_res1>-filename
iv_rc = '3' ) ##no_text.
ENDIF.
IF <ls_res1>-filename IS INITIAL.
io_log->add( iv_msgv1 = 'Filename is empty for object'
iv_msgv2 = <ls_res1>-obj_type
iv_msgv3 = <ls_res1>-obj_name
iv_rc = '4' ) ##no_text.
ENDIF.
MOVE-CORRESPONDING <ls_res1> TO ls_file.
ENDLOOP.
ENDMETHOD. "check
METHOD exists.
cl_package_factory=>load_package(
EXPORTING
i_package_name = iv_package
EXCEPTIONS
object_not_existing = 1
unexpected_error = 2
intern_err = 3
no_access = 4
object_locked_and_modified = 5 ).
rv_bool = boolc( sy-subrc <> 1 ).
ENDMETHOD.
METHOD create_child.
DATA: li_parent TYPE REF TO if_package,
ls_child TYPE scompkdtln.
cl_package_factory=>load_package(
EXPORTING
i_package_name = iv_parent
IMPORTING
e_package = li_parent
EXCEPTIONS
object_not_existing = 1
unexpected_error = 2
intern_err = 3
no_access = 4
object_locked_and_modified = 5 ).
IF sy-subrc <> 0.
lcx_exception=>raise( 'error reading parent package' ).
ENDIF.
ls_child-devclass = iv_child.
ls_child-dlvunit = li_parent->software_component.
ls_child-ctext = iv_child.
ls_child-parentcl = iv_parent.
ls_child-pdevclass = li_parent->transport_layer.
ls_child-as4user = sy-uname.
create( ls_child ).
ENDMETHOD.
METHOD create.
DATA: lv_err TYPE string,
ls_package LIKE is_package.
ASSERT NOT is_package-devclass IS INITIAL.
cl_package_factory=>load_package(
EXPORTING
i_package_name = is_package-devclass
EXCEPTIONS
object_not_existing = 1
unexpected_error = 2
intern_err = 3
no_access = 4
object_locked_and_modified = 5 ).
IF sy-subrc = 0.
RETURN. "Package already exists. We assume this is fine
ENDIF.
ls_package = is_package.
" Set software component to 'HOME' if none is set at this point.
" Otherwise SOFTWARE_COMPONENT_INVALID will be raised.
IF ls_package-dlvunit IS INITIAL.
ls_package-dlvunit = 'HOME'.
ENDIF.
cl_package_factory=>create_new_package(
EXPORTING
i_reuse_deleted_object = abap_true
* i_suppress_dialog = abap_true " does not exist in 730
IMPORTING
e_package = ri_package
CHANGING
c_package_data = ls_package
EXCEPTIONS
object_already_existing = 1
object_just_created = 2
not_authorized = 3
wrong_name_prefix = 4
undefined_name = 5
reserved_local_name = 6
invalid_package_name = 7
short_text_missing = 8
software_component_invalid = 9
layer_invalid = 10
author_not_existing = 11
component_not_existing = 12
component_missing = 13
prefix_in_use = 14
unexpected_error = 15
intern_err = 16
no_access = 17
* invalid_translation_depth = 18
* wrong_mainpack_value = 19
* superpackage_invalid = 20
* error_in_cts_checks = 21
OTHERS = 18 ).
IF sy-subrc <> 0.
lcx_exception=>raise( |Package { is_package-devclass } could not be created| ).
ENDIF.
ri_package->save(
* EXPORTING
* i_suppress_dialog = abap_true " Controls whether popups can be transmitted
EXCEPTIONS
object_invalid = 1
object_not_changeable = 2
cancelled_in_corr = 3
permission_failure = 4
unexpected_error = 5
intern_err = 6
OTHERS = 7 ).
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 INTO lv_err.
lcx_exception=>raise( lv_err ).
ENDIF.
ri_package->set_changeable( abap_false ).
ENDMETHOD.
METHOD list_superpackages.
DATA: lt_list LIKE rt_list,
lv_parent TYPE tdevc-parentcl,
lv_devclass LIKE LINE OF rt_list.
APPEND iv_package TO rt_list.
SELECT SINGLE parentcl INTO lv_parent
FROM tdevc WHERE devclass = iv_package. "#EC CI_GENBUFF
IF NOT lv_parent IS INITIAL.
APPEND lv_parent TO rt_list.
lt_list = list_superpackages( lv_devclass ).
APPEND LINES OF lt_list TO rt_list.
ENDIF.
ENDMETHOD.
METHOD list_subpackages.
DATA: lt_list LIKE rt_list,
lv_devclass LIKE LINE OF rt_list.
SELECT devclass INTO TABLE rt_list
FROM tdevc WHERE parentcl = iv_package. "#EC CI_GENBUFF
* note the recursion, since packages are added to the list
LOOP AT rt_list INTO lv_devclass.
lt_list = list_subpackages( lv_devclass ).
APPEND LINES OF lt_list TO rt_list.
ENDLOOP.
ENDMETHOD.
METHOD create_local.
DATA: ls_package TYPE scompkdtln.
ls_package-devclass = iv_package.
ls_package-ctext = iv_package.
ls_package-parentcl = '$TMP'.
ls_package-dlvunit = 'LOCAL'.
ls_package-as4user = sy-uname.
create( ls_package ).
ENDMETHOD. "create
ENDCLASS. "lcl_package IMPLEMENTATION
|
Fix missing software component for subpackages
|
Fix missing software component for subpackages
|
ABAP
|
mit
|
sbcgua/abapGit,sbcgua/abapGit,apex8/abapGit,larshp/abapGit,apex8/abapGit,EduardoCopat/abapGit,EduardoCopat/abapGit,nununo/abapGit,nununo/abapGit,larshp/abapGit
|
0aba096bc7ddc101dc07b6d8aade064acb0ff56a
|
src/zabapgit_requirements.prog.abap
|
src/zabapgit_requirements.prog.abap
|
*&---------------------------------------------------------------------*
*& Include zabapgit_requirements
*&---------------------------------------------------------------------*
"! Helper class for checking requirements / dependencies
CLASS lcl_requirement_helper DEFINITION FINAL.
PUBLIC SECTION.
TYPES:
BEGIN OF gty_status,
met TYPE abap_bool,
component TYPE dlvunit,
description TYPE text80,
installed_release TYPE saprelease,
installed_patch TYPE sappatchlv,
required_release TYPE saprelease,
required_patch TYPE sappatchlv,
END OF gty_status,
gty_status_tab TYPE STANDARD TABLE OF gty_status WITH DEFAULT KEY.
CLASS-METHODS:
"! Check if the given requirements are met with user interaction
"! <p>
"! Shows a popup if requested and asks the user if he wants to continue if there are unmet
"! requirements. If not an exception is raised.
"! </p>
"! @parameter it_requirements | The requirements to check
"! @parameter iv_show_popup | Show popup with requirements
"! @raising lcx_exception | Cancelled by user or internal error
check_requirements IMPORTING it_requirements TYPE lcl_dot_abapgit=>ty_requirement_tab
iv_show_popup TYPE abap_bool DEFAULT abap_true
RAISING lcx_exception,
"! Get a table with information about each requirement
"! @parameter it_requirements | Requirements
"! @parameter rt_status | Result
"! @raising lcx_exception | Internal error
get_requirement_met_status IMPORTING it_requirements TYPE lcl_dot_abapgit=>ty_requirement_tab
RETURNING VALUE(rt_status) TYPE gty_status_tab
RAISING lcx_exception.
PROTECTED SECTION.
PRIVATE SECTION.
CLASS-METHODS:
show_requirement_popup IMPORTING it_requirements TYPE gty_status_tab
RAISING lcx_exception,
version_greater_or_equal IMPORTING is_status TYPE gty_status
RETURNING VALUE(rv_true) TYPE abap_bool.
ENDCLASS.
CLASS lcl_requirement_helper IMPLEMENTATION.
METHOD check_requirements.
DATA: lt_met_status TYPE gty_status_tab,
lv_answer TYPE c LENGTH 1.
lt_met_status = get_requirement_met_status( it_requirements ).
IF iv_show_popup = abap_true.
show_requirement_popup( lt_met_status ).
ENDIF.
LOOP AT lt_met_status TRANSPORTING NO FIELDS WHERE met = abap_false.
EXIT.
ENDLOOP.
IF sy-subrc = 0.
CALL FUNCTION 'POPUP_TO_CONFIRM'
EXPORTING
text_question = 'The project has unmet requirements. Install anyways?'
IMPORTING
answer = lv_answer.
IF lv_answer <> '1'.
lcx_exception=>raise( 'Cancelling because of unmet requirements.' ).
ENDIF.
ENDIF.
ENDMETHOD.
METHOD get_requirement_met_status.
DATA: lt_installed TYPE STANDARD TABLE OF cvers_sdu.
FIELD-SYMBOLS: <ls_requirement> TYPE lcl_dot_abapgit=>ty_requirement,
<ls_status> TYPE gty_status,
<ls_installed_comp> TYPE cvers_sdu.
CALL FUNCTION 'DELIVERY_GET_INSTALLED_COMPS'
TABLES
tt_comptab = lt_installed
EXCEPTIONS
no_release_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
lcx_exception=>raise( |Error from DELIVERY_GET_INSTALLED_COMPS { sy-subrc }| ) ##NO_TEXT.
ENDIF.
LOOP AT it_requirements ASSIGNING <ls_requirement>.
APPEND INITIAL LINE TO rt_status ASSIGNING <ls_status>.
<ls_status>-component = <ls_requirement>-component.
<ls_status>-required_release = <ls_requirement>-min_release.
<ls_status>-required_patch = <ls_requirement>-min_patch.
READ TABLE lt_installed WITH KEY component = <ls_requirement>-component
ASSIGNING <ls_installed_comp>.
IF sy-subrc = 0.
<ls_status>-installed_release = <ls_installed_comp>-release.
<ls_status>-installed_patch = <ls_installed_comp>-extrelease.
<ls_status>-description = <ls_installed_comp>-desc_text.
<ls_status>-met = version_greater_or_equal( <ls_status> ).
ENDIF.
UNASSIGN <ls_installed_comp>.
ENDLOOP.
ENDMETHOD.
METHOD version_greater_or_equal.
DATA: lv_number TYPE numc4.
TRY.
MOVE EXACT: is_status-installed_release TO lv_number,
is_status-installed_patch TO lv_number,
is_status-required_release TO lv_number,
is_status-required_patch TO lv_number.
CATCH cx_sy_conversion_error.
" Cannot compare by number, assume requirement not fullfilled (user can force install
" anyways if this was an error)
rv_true = abap_false.
RETURN.
ENDTRY.
" Check if versions are comparable by number
IF is_status-installed_release > is_status-required_release
OR ( is_status-installed_release = is_status-required_release
AND ( is_status-required_patch IS INITIAL OR
is_status-installed_patch >= is_status-required_patch ) ).
rv_true = abap_true.
ENDIF.
ENDMETHOD.
METHOD show_requirement_popup.
CONSTANTS: lc_color_column_name TYPE lvc_fname VALUE 'COLOR'.
DATA: lo_alv TYPE REF TO cl_salv_table,
lo_column TYPE REF TO cl_salv_column,
lr_colored_table TYPE REF TO data,
lo_tab_descr TYPE REF TO cl_abap_tabledescr,
lo_struct_descr TYPE REF TO cl_abap_structdescr,
lo_enh_struct_descr TYPE REF TO cl_abap_structdescr,
lo_enh_tab_descr TYPE REF TO cl_abap_tabledescr,
lt_comps TYPE cl_abap_structdescr=>component_table,
lt_color_neg TYPE lvc_t_scol,
lt_color_pos TYPE lvc_t_scol,
ls_color TYPE lvc_s_scol,
lx_ex TYPE REF TO cx_root.
FIELD-SYMBOLS: <ls_comp> TYPE abap_componentdescr,
<lt_pointer> TYPE STANDARD TABLE,
<lg_line> TYPE data,
<lt_color> TYPE lvc_t_scol,
<lv_met> TYPE abap_bool.
ls_color-color-col = col_negative.
APPEND ls_color TO lt_color_neg.
ls_color-color-col = col_positive.
APPEND ls_color TO lt_color_pos.
CLEAR ls_color.
lo_tab_descr ?= cl_abap_typedescr=>describe_by_data( it_requirements ).
lo_struct_descr ?= lo_tab_descr->get_table_line_type( ).
lt_comps = lo_struct_descr->get_components( ).
APPEND INITIAL LINE TO lt_comps ASSIGNING <ls_comp>.
<ls_comp>-name = lc_color_column_name.
<ls_comp>-type ?= cl_abap_typedescr=>describe_by_name( 'LVC_T_SCOL' ).
lo_enh_struct_descr = cl_abap_structdescr=>get( lt_comps ).
lo_enh_tab_descr = cl_abap_tabledescr=>get( lo_enh_struct_descr ).
CREATE DATA lr_colored_table TYPE HANDLE lo_enh_tab_descr.
ASSERT lr_colored_table IS BOUND.
ASSIGN lr_colored_table->* TO <lt_pointer>.
ASSERT <lt_pointer> IS ASSIGNED.
MOVE-CORRESPONDING it_requirements TO <lt_pointer>.
LOOP AT <lt_pointer> ASSIGNING <lg_line>.
ASSIGN COMPONENT 'MET' OF STRUCTURE <lg_line> TO <lv_met>.
ASSERT <lv_met> IS ASSIGNED.
ASSIGN COMPONENT lc_color_column_name OF STRUCTURE <lg_line> TO <lt_color>.
ASSERT <lt_color> IS ASSIGNED.
IF <lv_met> = abap_false.
<lt_color> = lt_color_neg.
ELSE.
<lt_color> = lt_color_pos.
ENDIF.
UNASSIGN: <lt_color>, <lv_met>.
ENDLOOP.
UNASSIGN <lg_line>.
TRY.
cl_salv_table=>factory(
IMPORTING
r_salv_table = lo_alv
CHANGING
t_table = <lt_pointer>
).
lo_alv->get_columns(:
)->get_column( 'MET' )->set_short_text( 'Met' ),
)->set_color_column( lc_color_column_name ),
)->set_optimize( ),
).
lo_column = lo_alv->get_columns( )->get_column( 'REQUIRED_RELEASE' ).
lo_column->set_fixed_header_text( 'S').
lo_column->set_short_text( 'Req. Rel.' ).
lo_column = lo_alv->get_columns( )->get_column( 'REQUIRED_PATCH' ).
lo_column->set_fixed_header_text( 'S').
lo_column->set_short_text( 'Req. SP L.' ).
lo_alv->set_screen_popup( start_column = 30
end_column = 100
start_line = 10
end_line = 20 ).
lo_alv->get_display_settings( )->set_list_header( 'Requirements' ).
lo_alv->display( ).
CATCH cx_salv_msg cx_salv_not_found cx_salv_data_error INTO lx_ex.
RAISE EXCEPTION TYPE lcx_exception
EXPORTING
iv_text = lx_ex->get_text( )
ix_previous = lx_ex.
ENDTRY.
ENDMETHOD.
ENDCLASS.
|
*&---------------------------------------------------------------------*
*& Include zabapgit_requirements
*&---------------------------------------------------------------------*
"! Helper class for checking requirements / dependencies
CLASS lcl_requirement_helper DEFINITION FINAL.
PUBLIC SECTION.
TYPES:
BEGIN OF gty_status,
met TYPE abap_bool,
component TYPE dlvunit,
description TYPE text80,
installed_release TYPE saprelease,
installed_patch TYPE sappatchlv,
required_release TYPE saprelease,
required_patch TYPE sappatchlv,
END OF gty_status,
gty_status_tab TYPE STANDARD TABLE OF gty_status WITH DEFAULT KEY.
CLASS-METHODS:
"! Check if the given requirements are met with user interaction
"! <p>
"! Shows a popup if requested and asks the user if he wants to continue if there are unmet
"! requirements. If not an exception is raised.
"! </p>
"! @parameter it_requirements | The requirements to check
"! @parameter iv_show_popup | Show popup with requirements
"! @raising lcx_exception | Cancelled by user or internal error
check_requirements IMPORTING it_requirements TYPE lcl_dot_abapgit=>ty_requirement_tab
iv_show_popup TYPE abap_bool DEFAULT abap_true
RAISING lcx_exception,
"! Get a table with information about each requirement
"! @parameter it_requirements | Requirements
"! @parameter rt_status | Result
"! @raising lcx_exception | Internal error
get_requirement_met_status IMPORTING it_requirements TYPE lcl_dot_abapgit=>ty_requirement_tab
RETURNING VALUE(rt_status) TYPE gty_status_tab
RAISING lcx_exception.
PROTECTED SECTION.
PRIVATE SECTION.
CLASS-METHODS:
show_requirement_popup IMPORTING it_requirements TYPE gty_status_tab
RAISING lcx_exception,
version_greater_or_equal IMPORTING is_status TYPE gty_status
RETURNING VALUE(rv_true) TYPE abap_bool.
ENDCLASS.
CLASS lcl_requirement_helper IMPLEMENTATION.
METHOD check_requirements.
DATA: lt_met_status TYPE gty_status_tab,
lv_answer TYPE c LENGTH 1.
lt_met_status = get_requirement_met_status( it_requirements ).
IF iv_show_popup = abap_true.
show_requirement_popup( lt_met_status ).
ENDIF.
LOOP AT lt_met_status TRANSPORTING NO FIELDS WHERE met = abap_false.
EXIT.
ENDLOOP.
IF sy-subrc = 0.
CALL FUNCTION 'POPUP_TO_CONFIRM'
EXPORTING
text_question = 'The project has unmet requirements. Install anyways?'
IMPORTING
answer = lv_answer.
IF lv_answer <> '1'.
lcx_exception=>raise( 'Cancelling because of unmet requirements.' ).
ENDIF.
ENDIF.
ENDMETHOD.
METHOD get_requirement_met_status.
DATA: lt_installed TYPE STANDARD TABLE OF cvers_sdu.
FIELD-SYMBOLS: <ls_requirement> TYPE lcl_dot_abapgit=>ty_requirement,
<ls_status> TYPE gty_status,
<ls_installed_comp> TYPE cvers_sdu.
CALL FUNCTION 'DELIVERY_GET_INSTALLED_COMPS'
TABLES
tt_comptab = lt_installed
EXCEPTIONS
no_release_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
lcx_exception=>raise( |Error from DELIVERY_GET_INSTALLED_COMPS { sy-subrc }| ) ##NO_TEXT.
ENDIF.
LOOP AT it_requirements ASSIGNING <ls_requirement>.
APPEND INITIAL LINE TO rt_status ASSIGNING <ls_status>.
<ls_status>-component = <ls_requirement>-component.
<ls_status>-required_release = <ls_requirement>-min_release.
<ls_status>-required_patch = <ls_requirement>-min_patch.
READ TABLE lt_installed WITH KEY component = <ls_requirement>-component
ASSIGNING <ls_installed_comp>.
IF sy-subrc = 0.
<ls_status>-installed_release = <ls_installed_comp>-release.
<ls_status>-installed_patch = <ls_installed_comp>-extrelease.
<ls_status>-description = <ls_installed_comp>-desc_text.
<ls_status>-met = version_greater_or_equal( <ls_status> ).
ENDIF.
UNASSIGN <ls_installed_comp>.
ENDLOOP.
ENDMETHOD.
METHOD version_greater_or_equal.
DATA: lv_number TYPE numc4.
TRY.
MOVE EXACT: is_status-installed_release TO lv_number,
is_status-installed_patch TO lv_number,
is_status-required_release TO lv_number,
is_status-required_patch TO lv_number.
CATCH cx_sy_conversion_error.
" Cannot compare by number, assume requirement not fullfilled (user can force install
" anyways if this was an error)
rv_true = abap_false.
RETURN.
ENDTRY.
" Check if versions are comparable by number
IF is_status-installed_release > is_status-required_release
OR ( is_status-installed_release = is_status-required_release
AND ( is_status-required_patch IS INITIAL OR
is_status-installed_patch >= is_status-required_patch ) ).
rv_true = abap_true.
ENDIF.
ENDMETHOD.
METHOD show_requirement_popup.
TYPES: BEGIN OF lty_color_line,
color TYPE lvc_t_scol.
INCLUDE TYPE gty_status.
TYPES: END OF lty_color_line,
lty_color_tab TYPE STANDARD TABLE OF lty_color_line WITH DEFAULT KEY.
DATA: lo_alv TYPE REF TO cl_salv_table,
lo_column TYPE REF TO cl_salv_column,
lt_color_table TYPE lty_color_tab,
lt_color_neg TYPE lvc_t_scol,
lt_color_pos TYPE lvc_t_scol,
ls_color TYPE lvc_s_scol,
lx_ex TYPE REF TO cx_root.
FIELD-SYMBOLS: <ls_line> TYPE lty_color_line.
ls_color-color-col = col_negative.
APPEND ls_color TO lt_color_neg.
ls_color-color-col = col_positive.
APPEND ls_color TO lt_color_pos.
CLEAR ls_color.
MOVE-CORRESPONDING it_requirements TO lt_color_table.
LOOP AT lt_color_table ASSIGNING <ls_line>.
IF <ls_line>-met = abap_false.
<ls_line>-color = lt_color_neg.
ELSE.
<ls_line>-color = lt_color_pos.
ENDIF.
ENDLOOP.
UNASSIGN <ls_line>.
TRY.
cl_salv_table=>factory(
IMPORTING
r_salv_table = lo_alv
CHANGING
t_table = lt_color_table
).
lo_alv->get_columns(:
)->get_column( 'MET' )->set_short_text( 'Met' ),
)->set_color_column( 'COLOR' ),
)->set_optimize( ),
).
lo_column = lo_alv->get_columns( )->get_column( 'REQUIRED_RELEASE' ).
lo_column->set_fixed_header_text( 'S').
lo_column->set_short_text( 'Req. Rel.' ).
lo_column = lo_alv->get_columns( )->get_column( 'REQUIRED_PATCH' ).
lo_column->set_fixed_header_text( 'S').
lo_column->set_short_text( 'Req. SP L.' ).
lo_alv->set_screen_popup( start_column = 30
end_column = 100
start_line = 10
end_line = 20 ).
lo_alv->get_display_settings( )->set_list_header( 'Requirements' ).
lo_alv->display( ).
CATCH cx_salv_msg cx_salv_not_found cx_salv_data_error INTO lx_ex.
RAISE EXCEPTION TYPE lcx_exception
EXPORTING
iv_text = lx_ex->get_text( )
ix_previous = lx_ex.
ENDTRY.
ENDMETHOD.
ENDCLASS.
|
Remove unnecessary dynamic typing
|
Remove unnecessary dynamic typing
|
ABAP
|
mit
|
sbcgua/abapGit,larshp/abapGit,EduardoCopat/abapGit,apex8/abapGit,apex8/abapGit,EduardoCopat/abapGit,larshp/abapGit,sbcgua/abapGit
|
14b91e5b887447ae754f38d08d82df68e0c073c6
|
src/zabapgit_repo.prog.abap
|
src/zabapgit_repo.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_REPO
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_repo DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_repo DEFINITION ABSTRACT FRIENDS lcl_repo_srv.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING is_data TYPE lcl_persistence_repo=>ty_repo,
get_key
RETURNING VALUE(rv_key) TYPE lcl_persistence_db=>ty_value,
get_name
RETURNING VALUE(rv_name) TYPE string
RAISING lcx_exception,
get_files_local
IMPORTING io_log TYPE REF TO lcl_log OPTIONAL
RETURNING VALUE(rt_files) TYPE ty_files_item_tt
RAISING lcx_exception,
get_local_checksums
RETURNING VALUE(rt_checksums) TYPE lcl_persistence_repo=>ty_local_checksum_tt,
get_local_checksums_per_file
RETURNING VALUE(rt_checksums) TYPE ty_file_signatures_tt,
get_files_remote
RETURNING VALUE(rt_files) TYPE ty_files_tt
RAISING lcx_exception,
get_package
RETURNING VALUE(rv_package) TYPE lcl_persistence_repo=>ty_repo-package,
get_master_language
RETURNING VALUE(rv_language) TYPE spras,
is_write_protected
RETURNING VALUE(rv_yes) TYPE sap_bool,
delete
RAISING lcx_exception,
get_dot_abapgit
RETURNING VALUE(ro_dot_abapgit) TYPE REF TO lcl_dot_abapgit,
deserialize
RAISING lcx_exception,
refresh
IMPORTING iv_drop_cache TYPE abap_bool DEFAULT abap_false
RAISING lcx_exception,
refresh_local, " For testing purposes, maybe removed later
update_local_checksums
IMPORTING it_files TYPE ty_file_signatures_tt
RAISING lcx_exception,
rebuild_local_checksums
RAISING lcx_exception,
is_offline
RETURNING VALUE(rv_offline) TYPE abap_bool
RAISING lcx_exception.
PROTECTED SECTION.
DATA: mt_local TYPE ty_files_item_tt,
mt_remote TYPE ty_files_tt,
mo_dot_abapgit TYPE REF TO lcl_dot_abapgit,
mv_do_local_refresh TYPE abap_bool,
mv_last_serialization TYPE timestamp,
ms_data TYPE lcl_persistence_repo=>ty_repo.
METHODS:
find_dot_abapgit
RAISING lcx_exception,
set
IMPORTING iv_sha1 TYPE ty_sha1 OPTIONAL
it_checksums TYPE lcl_persistence_repo=>ty_local_checksum_tt OPTIONAL
iv_url TYPE lcl_persistence_repo=>ty_repo-url OPTIONAL
iv_branch_name TYPE lcl_persistence_repo=>ty_repo-branch_name OPTIONAL
iv_head_branch TYPE lcl_persistence_repo=>ty_repo-head_branch OPTIONAL
iv_offline TYPE lcl_persistence_repo=>ty_repo-offline OPTIONAL
RAISING lcx_exception.
ENDCLASS. "lcl_repo DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_repo_online DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_repo_online DEFINITION INHERITING FROM lcl_repo FINAL.
PUBLIC SECTION.
METHODS:
refresh REDEFINITION,
constructor
IMPORTING is_data TYPE lcl_persistence_repo=>ty_repo
RAISING lcx_exception,
get_url
RETURNING VALUE(rv_url) TYPE lcl_persistence_repo=>ty_repo-url,
get_branch_name
RETURNING VALUE(rv_name) TYPE lcl_persistence_repo=>ty_repo-branch_name,
get_head_branch_name
RETURNING VALUE(rv_name) TYPE lcl_persistence_repo=>ty_repo-head_branch,
get_branches
RETURNING VALUE(ro_branches) TYPE REF TO lcl_git_branch_list
RAISING lcx_exception,
set_url
IMPORTING iv_url TYPE lcl_persistence_repo=>ty_repo-url
RAISING lcx_exception,
set_branch_name
IMPORTING iv_branch_name TYPE lcl_persistence_repo=>ty_repo-branch_name
RAISING lcx_exception,
set_new_remote
IMPORTING iv_url TYPE lcl_persistence_repo=>ty_repo-url
iv_branch_name TYPE lcl_persistence_repo=>ty_repo-branch_name
RAISING lcx_exception,
get_sha1_local
RETURNING VALUE(rv_sha1) TYPE lcl_persistence_repo=>ty_repo-sha1,
get_sha1_remote
RETURNING VALUE(rv_sha1) TYPE lcl_persistence_repo=>ty_repo-sha1
RAISING lcx_exception,
get_files_remote REDEFINITION,
get_objects
RETURNING VALUE(rt_objects) TYPE ty_objects_tt
RAISING lcx_exception,
deserialize REDEFINITION,
status
IMPORTING io_log TYPE REF TO lcl_log OPTIONAL
RETURNING VALUE(rt_results) TYPE ty_results_tt
RAISING lcx_exception,
reset_status,
rebuild_local_checksums REDEFINITION,
push
IMPORTING is_comment TYPE ty_comment
io_stage TYPE REF TO lcl_stage
RAISING lcx_exception.
PRIVATE SECTION.
DATA:
mt_objects TYPE ty_objects_tt,
mv_branch TYPE ty_sha1,
mv_initialized TYPE abap_bool,
mo_branches TYPE REF TO lcl_git_branch_list,
mt_status TYPE ty_results_tt.
METHODS:
handle_stage_ignore
IMPORTING io_stage TYPE REF TO lcl_stage
RAISING lcx_exception,
initialize
RAISING lcx_exception,
actualize_head_branch
RAISING lcx_exception.
ENDCLASS. "lcl_repo_online DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_repo_offline DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_repo_offline DEFINITION INHERITING FROM lcl_repo FINAL.
PUBLIC SECTION.
METHODS:
set_files_remote
IMPORTING it_files TYPE ty_files_tt
RAISING lcx_exception.
ENDCLASS. "lcl_repo_offline DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_repo_srv DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_repo_srv DEFINITION FINAL CREATE PRIVATE FRIENDS lcl_app.
PUBLIC SECTION.
TYPES: ty_repo_tt TYPE STANDARD TABLE OF REF TO lcl_repo WITH DEFAULT KEY.
METHODS list
RETURNING VALUE(rt_list) TYPE ty_repo_tt
RAISING lcx_exception.
METHODS refresh
RAISING lcx_exception.
METHODS new_online
IMPORTING iv_url TYPE string
iv_branch_name TYPE string
iv_package TYPE devclass
RETURNING VALUE(ro_repo) TYPE REF TO lcl_repo_online
RAISING lcx_exception.
METHODS new_offline
IMPORTING iv_url TYPE string
iv_package TYPE devclass
RETURNING VALUE(ro_repo) TYPE REF TO lcl_repo_offline
RAISING lcx_exception.
METHODS delete
IMPORTING io_repo TYPE REF TO lcl_repo
RAISING lcx_exception.
METHODS get
IMPORTING iv_key TYPE lcl_persistence_db=>ty_value
RETURNING VALUE(ro_repo) TYPE REF TO lcl_repo
RAISING lcx_exception.
METHODS is_repo_installed
IMPORTING iv_url TYPE string
iv_target_package TYPE devclass OPTIONAL
RETURNING VALUE(rv_installed) TYPE abap_bool
RAISING lcx_exception.
METHODS switch_repo_type
IMPORTING iv_key TYPE lcl_persistence_db=>ty_value
iv_offline TYPE abap_bool
RAISING lcx_exception.
PRIVATE SECTION.
METHODS constructor.
DATA: mv_init TYPE abap_bool VALUE abap_false,
mo_persistence TYPE REF TO lcl_persistence_repo,
mt_list TYPE ty_repo_tt.
METHODS add
IMPORTING io_repo TYPE REF TO lcl_repo
RAISING lcx_exception.
METHODS validate_package
IMPORTING iv_package TYPE devclass
RAISING lcx_exception.
ENDCLASS. "lcl_repo_srv DEFINITION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_REPO
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_repo DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_repo DEFINITION ABSTRACT FRIENDS lcl_repo_srv.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING is_data TYPE lcl_persistence_repo=>ty_repo,
get_key
RETURNING VALUE(rv_key) TYPE lcl_persistence_db=>ty_value,
get_name
RETURNING VALUE(rv_name) TYPE string
RAISING lcx_exception,
get_files_local
IMPORTING io_log TYPE REF TO lcl_log OPTIONAL
it_filter TYPE scts_tadir OPTIONAL
RETURNING VALUE(rt_files) TYPE ty_files_item_tt
RAISING lcx_exception,
get_local_checksums
RETURNING VALUE(rt_checksums) TYPE lcl_persistence_repo=>ty_local_checksum_tt,
get_local_checksums_per_file
RETURNING VALUE(rt_checksums) TYPE ty_file_signatures_tt,
get_files_remote
RETURNING VALUE(rt_files) TYPE ty_files_tt
RAISING lcx_exception,
get_package
RETURNING VALUE(rv_package) TYPE lcl_persistence_repo=>ty_repo-package,
get_master_language
RETURNING VALUE(rv_language) TYPE spras,
is_write_protected
RETURNING VALUE(rv_yes) TYPE sap_bool,
delete
RAISING lcx_exception,
get_dot_abapgit
RETURNING VALUE(ro_dot_abapgit) TYPE REF TO lcl_dot_abapgit,
deserialize
RAISING lcx_exception,
refresh
IMPORTING iv_drop_cache TYPE abap_bool DEFAULT abap_false
RAISING lcx_exception,
refresh_local, " For testing purposes, maybe removed later
update_local_checksums
IMPORTING it_files TYPE ty_file_signatures_tt
RAISING lcx_exception,
rebuild_local_checksums
RAISING lcx_exception,
is_offline
RETURNING VALUE(rv_offline) TYPE abap_bool
RAISING lcx_exception.
PROTECTED SECTION.
DATA: mt_local TYPE ty_files_item_tt,
mt_remote TYPE ty_files_tt,
mo_dot_abapgit TYPE REF TO lcl_dot_abapgit,
mv_do_local_refresh TYPE abap_bool,
mv_last_serialization TYPE timestamp,
ms_data TYPE lcl_persistence_repo=>ty_repo.
METHODS:
find_dot_abapgit
RAISING lcx_exception,
set
IMPORTING iv_sha1 TYPE ty_sha1 OPTIONAL
it_checksums TYPE lcl_persistence_repo=>ty_local_checksum_tt OPTIONAL
iv_url TYPE lcl_persistence_repo=>ty_repo-url OPTIONAL
iv_branch_name TYPE lcl_persistence_repo=>ty_repo-branch_name OPTIONAL
iv_head_branch TYPE lcl_persistence_repo=>ty_repo-head_branch OPTIONAL
iv_offline TYPE lcl_persistence_repo=>ty_repo-offline OPTIONAL
RAISING lcx_exception.
ENDCLASS. "lcl_repo DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_repo_online DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_repo_online DEFINITION INHERITING FROM lcl_repo FINAL.
PUBLIC SECTION.
METHODS:
refresh REDEFINITION,
constructor
IMPORTING is_data TYPE lcl_persistence_repo=>ty_repo
RAISING lcx_exception,
get_url
RETURNING VALUE(rv_url) TYPE lcl_persistence_repo=>ty_repo-url,
get_branch_name
RETURNING VALUE(rv_name) TYPE lcl_persistence_repo=>ty_repo-branch_name,
get_head_branch_name
RETURNING VALUE(rv_name) TYPE lcl_persistence_repo=>ty_repo-head_branch,
get_branches
RETURNING VALUE(ro_branches) TYPE REF TO lcl_git_branch_list
RAISING lcx_exception,
set_url
IMPORTING iv_url TYPE lcl_persistence_repo=>ty_repo-url
RAISING lcx_exception,
set_branch_name
IMPORTING iv_branch_name TYPE lcl_persistence_repo=>ty_repo-branch_name
RAISING lcx_exception,
set_new_remote
IMPORTING iv_url TYPE lcl_persistence_repo=>ty_repo-url
iv_branch_name TYPE lcl_persistence_repo=>ty_repo-branch_name
RAISING lcx_exception,
get_sha1_local
RETURNING VALUE(rv_sha1) TYPE lcl_persistence_repo=>ty_repo-sha1,
get_sha1_remote
RETURNING VALUE(rv_sha1) TYPE lcl_persistence_repo=>ty_repo-sha1
RAISING lcx_exception,
get_files_remote REDEFINITION,
get_objects
RETURNING VALUE(rt_objects) TYPE ty_objects_tt
RAISING lcx_exception,
deserialize REDEFINITION,
status
IMPORTING io_log TYPE REF TO lcl_log OPTIONAL
RETURNING VALUE(rt_results) TYPE ty_results_tt
RAISING lcx_exception,
reset_status,
rebuild_local_checksums REDEFINITION,
push
IMPORTING is_comment TYPE ty_comment
io_stage TYPE REF TO lcl_stage
RAISING lcx_exception.
PRIVATE SECTION.
DATA:
mt_objects TYPE ty_objects_tt,
mv_branch TYPE ty_sha1,
mv_initialized TYPE abap_bool,
mo_branches TYPE REF TO lcl_git_branch_list,
mt_status TYPE ty_results_tt.
METHODS:
handle_stage_ignore
IMPORTING io_stage TYPE REF TO lcl_stage
RAISING lcx_exception,
initialize
RAISING lcx_exception,
actualize_head_branch
RAISING lcx_exception.
ENDCLASS. "lcl_repo_online DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_repo_offline DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_repo_offline DEFINITION INHERITING FROM lcl_repo FINAL.
PUBLIC SECTION.
METHODS:
set_files_remote
IMPORTING it_files TYPE ty_files_tt
RAISING lcx_exception.
ENDCLASS. "lcl_repo_offline DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_repo_srv DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_repo_srv DEFINITION FINAL CREATE PRIVATE FRIENDS lcl_app.
PUBLIC SECTION.
TYPES: ty_repo_tt TYPE STANDARD TABLE OF REF TO lcl_repo WITH DEFAULT KEY.
METHODS list
RETURNING VALUE(rt_list) TYPE ty_repo_tt
RAISING lcx_exception.
METHODS refresh
RAISING lcx_exception.
METHODS new_online
IMPORTING iv_url TYPE string
iv_branch_name TYPE string
iv_package TYPE devclass
RETURNING VALUE(ro_repo) TYPE REF TO lcl_repo_online
RAISING lcx_exception.
METHODS new_offline
IMPORTING iv_url TYPE string
iv_package TYPE devclass
RETURNING VALUE(ro_repo) TYPE REF TO lcl_repo_offline
RAISING lcx_exception.
METHODS delete
IMPORTING io_repo TYPE REF TO lcl_repo
RAISING lcx_exception.
METHODS get
IMPORTING iv_key TYPE lcl_persistence_db=>ty_value
RETURNING VALUE(ro_repo) TYPE REF TO lcl_repo
RAISING lcx_exception.
METHODS is_repo_installed
IMPORTING iv_url TYPE string
iv_target_package TYPE devclass OPTIONAL
RETURNING VALUE(rv_installed) TYPE abap_bool
RAISING lcx_exception.
METHODS switch_repo_type
IMPORTING iv_key TYPE lcl_persistence_db=>ty_value
iv_offline TYPE abap_bool
RAISING lcx_exception.
PRIVATE SECTION.
METHODS constructor.
DATA: mv_init TYPE abap_bool VALUE abap_false,
mo_persistence TYPE REF TO lcl_persistence_repo,
mt_list TYPE ty_repo_tt.
METHODS add
IMPORTING io_repo TYPE REF TO lcl_repo
RAISING lcx_exception.
METHODS validate_package
IMPORTING iv_package TYPE devclass
RAISING lcx_exception.
ENDCLASS. "lcl_repo_srv DEFINITION
|
Update zabapgit_repo.prog.abap
|
Update zabapgit_repo.prog.abap
|
ABAP
|
mit
|
apex8/abapGit,sbcgua/abapGit,EduardoCopat/abapGit,sbcgua/abapGit,larshp/abapGit,nununo/abapGit,larshp/abapGit,EduardoCopat/abapGit,apex8/abapGit,nununo/abapGit
|
f1ab524752d931be398bfea135ba2ab0f390217d
|
src/zabapgit.prog.abap
|
src/zabapgit.prog.abap
|
REPORT zabapgit LINE-SIZE 100.
* See http://www.abapgit.org
CONSTANTS: gc_xml_version TYPE string VALUE 'v1.0.0', "#EC NOTEXT
gc_abap_version TYPE string VALUE 'v1.17.16'. "#EC NOTEXT
********************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2014 abapGit Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
********************************************************************************
SELECTION-SCREEN BEGIN OF SCREEN 1001.
* dummy for triggering screen
SELECTION-SCREEN END OF SCREEN 1001.
INCLUDE zabapgit_password_dialog. " !!! Contains SELECTION SCREEN
INCLUDE zabapgit_definitions.
INCLUDE zabapgit_exceptions.
INCLUDE zabapgit_zlib.
INCLUDE zabapgit_html.
INCLUDE zabapgit_util.
INCLUDE zabapgit_xml.
INCLUDE zabapgit_app. " Some deferred definitions here
INCLUDE zabapgit_persistence_old.
INCLUDE zabapgit_persistence.
INCLUDE zabapgit_dot_abapgit.
INCLUDE zabapgit_sap_package.
INCLUDE zabapgit_stage.
INCLUDE zabapgit_git_helpers.
INCLUDE zabapgit_repo.
INCLUDE zabapgit_stage_logic.
INCLUDE zabapgit_git.
INCLUDE zabapgit_objects.
INCLUDE zabapgit_tadir.
INCLUDE zabapgit_file_status.
INCLUDE zabapgit_popups.
INCLUDE zabapgit_zip.
INCLUDE zabapgit_objects_impl.
INCLUDE zabapgit_object_serializing. " All serializing classes here
INCLUDE zabapgit_repo_impl.
INCLUDE zabapgit_background.
INCLUDE zabapgit_transport.
INCLUDE zabapgit_services. " All services here
INCLUDE zabapgit_gui_pages. " All GUI pages here
INCLUDE zabapgit_gui_pages_userexit IF FOUND.
INCLUDE zabapgit_gui_router.
INCLUDE zabapgit_gui.
INCLUDE zabapgit_app_impl.
INCLUDE zabapgit_unit_test.
INCLUDE zabapgit_forms.
**********************************************************************
INITIALIZATION.
lcl_password_dialog=>on_screen_init( ).
START-OF-SELECTION.
PERFORM run.
* Hide Execute button from screen
AT SELECTION-SCREEN OUTPUT.
IF sy-dynnr = lcl_password_dialog=>dynnr.
lcl_password_dialog=>on_screen_output( ).
ELSE.
PERFORM output.
ENDIF.
* SAP back command re-direction
AT SELECTION-SCREEN ON EXIT-COMMAND.
PERFORM exit.
AT SELECTION-SCREEN.
IF sy-dynnr = lcl_password_dialog=>dynnr.
lcl_password_dialog=>on_screen_event( sscrfields-ucomm ).
ENDIF.
|
REPORT zabapgit LINE-SIZE 100.
* See http://www.abapgit.org
CONSTANTS: gc_xml_version TYPE string VALUE 'v1.0.0', "#EC NOTEXT
gc_abap_version TYPE string VALUE 'v1.17.17'. "#EC NOTEXT
********************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2014 abapGit Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
********************************************************************************
SELECTION-SCREEN BEGIN OF SCREEN 1001.
* dummy for triggering screen
SELECTION-SCREEN END OF SCREEN 1001.
INCLUDE zabapgit_password_dialog. " !!! Contains SELECTION SCREEN
INCLUDE zabapgit_definitions.
INCLUDE zabapgit_exceptions.
INCLUDE zabapgit_zlib.
INCLUDE zabapgit_html.
INCLUDE zabapgit_util.
INCLUDE zabapgit_xml.
INCLUDE zabapgit_app. " Some deferred definitions here
INCLUDE zabapgit_persistence_old.
INCLUDE zabapgit_persistence.
INCLUDE zabapgit_dot_abapgit.
INCLUDE zabapgit_sap_package.
INCLUDE zabapgit_stage.
INCLUDE zabapgit_git_helpers.
INCLUDE zabapgit_repo.
INCLUDE zabapgit_stage_logic.
INCLUDE zabapgit_git.
INCLUDE zabapgit_objects.
INCLUDE zabapgit_tadir.
INCLUDE zabapgit_file_status.
INCLUDE zabapgit_popups.
INCLUDE zabapgit_zip.
INCLUDE zabapgit_objects_impl.
INCLUDE zabapgit_object_serializing. " All serializing classes here
INCLUDE zabapgit_repo_impl.
INCLUDE zabapgit_background.
INCLUDE zabapgit_transport.
INCLUDE zabapgit_services. " All services here
INCLUDE zabapgit_gui_pages. " All GUI pages here
INCLUDE zabapgit_gui_pages_userexit IF FOUND.
INCLUDE zabapgit_gui_router.
INCLUDE zabapgit_gui.
INCLUDE zabapgit_app_impl.
INCLUDE zabapgit_unit_test.
INCLUDE zabapgit_forms.
**********************************************************************
INITIALIZATION.
lcl_password_dialog=>on_screen_init( ).
START-OF-SELECTION.
PERFORM run.
* Hide Execute button from screen
AT SELECTION-SCREEN OUTPUT.
IF sy-dynnr = lcl_password_dialog=>dynnr.
lcl_password_dialog=>on_screen_output( ).
ELSE.
PERFORM output.
ENDIF.
* SAP back command re-direction
AT SELECTION-SCREEN ON EXIT-COMMAND.
PERFORM exit.
AT SELECTION-SCREEN.
IF sy-dynnr = lcl_password_dialog=>dynnr.
lcl_password_dialog=>on_screen_event( sscrfields-ucomm ).
ENDIF.
|
bump version to v1.17.17
|
bump version to v1.17.17
|
ABAP
|
mit
|
sbcgua/abapGit,apex8/abapGit,EduardoCopat/abapGit,larshp/abapGit,nununo/abapGit,apex8/abapGit,larshp/abapGit,EduardoCopat/abapGit,sbcgua/abapGit,nununo/abapGit
|
df549d1c47a8f4fa2df0b3e2637cd578307ba6a5
|
src/zabapgit_object_shlp.prog.abap
|
src/zabapgit_object_shlp.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_SHLP
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_shlp DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_shlp DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
ENDCLASS. "lcl_object_dtel DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_dtel IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_shlp IMPLEMENTATION.
METHOD lif_object~has_changed_since.
DATA: lv_date TYPE dats,
lv_time TYPE tims,
lv_ts TYPE timestamp.
SELECT SINGLE as4date as4time FROM dd30l
INTO (lv_date, lv_time)
WHERE shlpname = ms_item-obj_name
AND as4local = 'A'.
_object_check_timestamp lv_date lv_time.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
SELECT SINGLE as4user FROM dd30l INTO rv_user
WHERE shlpname = ms_item-obj_name
AND as4local = 'A'. "#EC CI_GENBUFF
IF sy-subrc <> 0.
rv_user = c_user_unknown.
ENDIF.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD lif_object~exists.
DATA: lv_shlpname TYPE dd30l-shlpname.
SELECT SINGLE shlpname FROM dd30l INTO lv_shlpname
WHERE shlpname = ms_item-obj_name
AND as4local = 'A'. "#EC CI_GENBUFF
rv_bool = boolc( sy-subrc = 0 ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~jump.
jump_se11( iv_radio = 'RSRD1-SHMA'
iv_field = 'RSRD1-SHMA_VAL' ).
ENDMETHOD. "jump
METHOD lif_object~delete.
DATA: lv_objname TYPE rsedd0-ddobjname.
lv_objname = ms_item-obj_name.
CALL FUNCTION 'RS_DD_DELETE_OBJ'
EXPORTING
no_ask = abap_true
objname = lv_objname
objtype = 'H'
EXCEPTIONS
not_executed = 1
object_not_found = 2
object_not_specified = 3
permission_failure = 4.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from RS_DD_DELETE_OBJ, SHLP' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~serialize.
DATA: lv_name TYPE ddobjname,
ls_dd30v TYPE dd30v,
lt_dd31v TYPE TABLE OF dd31v,
lt_dd32p TYPE TABLE OF dd32p,
lt_dd33v TYPE TABLE OF dd33v.
lv_name = ms_item-obj_name.
CALL FUNCTION 'DDIF_SHLP_GET'
EXPORTING
name = lv_name
state = 'A'
langu = mv_language
IMPORTING
dd30v_wa = ls_dd30v
TABLES
dd31v_tab = lt_dd31v
dd32p_tab = lt_dd32p
dd33v_tab = lt_dd33v
EXCEPTIONS
illegal_input = 1
OTHERS = 2.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DDIF_SHLP_GET' ).
ENDIF.
IF ls_dd30v IS INITIAL.
RETURN. " does not exist in system
ENDIF.
CLEAR: ls_dd30v-as4user,
ls_dd30v-as4date,
ls_dd30v-as4time.
io_xml->add( iv_name = 'DD30V'
ig_data = ls_dd30v ).
io_xml->add( ig_data = lt_dd31v
iv_name = 'DD31V_TABLE' ).
io_xml->add( ig_data = lt_dd32p
iv_name = 'DD32P_TABLE' ).
io_xml->add( ig_data = lt_dd33v
iv_name = 'DD33V_TABLE' ).
ENDMETHOD. "serialize
METHOD lif_object~deserialize.
DATA: lv_name TYPE ddobjname,
ls_dd30v TYPE dd30v,
lt_dd31v TYPE TABLE OF dd31v,
lt_dd32p TYPE TABLE OF dd32p,
lt_dd33v TYPE TABLE OF dd33v.
io_xml->read( EXPORTING iv_name = 'DD30V'
CHANGING cg_data = ls_dd30v ).
io_xml->read( EXPORTING iv_name = 'DD31V_TABLE'
CHANGING cg_data = lt_dd31v ).
io_xml->read( EXPORTING iv_name = 'DD32P_TABLE'
CHANGING cg_data = lt_dd32p ).
io_xml->read( EXPORTING iv_name = 'DD33V_TABLE'
CHANGING cg_data = lt_dd33v ).
corr_insert( iv_package ).
lv_name = ms_item-obj_name.
CALL FUNCTION 'DDIF_SHLP_PUT'
EXPORTING
name = lv_name
dd30v_wa = ls_dd30v
TABLES
dd31v_tab = lt_dd31v
dd32p_tab = lt_dd32p
dd33v_tab = lt_dd33v
EXCEPTIONS
shlp_not_found = 1
name_inconsistent = 2
shlp_inconsistent = 3
put_failure = 4
put_refused = 5
OTHERS = 6.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DDIF_SHLP_PUT' ).
ENDIF.
lcl_objects_activation=>add_item( ms_item ).
ENDMETHOD. "deserialize
ENDCLASS. "lcl_object_shlp IMPLEMENTATION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_SHLP
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_shlp DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_shlp DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
ENDCLASS. "lcl_object_dtel DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_dtel IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_shlp IMPLEMENTATION.
METHOD lif_object~has_changed_since.
DATA: lv_date TYPE dats,
lv_time TYPE tims,
lv_ts TYPE timestamp.
SELECT SINGLE as4date as4time FROM dd30l
INTO (lv_date, lv_time)
WHERE shlpname = ms_item-obj_name
AND as4local = 'A'.
_object_check_timestamp lv_date lv_time.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
SELECT SINGLE as4user FROM dd30l INTO rv_user
WHERE shlpname = ms_item-obj_name
AND as4local = 'A'. "#EC CI_GENBUFF
IF sy-subrc <> 0.
rv_user = c_user_unknown.
ENDIF.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD lif_object~exists.
DATA: lv_shlpname TYPE dd30l-shlpname.
SELECT SINGLE shlpname FROM dd30l INTO lv_shlpname
WHERE shlpname = ms_item-obj_name
AND as4local = 'A'. "#EC CI_GENBUFF
rv_bool = boolc( sy-subrc = 0 ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~jump.
jump_se11( iv_radio = 'RSRD1-SHMA'
iv_field = 'RSRD1-SHMA_VAL' ).
ENDMETHOD. "jump
METHOD lif_object~delete.
DATA: lv_objname TYPE rsedd0-ddobjname.
lv_objname = ms_item-obj_name.
CALL FUNCTION 'RS_DD_DELETE_OBJ'
EXPORTING
no_ask = abap_true
objname = lv_objname
objtype = 'H'
EXCEPTIONS
not_executed = 1
object_not_found = 2
object_not_specified = 3
permission_failure = 4.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from RS_DD_DELETE_OBJ, SHLP' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~serialize.
DATA: lv_name TYPE ddobjname,
ls_dd30v TYPE dd30v,
lt_dd31v TYPE TABLE OF dd31v,
lt_dd32p TYPE TABLE OF dd32p,
lt_dd33v TYPE TABLE OF dd33v.
FIELD-SYMBOLS: <ls_dd32p> LIKE LINE OF lt_dd32p.
lv_name = ms_item-obj_name.
CALL FUNCTION 'DDIF_SHLP_GET'
EXPORTING
name = lv_name
state = 'A'
langu = mv_language
IMPORTING
dd30v_wa = ls_dd30v
TABLES
dd31v_tab = lt_dd31v
dd32p_tab = lt_dd32p
dd33v_tab = lt_dd33v
EXCEPTIONS
illegal_input = 1
OTHERS = 2.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DDIF_SHLP_GET' ).
ENDIF.
IF ls_dd30v IS INITIAL.
RETURN. " does not exist in system
ENDIF.
CLEAR: ls_dd30v-as4user,
ls_dd30v-as4date,
ls_dd30v-as4time.
LOOP AT lt_dd32p ASSIGNING <ls_dd32p>.
* clear information inherited from domain
CLEAR: <ls_dd32p>-domname,
<ls_dd32p>-headlen,
<ls_dd32p>-scrlen1,
<ls_dd32p>-scrlen2,
<ls_dd32p>-datatype,
<ls_dd32p>-leng,
<ls_dd32p>-outputlen,
<ls_dd32p>-decimals,
<ls_dd32p>-lowercase,
<ls_dd32p>-signflag,
<ls_dd32p>-convexit.
ENDLOOP.
io_xml->add( iv_name = 'DD30V'
ig_data = ls_dd30v ).
io_xml->add( ig_data = lt_dd31v
iv_name = 'DD31V_TABLE' ).
io_xml->add( ig_data = lt_dd32p
iv_name = 'DD32P_TABLE' ).
io_xml->add( ig_data = lt_dd33v
iv_name = 'DD33V_TABLE' ).
ENDMETHOD. "serialize
METHOD lif_object~deserialize.
DATA: lv_name TYPE ddobjname,
ls_dd30v TYPE dd30v,
lt_dd31v TYPE TABLE OF dd31v,
lt_dd32p TYPE TABLE OF dd32p,
lt_dd33v TYPE TABLE OF dd33v.
io_xml->read( EXPORTING iv_name = 'DD30V'
CHANGING cg_data = ls_dd30v ).
io_xml->read( EXPORTING iv_name = 'DD31V_TABLE'
CHANGING cg_data = lt_dd31v ).
io_xml->read( EXPORTING iv_name = 'DD32P_TABLE'
CHANGING cg_data = lt_dd32p ).
io_xml->read( EXPORTING iv_name = 'DD33V_TABLE'
CHANGING cg_data = lt_dd33v ).
corr_insert( iv_package ).
lv_name = ms_item-obj_name.
CALL FUNCTION 'DDIF_SHLP_PUT'
EXPORTING
name = lv_name
dd30v_wa = ls_dd30v
TABLES
dd31v_tab = lt_dd31v
dd32p_tab = lt_dd32p
dd33v_tab = lt_dd33v
EXCEPTIONS
shlp_not_found = 1
name_inconsistent = 2
shlp_inconsistent = 3
put_failure = 4
put_refused = 5
OTHERS = 6.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DDIF_SHLP_PUT' ).
ENDIF.
lcl_objects_activation=>add_item( ms_item ).
ENDMETHOD. "deserialize
ENDCLASS. "lcl_object_shlp IMPLEMENTATION
|
clear info inherited from domain
|
SHLP: clear info inherited from domain
|
ABAP
|
mit
|
nununo/abapGit,apex8/abapGit,EduardoCopat/abapGit,nununo/abapGit,larshp/abapGit,EduardoCopat/abapGit,sbcgua/abapGit,apex8/abapGit,sbcgua/abapGit,larshp/abapGit
|
b24c63ad1ccafb181eab91da2392401cb13b7386
|
src/zabapgit_object_tran.prog.abap
|
src/zabapgit_object_tran.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_TRAN
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_tran DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_tran DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
PRIVATE SECTION.
CONSTANTS: c_oo_program(9) VALUE '\PROGRAM=',
c_oo_class(7) VALUE '\CLASS=',
c_oo_method(8) VALUE '\METHOD=',
c_oo_tcode TYPE tcode VALUE 'OS_APPLICATION',
c_oo_frclass(30) VALUE 'CLASS',
c_oo_frmethod(30) VALUE 'METHOD',
c_oo_frupdtask(30) VALUE 'UPDATE_MODE',
c_oo_synchron VALUE 'S',
c_oo_asynchron VALUE 'U',
c_true TYPE c VALUE 'X',
c_false TYPE c VALUE space.
METHODS:
split_parameters
CHANGING ct_rsparam TYPE s_param
cs_rsstcd TYPE rsstcd
cs_tstcp TYPE tstcp
cs_tstc TYPE tstc,
split_parameters_comp
IMPORTING iv_type TYPE any
iv_param TYPE any
CHANGING cg_value TYPE any.
ENDCLASS. "lcl_object_TRAN DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_msag IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_tran IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
rv_user = c_user_unknown. " todo
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD split_parameters_comp.
DATA: lv_off TYPE i.
IF iv_param CS iv_type.
lv_off = sy-fdpos + strlen( iv_type ).
cg_value = iv_param+lv_off.
IF cg_value CA '\'.
CLEAR cg_value+sy-fdpos.
ENDIF.
ENDIF.
ENDMETHOD. "split_parameters_comp
METHOD split_parameters.
* see subroutine split_parameters in include LSEUKF01
DATA: lv_off TYPE i,
lv_param_beg TYPE i,
lv_length TYPE i,
ls_param LIKE LINE OF ct_rsparam.
FIELD-SYMBOLS <lg_f> TYPE any.
CLEAR cs_rsstcd-s_vari.
IF cs_tstcp-param(1) = '\'. " OO-Transaktion ohne FR
split_parameters_comp( EXPORTING iv_type = c_oo_program
iv_param = cs_tstcp-param
CHANGING cg_value = cs_tstc-pgmna ).
split_parameters_comp( EXPORTING iv_type = c_oo_class
iv_param = cs_tstcp-param
CHANGING cg_value = cs_rsstcd-classname ).
split_parameters_comp( EXPORTING iv_type = c_oo_method
iv_param = cs_tstcp-param
CHANGING cg_value = cs_rsstcd-method ).
IF NOT cs_tstc-pgmna IS INITIAL.
cs_rsstcd-s_local = c_true.
ENDIF.
RETURN.
ELSEIF cs_tstcp-param(1) = '@'. " Transaktionsvariante
cs_rsstcd-s_vari = c_true.
IF cs_tstcp-param(2) = '@@'.
cs_rsstcd-s_ind_vari = c_true.
lv_off = 2.
ELSE.
CLEAR cs_rsstcd-s_ind_vari.
lv_off = 1.
ENDIF.
sy-fdpos = sy-fdpos - lv_off.
IF sy-fdpos > 0.
cs_rsstcd-call_tcode = cs_tstcp-param+lv_off(sy-fdpos).
sy-fdpos = sy-fdpos + 1 + lv_off.
cs_rsstcd-variant = cs_tstcp-param+sy-fdpos.
ENDIF.
ELSEIF cs_tstcp-param(1) = '/'.
cs_rsstcd-st_tcode = c_true.
cs_rsstcd-st_prog = space.
IF cs_tstcp-param+1(1) = '*'.
cs_rsstcd-st_skip_1 = c_true.
ELSE.
CLEAR cs_rsstcd-st_skip_1.
ENDIF.
lv_param_beg = sy-fdpos + 1.
sy-fdpos = sy-fdpos - 2.
IF sy-fdpos > 0.
cs_rsstcd-call_tcode = cs_tstcp-param+2(sy-fdpos).
ENDIF.
SHIFT cs_tstcp-param BY lv_param_beg PLACES.
ELSE.
cs_rsstcd-st_tcode = space.
cs_rsstcd-st_prog = c_true.
ENDIF.
DO 254 TIMES.
IF cs_tstcp-param = space.
EXIT.
ENDIF.
CLEAR ls_param.
IF cs_tstcp-param CA '='.
CHECK sy-fdpos <> 0.
ASSIGN cs_tstcp-param(sy-fdpos) TO <lg_f>.
ls_param-field = <lg_f>.
IF ls_param-field(1) = space.
SHIFT ls_param-field.
ENDIF.
sy-fdpos = sy-fdpos + 1.
SHIFT cs_tstcp-param BY sy-fdpos PLACES.
IF cs_tstcp-param CA ';'.
IF sy-fdpos <> 0.
ASSIGN cs_tstcp-param(sy-fdpos) TO <lg_f>.
ls_param-value = <lg_f>.
IF ls_param-value(1) = space.
SHIFT ls_param-value.
ENDIF.
ENDIF.
sy-fdpos = sy-fdpos + 1.
SHIFT cs_tstcp-param BY sy-fdpos PLACES.
APPEND ls_param TO ct_rsparam.
ELSE.
lv_length = strlen( cs_tstcp-param ).
CHECK lv_length > 0.
ASSIGN cs_tstcp-param(lv_length) TO <lg_f>.
ls_param-value = <lg_f>.
IF ls_param-value(1) = space.
SHIFT ls_param-value.
ENDIF.
lv_length = lv_length + 1.
SHIFT cs_tstcp-param BY lv_length PLACES.
APPEND ls_param TO ct_rsparam.
ENDIF.
ENDIF.
ENDDO.
* oo-Transaktion mit Framework
IF cs_rsstcd-call_tcode = c_oo_tcode.
cs_rsstcd-s_trframe = c_true.
LOOP AT ct_rsparam INTO ls_param.
CASE ls_param-field.
WHEN c_oo_frclass.
cs_rsstcd-classname = ls_param-value.
WHEN c_oo_frmethod.
cs_rsstcd-method = ls_param-value.
WHEN c_oo_frupdtask.
IF ls_param-value = c_oo_synchron.
cs_rsstcd-s_upddir = c_true.
cs_rsstcd-s_updtask = c_false.
cs_rsstcd-s_updlok = c_false.
ELSEIF ls_param-value = c_oo_asynchron.
cs_rsstcd-s_upddir = c_false.
cs_rsstcd-s_updtask = c_true.
cs_rsstcd-s_updlok = c_false.
ELSE.
cs_rsstcd-s_upddir = c_false.
cs_rsstcd-s_updtask = c_false.
cs_rsstcd-s_updlok = c_true.
ENDIF.
ENDCASE.
ENDLOOP.
ENDIF.
ENDMETHOD. "split_parameters
METHOD lif_object~exists.
DATA: lv_tcode TYPE tstc-tcode.
SELECT SINGLE tcode FROM tstc INTO lv_tcode
WHERE tcode = ms_item-obj_name. "#EC CI_GENBUFF
rv_bool = boolc( sy-subrc = 0 ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~jump.
DATA: lt_bdcdata TYPE TABLE OF bdcdata.
FIELD-SYMBOLS: <ls_bdcdata> LIKE LINE OF lt_bdcdata.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-program = 'SAPLSEUK'.
<ls_bdcdata>-dynpro = '0390'.
<ls_bdcdata>-dynbegin = abap_true.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'BDC_OKCODE'.
<ls_bdcdata>-fval = '=SHOW'.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'TSTC-TCODE'.
<ls_bdcdata>-fval = ms_item-obj_name.
CALL FUNCTION 'ABAP4_CALL_TRANSACTION'
STARTING NEW TASK 'GIT'
EXPORTING
tcode = 'SE93'
mode_val = 'E'
TABLES
using_tab = lt_bdcdata
EXCEPTIONS
system_failure = 1
communication_failure = 2
resource_failure = 3
OTHERS = 4
##fm_subrc_ok. "#EC CI_SUBRC
ENDMETHOD. "jump
METHOD lif_object~delete.
DATA: lv_transaction TYPE tstc-tcode.
lv_transaction = ms_item-obj_name.
CALL FUNCTION 'RPY_TRANSACTION_DELETE'
EXPORTING
transaction = lv_transaction
EXCEPTIONS
not_excecuted = 1
object_not_found = 2
OTHERS = 3.
IF sy-subrc <> 0.
lcx_exception=>raise( 'Error from RPY_TRANSACTION_DELETE' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~deserialize.
CONSTANTS: lc_hex_tra TYPE x VALUE '00',
* c_hex_men TYPE x VALUE '01',
lc_hex_par TYPE x VALUE '02',
lc_hex_rep TYPE x VALUE '80'.
* c_hex_rpv TYPE x VALUE '10',
* c_hex_obj TYPE x VALUE '08',
* c_hex_chk TYPE x VALUE '04',
* c_hex_enq TYPE x VALUE '20'.
DATA: lv_dynpro TYPE d020s-dnum,
ls_tstc TYPE tstc,
lv_type TYPE rglif-docutype,
ls_tstct TYPE tstct,
ls_tstcc TYPE tstcc,
ls_tstcp TYPE tstcp,
lt_param_values TYPE TABLE OF rsparam,
ls_rsstcd TYPE rsstcd.
io_xml->read( EXPORTING iv_name = 'TSTC'
CHANGING cg_data = ls_tstc ).
io_xml->read( EXPORTING iv_name = 'TSTCC'
CHANGING cg_data = ls_tstcc ).
io_xml->read( EXPORTING iv_name = 'TSTCT'
CHANGING cg_data = ls_tstct ).
io_xml->read( EXPORTING iv_name = 'TSTCP'
CHANGING cg_data = ls_tstcp ).
lv_dynpro = ls_tstc-dypno.
CASE ls_tstc-cinfo.
WHEN lc_hex_tra.
lv_type = ststc_c_type_dialog.
WHEN lc_hex_rep.
lv_type = ststc_c_type_report.
WHEN lc_hex_par.
lv_type = ststc_c_type_parameters.
* todo, or ststc_c_type_variant?
WHEN OTHERS.
lcx_exception=>raise( 'Transaction, unknown CINFO' ).
ENDCASE.
IF ls_tstcp IS NOT INITIAL.
split_parameters(
CHANGING
ct_rsparam = lt_param_values
cs_rsstcd = ls_rsstcd
cs_tstcp = ls_tstcp
cs_tstc = ls_tstc ).
ENDIF.
CALL FUNCTION 'RPY_TRANSACTION_INSERT'
EXPORTING
transaction = ls_tstc-tcode
program = ls_tstc-pgmna
dynpro = lv_dynpro
language = mv_language
development_class = iv_package
transaction_type = lv_type
shorttext = ls_tstct-ttext
called_transaction = ls_rsstcd-call_tcode
called_transaction_skip = ls_rsstcd-st_skip_1
variant = ls_rsstcd-variant
cl_independend = ls_rsstcd-s_ind_vari
html_enabled = ls_tstcc-s_webgui
java_enabled = ls_tstcc-s_platin
wingui_enabled = ls_tstcc-s_win32
TABLES
param_values = lt_param_values
EXCEPTIONS
cancelled = 1
already_exist = 2
permission_error = 3
name_not_allowed = 4
name_conflict = 5
illegal_type = 6
object_inconsistent = 7
db_access_error = 8
OTHERS = 9.
IF sy-subrc <> 0.
lcx_exception=>raise( 'Error from RPY_TRANSACTION_INSERT' ).
ENDIF.
ENDMETHOD. "deserialize
METHOD lif_object~serialize.
DATA: lv_transaction TYPE tstc-tcode,
lt_tcodes TYPE TABLE OF tstc,
ls_tcode LIKE LINE OF lt_tcodes,
ls_tstct TYPE tstct,
ls_tstcp TYPE tstcp,
lt_gui_attr TYPE TABLE OF tstcc,
ls_gui_attr LIKE LINE OF lt_gui_attr.
lv_transaction = ms_item-obj_name.
CALL FUNCTION 'RPY_TRANSACTION_READ'
EXPORTING
transaction = lv_transaction
TABLES
tcodes = lt_tcodes
gui_attributes = lt_gui_attr
EXCEPTIONS
permission_error = 1
cancelled = 2
not_found = 3
object_not_found = 4
OTHERS = 5.
IF sy-subrc = 4 OR sy-subrc = 3.
RETURN.
ELSEIF sy-subrc <> 0.
lcx_exception=>raise( 'Error from RPY_TRANSACTION_READ' ).
ENDIF.
SELECT SINGLE * FROM tstct INTO ls_tstct
WHERE sprsl = mv_language
AND tcode = lv_transaction. "#EC CI_SUBRC "#EC CI_GENBUFF
SELECT SINGLE * FROM tstcp INTO ls_tstcp
WHERE tcode = lv_transaction. "#EC CI_SUBRC "#EC CI_GENBUFF
READ TABLE lt_tcodes INDEX 1 INTO ls_tcode.
ASSERT sy-subrc = 0.
READ TABLE lt_gui_attr INDEX 1 INTO ls_gui_attr.
ASSERT sy-subrc = 0.
io_xml->add( iv_name = 'TSTC'
ig_data = ls_tcode ).
io_xml->add( iv_name = 'TSTCC'
ig_data = ls_gui_attr ).
io_xml->add( iv_name = 'TSTCT'
ig_data = ls_tstct ).
IF ls_tstcp IS NOT INITIAL.
io_xml->add( iv_name = 'TSTCP'
ig_data = ls_tstcp ).
ENDIF.
ENDMETHOD. "serialize
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_null_comparison_result.
ENDMETHOD.
ENDCLASS. "lcl_object_tran IMPLEMENTATION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_TRAN
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_tran DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_tran DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
PRIVATE SECTION.
CONSTANTS: c_oo_program(9) VALUE '\PROGRAM=',
c_oo_class(7) VALUE '\CLASS=',
c_oo_method(8) VALUE '\METHOD=',
c_oo_tcode TYPE tcode VALUE 'OS_APPLICATION',
c_oo_frclass(30) VALUE 'CLASS',
c_oo_frmethod(30) VALUE 'METHOD',
c_oo_frupdtask(30) VALUE 'UPDATE_MODE',
c_oo_synchron VALUE 'S',
c_oo_asynchron VALUE 'U',
c_true TYPE c VALUE 'X',
c_false TYPE c VALUE space.
METHODS:
split_parameters
CHANGING ct_rsparam TYPE s_param
cs_rsstcd TYPE rsstcd
cs_tstcp TYPE tstcp
cs_tstc TYPE tstc,
split_parameters_comp
IMPORTING iv_type TYPE any
iv_param TYPE any
CHANGING cg_value TYPE any.
ENDCLASS. "lcl_object_TRAN DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_msag IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_tran IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
rv_user = c_user_unknown. " todo
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD split_parameters_comp.
DATA: lv_off TYPE i.
IF iv_param CS iv_type.
lv_off = sy-fdpos + strlen( iv_type ).
cg_value = iv_param+lv_off.
IF cg_value CA '\'.
CLEAR cg_value+sy-fdpos.
ENDIF.
ENDIF.
ENDMETHOD. "split_parameters_comp
METHOD split_parameters.
* see subroutine split_parameters in include LSEUKF01
DATA: lv_off TYPE i,
lv_param_beg TYPE i,
lv_length TYPE i,
ls_param LIKE LINE OF ct_rsparam.
FIELD-SYMBOLS <lg_f> TYPE any.
CLEAR cs_rsstcd-s_vari.
IF cs_tstcp-param(1) = '\'. " OO-Transaktion ohne FR
split_parameters_comp( EXPORTING iv_type = c_oo_program
iv_param = cs_tstcp-param
CHANGING cg_value = cs_tstc-pgmna ).
split_parameters_comp( EXPORTING iv_type = c_oo_class
iv_param = cs_tstcp-param
CHANGING cg_value = cs_rsstcd-classname ).
split_parameters_comp( EXPORTING iv_type = c_oo_method
iv_param = cs_tstcp-param
CHANGING cg_value = cs_rsstcd-method ).
IF NOT cs_tstc-pgmna IS INITIAL.
cs_rsstcd-s_local = c_true.
ENDIF.
RETURN.
ELSEIF cs_tstcp-param(1) = '@'. " Transaktionsvariante
cs_rsstcd-s_vari = c_true.
IF cs_tstcp-param(2) = '@@'.
cs_rsstcd-s_ind_vari = c_true.
lv_off = 2.
ELSE.
CLEAR cs_rsstcd-s_ind_vari.
lv_off = 1.
ENDIF.
sy-fdpos = sy-fdpos - lv_off.
IF sy-fdpos > 0.
cs_rsstcd-call_tcode = cs_tstcp-param+lv_off(sy-fdpos).
sy-fdpos = sy-fdpos + 1 + lv_off.
cs_rsstcd-variant = cs_tstcp-param+sy-fdpos.
ENDIF.
ELSEIF cs_tstcp-param(1) = '/'.
cs_rsstcd-st_tcode = c_true.
cs_rsstcd-st_prog = space.
IF cs_tstcp-param+1(1) = '*'.
cs_rsstcd-st_skip_1 = c_true.
ELSE.
CLEAR cs_rsstcd-st_skip_1.
ENDIF.
lv_param_beg = sy-fdpos + 1.
sy-fdpos = sy-fdpos - 2.
IF sy-fdpos > 0.
cs_rsstcd-call_tcode = cs_tstcp-param+2(sy-fdpos).
ENDIF.
SHIFT cs_tstcp-param BY lv_param_beg PLACES.
ELSE.
cs_rsstcd-st_tcode = space.
cs_rsstcd-st_prog = c_true.
ENDIF.
DO 254 TIMES.
IF cs_tstcp-param = space.
EXIT.
ENDIF.
CLEAR ls_param.
IF cs_tstcp-param CA '='.
CHECK sy-fdpos <> 0.
ASSIGN cs_tstcp-param(sy-fdpos) TO <lg_f>.
ls_param-field = <lg_f>.
IF ls_param-field(1) = space.
SHIFT ls_param-field.
ENDIF.
sy-fdpos = sy-fdpos + 1.
SHIFT cs_tstcp-param BY sy-fdpos PLACES.
IF cs_tstcp-param CA ';'.
IF sy-fdpos <> 0.
ASSIGN cs_tstcp-param(sy-fdpos) TO <lg_f>.
ls_param-value = <lg_f>.
IF ls_param-value(1) = space.
SHIFT ls_param-value.
ENDIF.
ENDIF.
sy-fdpos = sy-fdpos + 1.
SHIFT cs_tstcp-param BY sy-fdpos PLACES.
APPEND ls_param TO ct_rsparam.
ELSE.
lv_length = strlen( cs_tstcp-param ).
CHECK lv_length > 0.
ASSIGN cs_tstcp-param(lv_length) TO <lg_f>.
ls_param-value = <lg_f>.
IF ls_param-value(1) = space.
SHIFT ls_param-value.
ENDIF.
lv_length = lv_length + 1.
SHIFT cs_tstcp-param BY lv_length PLACES.
APPEND ls_param TO ct_rsparam.
ENDIF.
ENDIF.
ENDDO.
* oo-Transaktion mit Framework
IF cs_rsstcd-call_tcode = c_oo_tcode.
cs_rsstcd-s_trframe = c_true.
LOOP AT ct_rsparam INTO ls_param.
CASE ls_param-field.
WHEN c_oo_frclass.
cs_rsstcd-classname = ls_param-value.
WHEN c_oo_frmethod.
cs_rsstcd-method = ls_param-value.
WHEN c_oo_frupdtask.
IF ls_param-value = c_oo_synchron.
cs_rsstcd-s_upddir = c_true.
cs_rsstcd-s_updtask = c_false.
cs_rsstcd-s_updlok = c_false.
ELSEIF ls_param-value = c_oo_asynchron.
cs_rsstcd-s_upddir = c_false.
cs_rsstcd-s_updtask = c_true.
cs_rsstcd-s_updlok = c_false.
ELSE.
cs_rsstcd-s_upddir = c_false.
cs_rsstcd-s_updtask = c_false.
cs_rsstcd-s_updlok = c_true.
ENDIF.
ENDCASE.
ENDLOOP.
ENDIF.
ENDMETHOD. "split_parameters
METHOD lif_object~exists.
DATA: lv_tcode TYPE tstc-tcode.
SELECT SINGLE tcode FROM tstc INTO lv_tcode
WHERE tcode = ms_item-obj_name. "#EC CI_GENBUFF
rv_bool = boolc( sy-subrc = 0 ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~jump.
DATA: lt_bdcdata TYPE TABLE OF bdcdata.
FIELD-SYMBOLS: <ls_bdcdata> LIKE LINE OF lt_bdcdata.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-program = 'SAPLSEUK'.
<ls_bdcdata>-dynpro = '0390'.
<ls_bdcdata>-dynbegin = abap_true.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'BDC_OKCODE'.
<ls_bdcdata>-fval = '=SHOW'.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'TSTC-TCODE'.
<ls_bdcdata>-fval = ms_item-obj_name.
CALL FUNCTION 'ABAP4_CALL_TRANSACTION'
STARTING NEW TASK 'GIT'
EXPORTING
tcode = 'SE93'
mode_val = 'E'
TABLES
using_tab = lt_bdcdata
EXCEPTIONS
system_failure = 1
communication_failure = 2
resource_failure = 3
OTHERS = 4
##fm_subrc_ok. "#EC CI_SUBRC
ENDMETHOD. "jump
METHOD lif_object~delete.
DATA: lv_transaction TYPE tstc-tcode.
lv_transaction = ms_item-obj_name.
CALL FUNCTION 'RPY_TRANSACTION_DELETE'
EXPORTING
transaction = lv_transaction
EXCEPTIONS
not_excecuted = 1
object_not_found = 2
OTHERS = 3.
IF sy-subrc <> 0.
lcx_exception=>raise( 'Error from RPY_TRANSACTION_DELETE' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~deserialize.
CONSTANTS: lc_hex_tra TYPE x VALUE '00',
* c_hex_men TYPE x VALUE '01',
lc_hex_par TYPE x VALUE '02',
lc_hex_rep TYPE x VALUE '80'.
* c_hex_rpv TYPE x VALUE '10',
* c_hex_obj TYPE x VALUE '08',
* c_hex_chk TYPE x VALUE '04',
* c_hex_enq TYPE x VALUE '20'.
DATA: lv_dynpro TYPE d020s-dnum,
ls_tstc TYPE tstc,
lv_type TYPE rglif-docutype,
ls_tstct TYPE tstct,
ls_tstcc TYPE tstcc,
ls_tstcp TYPE tstcp,
lt_param_values TYPE TABLE OF rsparam,
ls_rsstcd TYPE rsstcd.
IF lif_object~exists( ) = abap_true.
lif_object~delete( ).
ENDIF.
io_xml->read( EXPORTING iv_name = 'TSTC'
CHANGING cg_data = ls_tstc ).
io_xml->read( EXPORTING iv_name = 'TSTCC'
CHANGING cg_data = ls_tstcc ).
io_xml->read( EXPORTING iv_name = 'TSTCT'
CHANGING cg_data = ls_tstct ).
io_xml->read( EXPORTING iv_name = 'TSTCP'
CHANGING cg_data = ls_tstcp ).
lv_dynpro = ls_tstc-dypno.
CASE ls_tstc-cinfo.
WHEN lc_hex_tra.
lv_type = ststc_c_type_dialog.
WHEN lc_hex_rep.
lv_type = ststc_c_type_report.
WHEN lc_hex_par.
lv_type = ststc_c_type_parameters.
* todo, or ststc_c_type_variant?
WHEN OTHERS.
lcx_exception=>raise( 'Transaction, unknown CINFO' ).
ENDCASE.
IF ls_tstcp IS NOT INITIAL.
split_parameters(
CHANGING
ct_rsparam = lt_param_values
cs_rsstcd = ls_rsstcd
cs_tstcp = ls_tstcp
cs_tstc = ls_tstc ).
ENDIF.
CALL FUNCTION 'RPY_TRANSACTION_INSERT'
EXPORTING
transaction = ls_tstc-tcode
program = ls_tstc-pgmna
dynpro = lv_dynpro
language = mv_language
development_class = iv_package
transaction_type = lv_type
shorttext = ls_tstct-ttext
called_transaction = ls_rsstcd-call_tcode
called_transaction_skip = ls_rsstcd-st_skip_1
variant = ls_rsstcd-variant
cl_independend = ls_rsstcd-s_ind_vari
html_enabled = ls_tstcc-s_webgui
java_enabled = ls_tstcc-s_platin
wingui_enabled = ls_tstcc-s_win32
TABLES
param_values = lt_param_values
EXCEPTIONS
cancelled = 1
already_exist = 2
permission_error = 3
name_not_allowed = 4
name_conflict = 5
illegal_type = 6
object_inconsistent = 7
db_access_error = 8
OTHERS = 9.
IF sy-subrc <> 0.
lcx_exception=>raise( 'Error from RPY_TRANSACTION_INSERT' ).
ENDIF.
ENDMETHOD. "deserialize
METHOD lif_object~serialize.
DATA: lv_transaction TYPE tstc-tcode,
lt_tcodes TYPE TABLE OF tstc,
ls_tcode LIKE LINE OF lt_tcodes,
ls_tstct TYPE tstct,
ls_tstcp TYPE tstcp,
lt_gui_attr TYPE TABLE OF tstcc,
ls_gui_attr LIKE LINE OF lt_gui_attr.
lv_transaction = ms_item-obj_name.
CALL FUNCTION 'RPY_TRANSACTION_READ'
EXPORTING
transaction = lv_transaction
TABLES
tcodes = lt_tcodes
gui_attributes = lt_gui_attr
EXCEPTIONS
permission_error = 1
cancelled = 2
not_found = 3
object_not_found = 4
OTHERS = 5.
IF sy-subrc = 4 OR sy-subrc = 3.
RETURN.
ELSEIF sy-subrc <> 0.
lcx_exception=>raise( 'Error from RPY_TRANSACTION_READ' ).
ENDIF.
SELECT SINGLE * FROM tstct INTO ls_tstct
WHERE sprsl = mv_language
AND tcode = lv_transaction. "#EC CI_SUBRC "#EC CI_GENBUFF
SELECT SINGLE * FROM tstcp INTO ls_tstcp
WHERE tcode = lv_transaction. "#EC CI_SUBRC "#EC CI_GENBUFF
READ TABLE lt_tcodes INDEX 1 INTO ls_tcode.
ASSERT sy-subrc = 0.
READ TABLE lt_gui_attr INDEX 1 INTO ls_gui_attr.
ASSERT sy-subrc = 0.
io_xml->add( iv_name = 'TSTC'
ig_data = ls_tcode ).
io_xml->add( iv_name = 'TSTCC'
ig_data = ls_gui_attr ).
io_xml->add( iv_name = 'TSTCT'
ig_data = ls_tstct ).
IF ls_tstcp IS NOT INITIAL.
io_xml->add( iv_name = 'TSTCP'
ig_data = ls_tstcp ).
ENDIF.
ENDMETHOD. "serialize
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_null_comparison_result.
ENDMETHOD.
ENDCLASS. "lcl_object_tran IMPLEMENTATION
|
fix "Error from RPY_TRANSACTION_INSERT"
|
TRAN: fix "Error from RPY_TRANSACTION_INSERT"
|
ABAP
|
mit
|
EduardoCopat/abapGit,nununo/abapGit,nununo/abapGit,apex8/abapGit,EduardoCopat/abapGit,sbcgua/abapGit,larshp/abapGit,sbcgua/abapGit,apex8/abapGit,larshp/abapGit
|
be5da79d15627570d0500009c487c5a0e3bf5581
|
src/zabapgit_page_debug.prog.abap
|
src/zabapgit_page_debug.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_PAGE_DEBUG
*&---------------------------------------------------------------------*
CLASS lcl_gui_page_debuginfo DEFINITION FINAL INHERITING FROM lcl_gui_page.
PUBLIC SECTION.
METHODS constructor.
PROTECTED SECTION.
METHODS:
render_content REDEFINITION,
scripts REDEFINITION.
PRIVATE SECTION.
METHODS render_debug_info
RETURNING VALUE(ro_html) TYPE REF TO lcl_html
RAISING lcx_exception.
METHODS render_supported_object_types
RETURNING VALUE(rv_html) TYPE string.
ENDCLASS. "lcl_gui_page_debuginfo
CLASS lcl_gui_page_debuginfo IMPLEMENTATION.
METHOD constructor.
super->constructor( ).
ms_control-page_title = 'DEBUG INFO'.
ENDMETHOD. " constructor.
METHOD render_content.
CREATE OBJECT ro_html.
ro_html->add( '<div id="debug_info" class="debug_container">' ).
ro_html->add( render_debug_info( ) ).
ro_html->add( render_supported_object_types( ) ).
ro_html->add( '</div>' ).
ENDMETHOD. "render_content
METHOD render_debug_info.
DATA: lt_ver_tab TYPE filetable,
lv_rc TYPE i,
lv_gui_version TYPE string,
ls_version LIKE LINE OF lt_ver_tab.
cl_gui_frontend_services=>get_gui_version(
CHANGING version_table = lt_ver_tab rc = lv_rc
EXCEPTIONS OTHERS = 1 ).
READ TABLE lt_ver_tab INTO ls_version INDEX 1.
lv_gui_version = ls_version-filename.
READ TABLE lt_ver_tab INTO ls_version INDEX 2.
lv_gui_version = |{ lv_gui_version }.{ ls_version-filename }|.
CREATE OBJECT ro_html.
ro_html->add( |<p>abapGit version: { gc_abap_version }</p>| ).
ro_html->add( |<p>XML version: { gc_xml_version }</p>| ).
ro_html->add( |<p>GUI version: { lv_gui_version }</p>| ).
ro_html->add( |<p>LCL_TIME: { lcl_time=>get( ) }</p>| ).
ro_html->add( |<p>SY time: { sy-datum } { sy-uzeit } { sy-tzone }</p>| ).
ENDMETHOD. "render_debug_info
METHOD render_supported_object_types.
DATA: lt_objects TYPE STANDARD TABLE OF ko100,
lv_list TYPE string,
ls_item TYPE ty_item.
FIELD-SYMBOLS <object> LIKE LINE OF lt_objects.
CALL FUNCTION 'TR_OBJECT_TABLE'
TABLES
wt_object_text = lt_objects
EXCEPTIONS
OTHERS = 1 ##FM_SUBRC_OK.
LOOP AT lt_objects ASSIGNING <object> WHERE pgmid = 'R3TR'.
ls_item-obj_type = <object>-object.
IF lcl_objects=>is_supported( is_item = ls_item iv_native_only = abap_true ) = abap_true.
IF lv_list IS INITIAL.
lv_list = ls_item-obj_type.
ELSE.
lv_list = lv_list && `, ` && ls_item-obj_type.
ENDIF.
ENDIF.
ENDLOOP.
rv_html = |<p>Supported objects: { lv_list }</p>|.
ENDMETHOD. " render_supported_object_types
METHOD scripts.
CREATE OBJECT ro_html.
ro_html->add( 'debugOutput("Browser: " + navigator.userAgent + "<br>Frontend time: " + new Date(), "debug_info");' ).
ENDMETHOD. "scripts
ENDCLASS. "lcl_gui_page_debuginfo
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_PAGE_DEBUG
*&---------------------------------------------------------------------*
CLASS lcl_gui_page_debuginfo DEFINITION FINAL INHERITING FROM lcl_gui_page.
PUBLIC SECTION.
METHODS constructor.
PROTECTED SECTION.
METHODS:
render_content REDEFINITION,
scripts REDEFINITION.
PRIVATE SECTION.
METHODS render_debug_info
RETURNING VALUE(ro_html) TYPE REF TO lcl_html
RAISING lcx_exception.
METHODS render_supported_object_types
RETURNING VALUE(rv_html) TYPE string.
ENDCLASS. "lcl_gui_page_debuginfo
CLASS lcl_gui_page_debuginfo IMPLEMENTATION.
METHOD constructor.
super->constructor( ).
ms_control-page_title = 'DEBUG INFO'.
ENDMETHOD. " constructor.
METHOD render_content.
CREATE OBJECT ro_html.
ro_html->add( '<div id="debug_info" class="debug_container">' ).
ro_html->add( render_debug_info( ) ).
ro_html->add( render_supported_object_types( ) ).
ro_html->add( '</div>' ).
ENDMETHOD. "render_content
METHOD render_debug_info.
DATA: lt_ver_tab TYPE filetable,
lv_rc TYPE i,
lv_gui_version TYPE string,
ls_version LIKE LINE OF lt_ver_tab.
cl_gui_frontend_services=>get_gui_version(
CHANGING version_table = lt_ver_tab rc = lv_rc
EXCEPTIONS OTHERS = 1 ).
READ TABLE lt_ver_tab INTO ls_version INDEX 1.
lv_gui_version = ls_version-filename.
READ TABLE lt_ver_tab INTO ls_version INDEX 2.
lv_gui_version = |{ lv_gui_version }.{ ls_version-filename }|.
CREATE OBJECT ro_html.
ro_html->add( |<p>abapGit version: { gc_abap_version }</p>| ).
ro_html->add( |<p>XML version: { gc_xml_version }</p>| ).
ro_html->add( |<p>GUI version: { lv_gui_version }</p>| ).
ro_html->add( |<p>LCL_TIME: { lcl_time=>get( ) }</p>| ).
ro_html->add( |<p>SY time: { sy-datum } { sy-uzeit } { sy-tzone }</p>| ).
ENDMETHOD. "render_debug_info
METHOD render_supported_object_types.
DATA: lt_objects TYPE STANDARD TABLE OF ko100,
lv_list TYPE string,
ls_item TYPE ty_item.
FIELD-SYMBOLS <object> LIKE LINE OF lt_objects.
CALL FUNCTION 'TR_OBJECT_TABLE'
TABLES
wt_object_text = lt_objects
EXCEPTIONS
OTHERS = 1 ##FM_SUBRC_OK.
LOOP AT lt_objects ASSIGNING <object> WHERE pgmid = 'R3TR'.
ls_item-obj_type = <object>-object.
IF lcl_objects=>is_supported( is_item = ls_item iv_native_only = abap_true ) = abap_true.
IF lv_list IS INITIAL.
lv_list = ls_item-obj_type.
ELSE.
lv_list = lv_list && `, ` && ls_item-obj_type.
ENDIF.
ENDIF.
ENDLOOP.
rv_html = |<p>Supported objects: { lv_list }</p>|.
ENDMETHOD. " render_supported_object_types
METHOD scripts.
CREATE OBJECT ro_html.
ro_html->add( 'debugOutput("Browser: " + navigator.userAgent + ' &&
'"<br>Frontend time: " + new Date(), "debug_info");' ).
ENDMETHOD. "scripts
ENDCLASS. "lcl_gui_page_debuginfo
|
fix line length
|
fix line length
|
ABAP
|
mit
|
EduardoCopat/abapGit,larshp/abapGit,sbcgua/abapGit,larshp/abapGit,nununo/abapGit,sbcgua/abapGit,apex8/abapGit,EduardoCopat/abapGit,apex8/abapGit,nununo/abapGit
|
cd3e3ae12eb63159df58cdc30839bb915158bfa4
|
src/zabapgit.prog.abap
|
src/zabapgit.prog.abap
|
REPORT zabapgit LINE-SIZE 100.
* See http://www.abapgit.org
CONSTANTS: gc_xml_version TYPE string VALUE 'v1.0.0', "#EC NOTEXT
gc_abap_version TYPE string VALUE 'v1.18.1'. "#EC NOTEXT
********************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2014 abapGit Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
********************************************************************************
SELECTION-SCREEN BEGIN OF SCREEN 1001.
* dummy for triggering screen
SELECTION-SCREEN END OF SCREEN 1001.
INCLUDE zabapgit_password_dialog. " !!! Contains SELECTION SCREEN
INCLUDE zabapgit_definitions.
INCLUDE zabapgit_macros.
INCLUDE zabapgit_exceptions.
INCLUDE zabapgit_zlib.
INCLUDE zabapgit_html.
INCLUDE zabapgit_util.
INCLUDE zabapgit_xml.
INCLUDE zabapgit_app. " Some deferred definitions here
INCLUDE zabapgit_persistence_old.
INCLUDE zabapgit_persistence.
INCLUDE zabapgit_dot_abapgit.
INCLUDE zabapgit_sap_package.
INCLUDE zabapgit_stage.
INCLUDE zabapgit_git_helpers.
INCLUDE zabapgit_repo.
INCLUDE zabapgit_stage_logic.
INCLUDE zabapgit_git.
INCLUDE zabapgit_objects.
INCLUDE zabapgit_tadir.
INCLUDE zabapgit_file_status.
INCLUDE zabapgit_popups.
INCLUDE zabapgit_zip.
INCLUDE zabapgit_objects_impl.
INCLUDE zabapgit_object_serializing. " All serializing classes here
INCLUDE zabapgit_repo_impl.
INCLUDE zabapgit_background.
INCLUDE zabapgit_transport.
INCLUDE zabapgit_services. " All services here
INCLUDE zabapgit_gui_pages. " All GUI pages here
INCLUDE zabapgit_gui_pages_userexit IF FOUND.
INCLUDE zabapgit_gui_router.
INCLUDE zabapgit_gui.
INCLUDE zabapgit_app_impl.
INCLUDE zabapgit_unit_test.
INCLUDE zabapgit_forms.
**********************************************************************
INITIALIZATION.
lcl_password_dialog=>on_screen_init( ).
START-OF-SELECTION.
PERFORM run.
* Hide Execute button from screen
AT SELECTION-SCREEN OUTPUT.
IF sy-dynnr = lcl_password_dialog=>dynnr.
lcl_password_dialog=>on_screen_output( ).
ELSE.
PERFORM output.
ENDIF.
* SAP back command re-direction
AT SELECTION-SCREEN ON EXIT-COMMAND.
PERFORM exit.
AT SELECTION-SCREEN.
IF sy-dynnr = lcl_password_dialog=>dynnr.
lcl_password_dialog=>on_screen_event( sscrfields-ucomm ).
ENDIF.
|
REPORT zabapgit LINE-SIZE 100.
* See http://www.abapgit.org
CONSTANTS: gc_xml_version TYPE string VALUE 'v1.0.0', "#EC NOTEXT
gc_abap_version TYPE string VALUE 'v1.18.2'. "#EC NOTEXT
********************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2014 abapGit Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
********************************************************************************
SELECTION-SCREEN BEGIN OF SCREEN 1001.
* dummy for triggering screen
SELECTION-SCREEN END OF SCREEN 1001.
INCLUDE zabapgit_password_dialog. " !!! Contains SELECTION SCREEN
INCLUDE zabapgit_definitions.
INCLUDE zabapgit_macros.
INCLUDE zabapgit_exceptions.
INCLUDE zabapgit_zlib.
INCLUDE zabapgit_html.
INCLUDE zabapgit_util.
INCLUDE zabapgit_xml.
INCLUDE zabapgit_app. " Some deferred definitions here
INCLUDE zabapgit_persistence_old.
INCLUDE zabapgit_persistence.
INCLUDE zabapgit_dot_abapgit.
INCLUDE zabapgit_sap_package.
INCLUDE zabapgit_stage.
INCLUDE zabapgit_git_helpers.
INCLUDE zabapgit_repo.
INCLUDE zabapgit_stage_logic.
INCLUDE zabapgit_git.
INCLUDE zabapgit_objects.
INCLUDE zabapgit_tadir.
INCLUDE zabapgit_file_status.
INCLUDE zabapgit_popups.
INCLUDE zabapgit_zip.
INCLUDE zabapgit_objects_impl.
INCLUDE zabapgit_object_serializing. " All serializing classes here
INCLUDE zabapgit_repo_impl.
INCLUDE zabapgit_background.
INCLUDE zabapgit_transport.
INCLUDE zabapgit_services. " All services here
INCLUDE zabapgit_gui_pages. " All GUI pages here
INCLUDE zabapgit_gui_pages_userexit IF FOUND.
INCLUDE zabapgit_gui_router.
INCLUDE zabapgit_gui.
INCLUDE zabapgit_app_impl.
INCLUDE zabapgit_unit_test.
INCLUDE zabapgit_forms.
**********************************************************************
INITIALIZATION.
lcl_password_dialog=>on_screen_init( ).
START-OF-SELECTION.
PERFORM run.
* Hide Execute button from screen
AT SELECTION-SCREEN OUTPUT.
IF sy-dynnr = lcl_password_dialog=>dynnr.
lcl_password_dialog=>on_screen_output( ).
ELSE.
PERFORM output.
ENDIF.
* SAP back command re-direction
AT SELECTION-SCREEN ON EXIT-COMMAND.
PERFORM exit.
AT SELECTION-SCREEN.
IF sy-dynnr = lcl_password_dialog=>dynnr.
lcl_password_dialog=>on_screen_event( sscrfields-ucomm ).
ENDIF.
|
bump version to v1.18.2
|
bump version to v1.18.2
|
ABAP
|
mit
|
larshp/abapGit,sbcgua/abapGit,EduardoCopat/abapGit,larshp/abapGit,nununo/abapGit,apex8/abapGit,sbcgua/abapGit,apex8/abapGit,nununo/abapGit,EduardoCopat/abapGit
|
703c103e73e64f72b2e177d3642dbc8a4a60f5cc
|
src/zabapgit_object_form.prog.abap
|
src/zabapgit_object_form.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_FORM
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_form DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_object_form DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
PRIVATE SECTION.
CONSTANTS: c_objectname_form TYPE thead-tdobject VALUE 'FORM' ##NO_TEXT.
CONSTANTS: c_extension_xml TYPE string VALUE 'xml' ##NO_TEXT.
CONSTANTS: c_tdid_default TYPE thead-tdid VALUE 'DEF' ##NO_TEXT.
TYPES: tyt_header TYPE STANDARD TABLE OF thead WITH DEFAULT KEY.
TYPES: tyt_lines TYPE tline_tab.
METHODS _get_last_changes
IMPORTING iv_form_name TYPE ty_item-obj_name
RETURNING VALUE(es_last_changed) TYPE thead.
METHODS _build_extr_from_header
IMPORTING
ls_header TYPE LINE OF tyt_header
RETURNING
VALUE(r_result) TYPE string.
ENDCLASS.
*----------------------------------------------------------------------*
* CLASS lcl_object_form IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS lcl_object_form IMPLEMENTATION.
METHOD lif_object~has_changed_since.
DATA: ls_last_changed TYPE thead.
DATA: lv_last_changed_ts TYPE timestamp.
ls_last_changed = _get_last_changes( ms_item-obj_name ).
CONVERT DATE ls_last_changed-tdldate TIME ls_last_changed-tdltime
INTO TIME STAMP lv_last_changed_ts TIME ZONE sy-zonlo.
rv_changed = boolc( sy-subrc <> 0 OR lv_last_changed_ts > iv_timestamp ).
ENDMETHOD.
METHOD lif_object~changed_by.
DATA: ls_last_changed TYPE thead.
ls_last_changed = _get_last_changes( ms_item-obj_name ).
IF ls_last_changed-tdluser IS NOT INITIAL.
rv_user = ls_last_changed-tdluser.
ELSE.
rv_user = c_user_unknown.
ENDIF.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
rs_metadata-delete_tadir = abap_true.
ENDMETHOD.
METHOD lif_object~exists.
DATA: lv_form_name TYPE thead-tdform.
lv_form_name = ms_item-obj_name.
CALL FUNCTION 'READ_FORM'
EXPORTING
form = lv_form_name
IMPORTING
found = rv_bool.
ENDMETHOD.
METHOD lif_object~jump.
DATA: lt_bdcdata TYPE TABLE OF bdcdata.
FIELD-SYMBOLS: <ls_bdcdata> LIKE LINE OF lt_bdcdata.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-program = 'SAPMSSCF' ##NO_TEXT.
<ls_bdcdata>-dynpro = '1102' ##NO_TEXT.
<ls_bdcdata>-dynbegin = abap_true.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'BDC_OKCODE' ##NO_TEXT.
<ls_bdcdata>-fval = '=SHOW' ##NO_TEXT.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'RSSCF-TDFORM' ##NO_TEXT.
<ls_bdcdata>-fval = ms_item-obj_name.
CALL FUNCTION 'ABAP4_CALL_TRANSACTION'
STARTING NEW TASK 'GIT'
EXPORTING
tcode = 'SE71'
mode_val = 'E'
TABLES
using_tab = lt_bdcdata
EXCEPTIONS
OTHERS = 1
##fm_subrc_ok. "#EC CI_SUBRC
ENDMETHOD.
METHOD lif_object~delete.
DATA: lv_name TYPE thead-tdname.
lv_name = ms_item-obj_name.
CALL FUNCTION 'DELETE_TEXT'
EXPORTING
id = 'TXT'
language = '*'
name = lv_name
object = c_objectname_form
EXCEPTIONS
OTHERS = 1.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DELETE_TEXT TXT, FORM' ) ##NO_TEXT.
ENDIF.
lv_name+16(3) = '* '.
CALL FUNCTION 'DELETE_TEXT'
EXPORTING
id = c_tdid_default
language = '*'
name = lv_name
object = c_objectname_form
EXCEPTIONS
OTHERS = 1.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DELETE_TEXT DEF, FORM' ) ##NO_TEXT.
ENDIF.
ENDMETHOD.
METHOD lif_object~serialize.
DATA: lt_form TYPE tyt_header.
DATA: ls_header TYPE LINE OF tyt_header.
DATA: lt_lines TYPE tyt_lines.
DATA: lv_name TYPE thead-tdname.
DATA: lt_header TYPE tyt_header.
DATA: lv_string TYPE string.
DATA: lo_xml TYPE REF TO lcl_xml_output.
FIELD-SYMBOLS: <ls_header> TYPE LINE OF tyt_header.
lv_name = ms_item-obj_name.
CALL FUNCTION 'SELECT_TEXT'
EXPORTING
database_only = abap_true
id = '*'
language = '*'
name = lv_name
object = c_objectname_form
TABLES
selections = lt_header
EXCEPTIONS
OTHERS = 1
##fm_subrc_ok. "#EC CI_SUBRC
LOOP AT lt_header ASSIGNING <ls_header>.
CLEAR ls_header.
CLEAR lt_lines.
FREE lo_xml.
CALL FUNCTION 'READ_TEXT'
EXPORTING
id = <ls_header>-tdid
language = <ls_header>-tdspras
name = <ls_header>-tdname
object = <ls_header>-tdobject
IMPORTING
header = ls_header
TABLES
lines = lt_lines
EXCEPTIONS
OTHERS = 1
##fm_subrc_ok. "#EC CI_SUBRC
CLEAR: ls_header-tdfuser,
ls_header-tdfdate,
ls_header-tdftime,
ls_header-tdfreles,
ls_header-tdluser,
ls_header-tdldate,
ls_header-tdltime,
ls_header-tdlreles.
CREATE OBJECT lo_xml.
lo_xml->add( iv_name = 'TLINES'
ig_data = lt_lines ).
lv_string = lo_xml->render( ).
IF lv_string IS NOT INITIAL.
mo_files->add_string( iv_extra = _build_extr_from_header( ls_header )
iv_ext = c_extension_xml
iv_string = lv_string ).
ENDIF.
INSERT ls_header INTO TABLE lt_form.
ENDLOOP.
IF lt_form IS NOT INITIAL.
io_xml->add( iv_name = c_objectname_form
ig_data = lt_form ).
ENDIF.
ENDMETHOD.
METHOD lif_object~deserialize.
DATA: lt_form TYPE tyt_header.
DATA: lt_lines TYPE tyt_lines.
DATA: lv_string TYPE string.
DATA: lo_xml TYPE REF TO lcl_xml_input.
FIELD-SYMBOLS: <ls_header> TYPE LINE OF tyt_header.
io_xml->read( EXPORTING iv_name = c_objectname_form
CHANGING cg_data = lt_form ).
LOOP AT lt_form ASSIGNING <ls_header>.
lv_string = mo_files->read_string( iv_extra = _build_extr_from_header( <ls_header> )
iv_ext = c_extension_xml ).
CREATE OBJECT lo_xml EXPORTING iv_xml = lv_string.
lo_xml->read( EXPORTING iv_name = 'TLINES'
CHANGING cg_data = lt_lines ).
IF <ls_header>-tdid = c_tdid_default.
CALL FUNCTION 'SAPSCRIPT_CHANGE_OLANGUAGE'
EXPORTING
forced = abap_true
name = <ls_header>-tdname
object = <ls_header>-tdobject
olanguage = <ls_header>-tdspras
EXCEPTIONS
OTHERS = 1
##fm_subrc_ok. "#EC CI_SUBRC
ENDIF.
CALL FUNCTION 'SAVE_TEXT'
EXPORTING
header = <ls_header>
savemode_direct = abap_true
TABLES
lines = lt_lines
EXCEPTIONS
OTHERS = 1.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from SAVE_TEXT, FORM' ) ##NO_TEXT.
ENDIF.
ENDLOOP.
CALL FUNCTION 'SAPSCRIPT_DELETE_LOAD'
EXPORTING
delete = abap_true
form = '*'
write = space.
tadir_insert( iv_package ).
ENDMETHOD.
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_null_comparison_result.
ENDMETHOD.
METHOD _build_extr_from_header.
r_result = ls_header-tdid && '_' && ls_header-tdspras.
ENDMETHOD.
METHOD _get_last_changes.
DATA: lv_name TYPE thead-tdname.
DATA: lt_header TYPE tyt_header.
FIELD-SYMBOLS: <ls_header> TYPE LINE OF tyt_header.
CLEAR es_last_changed.
lv_name = ms_item-obj_name.
CALL FUNCTION 'SELECT_TEXT'
EXPORTING
database_only = abap_true
id = '*'
language = '*'
name = lv_name
object = c_objectname_form
TABLES
selections = lt_header
EXCEPTIONS
OTHERS = 1
##fm_subrc_ok. "#EC CI_SUBRC
LOOP AT lt_header ASSIGNING <ls_header>.
IF <ls_header>-tdldate > es_last_changed-tdldate OR
<ls_header>-tdldate = es_last_changed-tdldate AND
<ls_header>-tdltime > es_last_changed-tdltime.
es_last_changed = <ls_header>.
ENDIF.
ENDLOOP.
ENDMETHOD.
ENDCLASS. "lcl_object_FORM IMPLEMENTATION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_FORM
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_form DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_object_form DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
PRIVATE SECTION.
CONSTANTS: c_objectname_form TYPE thead-tdobject VALUE 'FORM' ##NO_TEXT.
CONSTANTS: c_extension_xml TYPE string VALUE 'xml' ##NO_TEXT.
CONSTANTS: c_tdid_default TYPE thead-tdid VALUE 'DEF' ##NO_TEXT.
TYPES: tyt_header TYPE STANDARD TABLE OF thead WITH DEFAULT KEY.
TYPES: tys_header TYPE LINE OF tyt_header.
TYPES: tyt_lines TYPE tline_tab.
METHODS _get_last_changes
IMPORTING
iv_form_name TYPE ty_item-obj_name
RETURNING
VALUE(es_last_changed) TYPE thead.
METHODS _build_extr_from_header
IMPORTING
ls_header TYPE tys_header
RETURNING
VALUE(r_result) TYPE string.
ENDCLASS.
*----------------------------------------------------------------------*
* CLASS lcl_object_form IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS lcl_object_form IMPLEMENTATION.
METHOD lif_object~has_changed_since.
DATA: ls_last_changed TYPE thead.
DATA: lv_last_changed_ts TYPE timestamp.
ls_last_changed = _get_last_changes( ms_item-obj_name ).
CONVERT DATE ls_last_changed-tdldate TIME ls_last_changed-tdltime
INTO TIME STAMP lv_last_changed_ts TIME ZONE sy-zonlo.
rv_changed = boolc( sy-subrc <> 0 OR lv_last_changed_ts > iv_timestamp ).
ENDMETHOD.
METHOD lif_object~changed_by.
DATA: ls_last_changed TYPE thead.
ls_last_changed = _get_last_changes( ms_item-obj_name ).
IF ls_last_changed-tdluser IS NOT INITIAL.
rv_user = ls_last_changed-tdluser.
ELSE.
rv_user = c_user_unknown.
ENDIF.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
rs_metadata-delete_tadir = abap_true.
ENDMETHOD.
METHOD lif_object~exists.
DATA: lv_form_name TYPE thead-tdform.
lv_form_name = ms_item-obj_name.
CALL FUNCTION 'READ_FORM'
EXPORTING
form = lv_form_name
IMPORTING
found = rv_bool.
ENDMETHOD.
METHOD lif_object~jump.
DATA: lt_bdcdata TYPE TABLE OF bdcdata.
FIELD-SYMBOLS: <ls_bdcdata> LIKE LINE OF lt_bdcdata.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-program = 'SAPMSSCF' ##NO_TEXT.
<ls_bdcdata>-dynpro = '1102' ##NO_TEXT.
<ls_bdcdata>-dynbegin = abap_true.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'BDC_OKCODE' ##NO_TEXT.
<ls_bdcdata>-fval = '=SHOW' ##NO_TEXT.
APPEND INITIAL LINE TO lt_bdcdata ASSIGNING <ls_bdcdata>.
<ls_bdcdata>-fnam = 'RSSCF-TDFORM' ##NO_TEXT.
<ls_bdcdata>-fval = ms_item-obj_name.
CALL FUNCTION 'ABAP4_CALL_TRANSACTION'
STARTING NEW TASK 'GIT'
EXPORTING
tcode = 'SE71'
mode_val = 'E'
TABLES
using_tab = lt_bdcdata
EXCEPTIONS
OTHERS = 1
##fm_subrc_ok. "#EC CI_SUBRC
ENDMETHOD.
METHOD lif_object~delete.
DATA: lv_name TYPE thead-tdname.
lv_name = ms_item-obj_name.
CALL FUNCTION 'DELETE_TEXT'
EXPORTING
id = 'TXT'
language = '*'
name = lv_name
object = c_objectname_form
EXCEPTIONS
OTHERS = 1.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DELETE_TEXT TXT, FORM' ) ##NO_TEXT.
ENDIF.
lv_name+16(3) = '* '.
CALL FUNCTION 'DELETE_TEXT'
EXPORTING
id = c_tdid_default
language = '*'
name = lv_name
object = c_objectname_form
EXCEPTIONS
OTHERS = 1.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from DELETE_TEXT DEF, FORM' ) ##NO_TEXT.
ENDIF.
ENDMETHOD.
METHOD lif_object~serialize.
DATA: lt_form TYPE tyt_header.
DATA: ls_header TYPE LINE OF tyt_header.
DATA: lt_lines TYPE tyt_lines.
DATA: lv_name TYPE thead-tdname.
DATA: lt_header TYPE tyt_header.
DATA: lv_string TYPE string.
DATA: lo_xml TYPE REF TO lcl_xml_output.
FIELD-SYMBOLS: <ls_header> TYPE LINE OF tyt_header.
lv_name = ms_item-obj_name.
CALL FUNCTION 'SELECT_TEXT'
EXPORTING
database_only = abap_true
id = '*'
language = '*'
name = lv_name
object = c_objectname_form
TABLES
selections = lt_header
EXCEPTIONS
OTHERS = 1
##fm_subrc_ok. "#EC CI_SUBRC
LOOP AT lt_header ASSIGNING <ls_header>.
CLEAR ls_header.
CLEAR lt_lines.
FREE lo_xml.
CALL FUNCTION 'READ_TEXT'
EXPORTING
id = <ls_header>-tdid
language = <ls_header>-tdspras
name = <ls_header>-tdname
object = <ls_header>-tdobject
IMPORTING
header = ls_header
TABLES
lines = lt_lines
EXCEPTIONS
OTHERS = 1
##fm_subrc_ok. "#EC CI_SUBRC
CLEAR: ls_header-tdfuser,
ls_header-tdfdate,
ls_header-tdftime,
ls_header-tdfreles,
ls_header-tdluser,
ls_header-tdldate,
ls_header-tdltime,
ls_header-tdlreles.
CREATE OBJECT lo_xml.
lo_xml->add( iv_name = 'TLINES'
ig_data = lt_lines ).
lv_string = lo_xml->render( ).
IF lv_string IS NOT INITIAL.
mo_files->add_string( iv_extra = _build_extr_from_header( ls_header )
iv_ext = c_extension_xml
iv_string = lv_string ).
ENDIF.
INSERT ls_header INTO TABLE lt_form.
ENDLOOP.
IF lt_form IS NOT INITIAL.
io_xml->add( iv_name = c_objectname_form
ig_data = lt_form ).
ENDIF.
ENDMETHOD.
METHOD lif_object~deserialize.
DATA: lt_form TYPE tyt_header.
DATA: lt_lines TYPE tyt_lines.
DATA: lv_string TYPE string.
DATA: lo_xml TYPE REF TO lcl_xml_input.
FIELD-SYMBOLS: <ls_header> TYPE LINE OF tyt_header.
io_xml->read( EXPORTING iv_name = c_objectname_form
CHANGING cg_data = lt_form ).
LOOP AT lt_form ASSIGNING <ls_header>.
lv_string = mo_files->read_string( iv_extra = _build_extr_from_header( <ls_header> )
iv_ext = c_extension_xml ).
CREATE OBJECT lo_xml EXPORTING iv_xml = lv_string.
lo_xml->read( EXPORTING iv_name = 'TLINES'
CHANGING cg_data = lt_lines ).
IF <ls_header>-tdid = c_tdid_default.
CALL FUNCTION 'SAPSCRIPT_CHANGE_OLANGUAGE'
EXPORTING
forced = abap_true
name = <ls_header>-tdname
object = <ls_header>-tdobject
olanguage = <ls_header>-tdspras
EXCEPTIONS
OTHERS = 1
##fm_subrc_ok. "#EC CI_SUBRC
ENDIF.
CALL FUNCTION 'SAVE_TEXT'
EXPORTING
header = <ls_header>
savemode_direct = abap_true
TABLES
lines = lt_lines
EXCEPTIONS
OTHERS = 1.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from SAVE_TEXT, FORM' ) ##NO_TEXT.
ENDIF.
ENDLOOP.
CALL FUNCTION 'SAPSCRIPT_DELETE_LOAD'
EXPORTING
delete = abap_true
form = '*'
write = space.
tadir_insert( iv_package ).
ENDMETHOD.
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_null_comparison_result.
ENDMETHOD.
METHOD _build_extr_from_header.
r_result = ls_header-tdid && '_' && ls_header-tdspras.
ENDMETHOD.
METHOD _get_last_changes.
DATA: lv_name TYPE thead-tdname.
DATA: lt_header TYPE tyt_header.
FIELD-SYMBOLS: <ls_header> TYPE LINE OF tyt_header.
CLEAR es_last_changed.
lv_name = ms_item-obj_name.
CALL FUNCTION 'SELECT_TEXT'
EXPORTING
database_only = abap_true
id = '*'
language = '*'
name = lv_name
object = c_objectname_form
TABLES
selections = lt_header
EXCEPTIONS
OTHERS = 1
##fm_subrc_ok. "#EC CI_SUBRC
LOOP AT lt_header ASSIGNING <ls_header>.
IF <ls_header>-tdldate > es_last_changed-tdldate OR
<ls_header>-tdldate = es_last_changed-tdldate AND
<ls_header>-tdltime > es_last_changed-tdltime.
es_last_changed = <ls_header>.
ENDIF.
ENDLOOP.
ENDMETHOD.
ENDCLASS. "lcl_object_FORM IMPLEMENTATION
|
fix abaplint error #751
|
fix abaplint error #751
|
ABAP
|
mit
|
larshp/abapGit,larshp/abapGit,sbcgua/abapGit,EduardoCopat/abapGit,sbcgua/abapGit,apex8/abapGit,apex8/abapGit,EduardoCopat/abapGit
|
6b8f63e36472ccefd90172e1512625afca3ec580
|
src/zabapgit_object_susc.prog.abap
|
src/zabapgit_object_susc.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_SUSC
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_susc DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_susc DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
ENDCLASS. "lcl_object_susc DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_susc IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_susc IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
rv_user = c_user_unknown. " todo
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD lif_object~exists.
DATA: lv_oclss TYPE tobc-oclss.
SELECT SINGLE oclss FROM tobc INTO lv_oclss
WHERE oclss = ms_item-obj_name.
rv_bool = boolc( sy-subrc = 0 ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~serialize.
DATA: ls_tobc TYPE tobc,
ls_tobct TYPE tobct.
SELECT SINGLE * FROM tobc INTO ls_tobc
WHERE oclss = ms_item-obj_name.
IF sy-subrc <> 0.
RETURN.
ENDIF.
SELECT SINGLE * FROM tobct INTO ls_tobct
WHERE oclss = ms_item-obj_name
AND langu = mv_language.
IF sy-subrc <> 0.
lcx_exception=>raise( 'TOBCT no english description' ).
ENDIF.
io_xml->add( iv_name = 'TOBC'
ig_data = ls_tobc ).
io_xml->add( iv_name = 'TOBCT'
ig_data = ls_tobct ).
ENDMETHOD. "serialize
METHOD lif_object~deserialize.
* see function group SUSA
DATA: ls_tobc TYPE tobc,
lv_objectname TYPE e071-obj_name,
ls_tobct TYPE tobct.
io_xml->read( EXPORTING iv_name = 'TOBC'
CHANGING cg_data = ls_tobc ).
io_xml->read( EXPORTING iv_name = 'TOBCT'
CHANGING cg_data = ls_tobct ).
lv_objectname = ms_item-obj_name.
CALL FUNCTION 'SUSR_COMMEDITCHECK'
EXPORTING
objectname = lv_objectname
transobjecttype = 'C'.
INSERT tobc FROM ls_tobc. "#EC CI_SUBRC
* ignore sy-subrc as all fields are key fields
MODIFY tobct FROM ls_tobct. "#EC CI_SUBRC
ASSERT sy-subrc = 0.
ENDMETHOD. "deserialize
METHOD lif_object~delete.
DATA: lv_objclass TYPE tobc-oclss.
lv_objclass = ms_item-obj_name.
CALL FUNCTION 'SUSR_DELETE_OBJECT_CLASS'
EXPORTING
objclass = lv_objclass.
ENDMETHOD. "delete
METHOD lif_object~jump.
DATA: lv_objclass TYPE tobc-oclss.
lv_objclass = ms_item-obj_name.
CALL FUNCTION 'SUSR_SHOW_OBJECT_CLASS'
EXPORTING
objclass = lv_objclass.
ENDMETHOD. "jump
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_null_comparison_result.
ENDMETHOD.
ENDCLASS. "lcl_object_susc IMPLEMENTATION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_SUSC
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_susc DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_susc DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
ENDCLASS. "lcl_object_susc DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_susc IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_susc IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
rv_user = c_user_unknown. " todo
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
rs_metadata-delete_tadir = abap_true.
ENDMETHOD. "lif_object~get_metadata
METHOD lif_object~exists.
DATA: lv_oclss TYPE tobc-oclss.
SELECT SINGLE oclss FROM tobc INTO lv_oclss
WHERE oclss = ms_item-obj_name.
rv_bool = boolc( sy-subrc = 0 ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~serialize.
DATA: ls_tobc TYPE tobc,
ls_tobct TYPE tobct.
SELECT SINGLE * FROM tobc INTO ls_tobc
WHERE oclss = ms_item-obj_name.
IF sy-subrc <> 0.
RETURN.
ENDIF.
SELECT SINGLE * FROM tobct INTO ls_tobct
WHERE oclss = ms_item-obj_name
AND langu = mv_language.
IF sy-subrc <> 0.
lcx_exception=>raise( 'TOBCT no english description' ).
ENDIF.
io_xml->add( iv_name = 'TOBC'
ig_data = ls_tobc ).
io_xml->add( iv_name = 'TOBCT'
ig_data = ls_tobct ).
ENDMETHOD. "serialize
METHOD lif_object~deserialize.
* see function group SUSA
DATA: ls_tobc TYPE tobc,
lv_objectname TYPE e071-obj_name,
ls_tobct TYPE tobct.
io_xml->read( EXPORTING iv_name = 'TOBC'
CHANGING cg_data = ls_tobc ).
io_xml->read( EXPORTING iv_name = 'TOBCT'
CHANGING cg_data = ls_tobct ).
lv_objectname = ms_item-obj_name.
CALL FUNCTION 'SUSR_COMMEDITCHECK'
EXPORTING
objectname = lv_objectname
transobjecttype = 'C'.
INSERT tobc FROM ls_tobc. "#EC CI_SUBRC
* ignore sy-subrc as all fields are key fields
MODIFY tobct FROM ls_tobct. "#EC CI_SUBRC
ASSERT sy-subrc = 0.
ENDMETHOD. "deserialize
METHOD lif_object~delete.
DATA: lv_objclass TYPE tobc-oclss.
lv_objclass = ms_item-obj_name.
CALL FUNCTION 'SUSR_DELETE_OBJECT_CLASS'
EXPORTING
objclass = lv_objclass.
ENDMETHOD. "delete
METHOD lif_object~jump.
DATA: lv_objclass TYPE tobc-oclss.
lv_objclass = ms_item-obj_name.
CALL FUNCTION 'SUSR_SHOW_OBJECT_CLASS'
EXPORTING
objclass = lv_objclass.
ENDMETHOD. "jump
METHOD lif_object~compare_to_remote_version.
CREATE OBJECT ro_comparison_result TYPE lcl_null_comparison_result.
ENDMETHOD.
ENDCLASS. "lcl_object_susc IMPLEMENTATION
|
Enable tadir deletion of SUSC
|
Enable tadir deletion of SUSC
|
ABAP
|
mit
|
apex8/abapGit,apex8/abapGit,larshp/abapGit,nununo/abapGit,EduardoCopat/abapGit,nununo/abapGit,EduardoCopat/abapGit,sbcgua/abapGit,larshp/abapGit,sbcgua/abapGit
|
9c053763b7f73f59609028f9294b808c4792d27f
|
src/zabapgit_object_nrob.prog.abap
|
src/zabapgit_object_nrob.prog.abap
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_NROB
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_nrob DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_nrob DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
ENDCLASS. "lcl_object_nrob DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_nrob IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_nrob IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
DATA: lv_objectid TYPE cdhdr-objectid,
lt_cdhdr TYPE cdhdr_tab.
FIELD-SYMBOLS: <ls_cdhdr> LIKE LINE OF lt_cdhdr.
lv_objectid = ms_item-obj_name.
CALL FUNCTION 'CHANGEDOCUMENT_READ_HEADERS'
EXPORTING
objectclass = 'NRKROBJ'
objectid = lv_objectid
TABLES
i_cdhdr = lt_cdhdr
EXCEPTIONS
no_position_found = 1
wrong_access_to_archive = 2
time_zone_conversion_error = 3
OTHERS = 4.
IF sy-subrc <> 0.
rv_user = c_user_unknown.
RETURN.
ENDIF.
SORT lt_cdhdr BY udate DESCENDING utime DESCENDING.
READ TABLE lt_cdhdr INDEX 1 ASSIGNING <ls_cdhdr>.
ASSERT sy-subrc = 0.
rv_user = <ls_cdhdr>-username.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD lif_object~exists.
DATA: lv_object TYPE tnro-object.
SELECT SINGLE object FROM tnro INTO lv_object
WHERE object = ms_item-obj_name.
rv_bool = boolc( sy-subrc = 0 ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~serialize.
DATA: lv_object TYPE tnro-object,
ls_attributes TYPE tnro,
ls_text TYPE tnrot.
lv_object = ms_item-obj_name.
CALL FUNCTION 'NUMBER_RANGE_OBJECT_READ'
EXPORTING
language = mv_language
object = lv_object
IMPORTING
object_attributes = ls_attributes
object_text = ls_text
EXCEPTIONS
object_not_found = 1
OTHERS = 2.
IF sy-subrc = 1.
RETURN.
ELSEIF sy-subrc <> 0.
lcx_exception=>raise( 'error from NUMBER_RANGE_OBJECT_READ' ).
ENDIF.
io_xml->add( iv_name = 'ATTRIBUTES'
ig_data = ls_attributes ).
io_xml->add( iv_name = 'TEXT'
ig_data = ls_text ).
ENDMETHOD. "serialize
METHOD lif_object~deserialize.
DATA: lt_errors TYPE TABLE OF inoer,
ls_attributes TYPE tnro,
ls_text TYPE tnrot.
io_xml->read( EXPORTING iv_name = 'ATTRIBUTES'
CHANGING cg_data = ls_attributes ).
io_xml->read( EXPORTING iv_name = 'TEXT'
CHANGING cg_data = ls_text ).
CALL FUNCTION 'NUMBER_RANGE_OBJECT_UPDATE'
EXPORTING
indicator = 'I'
object_attributes = ls_attributes
object_text = ls_text
TABLES
errors = lt_errors
EXCEPTIONS
object_already_exists = 1
object_attributes_missing = 2
object_not_found = 3
object_text_missing = 4
wrong_indicator = 5
OTHERS = 6.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from NUMBER_RANGE_OBJECT_UPDATE' ).
ENDIF.
CALL FUNCTION 'NUMBER_RANGE_OBJECT_CLOSE'
EXPORTING
object = ls_attributes-object
EXCEPTIONS
object_not_initialized = 1.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from NUMBER_RANGE_OBJECT_CLOSE' ).
ENDIF.
CALL FUNCTION 'TR_TADIR_INTERFACE'
EXPORTING
wi_test_modus = abap_false
wi_tadir_pgmid = 'R3TR'
wi_tadir_object = 'NROB'
wi_tadir_obj_name = ms_item-obj_name
wi_tadir_author = sy-uname
wi_tadir_devclass = iv_package
wi_tadir_masterlang = mv_language
wi_set_genflag = abap_true
EXCEPTIONS
OTHERS = 1.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from TR_TADIR_INTERFACE' ).
ENDIF.
ENDMETHOD. "deserialize
METHOD lif_object~delete.
DATA: lv_object TYPE tnro-object.
lv_object = ms_item-obj_name.
CALL FUNCTION 'NUMBER_RANGE_OBJECT_DELETE'
EXPORTING
language = mv_language
object = lv_object
EXCEPTIONS
delete_not_allowed = 1
object_not_found = 2
wrong_indicator = 3
OTHERS = 4.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from NUMBER_RANGE_OBJECT_DELETE' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~jump.
lcx_exception=>raise( 'todo' ).
ENDMETHOD. "jump
ENDCLASS. "lcl_object_nrob IMPLEMENTATION
|
*&---------------------------------------------------------------------*
*& Include ZABAPGIT_OBJECT_NROB
*&---------------------------------------------------------------------*
*----------------------------------------------------------------------*
* CLASS lcl_object_nrob DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_nrob DEFINITION INHERITING FROM lcl_objects_super FINAL.
PUBLIC SECTION.
INTERFACES lif_object.
ALIASES mo_files FOR lif_object~mo_files.
PRIVATE SECTION.
METHODS:
delete_intervals IMPORTING iv_object TYPE inri-object
RAISING lcx_exception.
ENDCLASS. "lcl_object_nrob DEFINITION
*----------------------------------------------------------------------*
* CLASS lcl_object_nrob IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS lcl_object_nrob IMPLEMENTATION.
METHOD lif_object~has_changed_since.
rv_changed = abap_true.
ENDMETHOD. "lif_object~has_changed_since
METHOD lif_object~changed_by.
DATA: lv_objectid TYPE cdhdr-objectid,
lt_cdhdr TYPE cdhdr_tab.
FIELD-SYMBOLS: <ls_cdhdr> LIKE LINE OF lt_cdhdr.
lv_objectid = ms_item-obj_name.
CALL FUNCTION 'CHANGEDOCUMENT_READ_HEADERS'
EXPORTING
objectclass = 'NRKROBJ'
objectid = lv_objectid
TABLES
i_cdhdr = lt_cdhdr
EXCEPTIONS
no_position_found = 1
wrong_access_to_archive = 2
time_zone_conversion_error = 3
OTHERS = 4.
IF sy-subrc <> 0.
rv_user = c_user_unknown.
RETURN.
ENDIF.
SORT lt_cdhdr BY udate DESCENDING utime DESCENDING.
READ TABLE lt_cdhdr INDEX 1 ASSIGNING <ls_cdhdr>.
ASSERT sy-subrc = 0.
rv_user = <ls_cdhdr>-username.
ENDMETHOD.
METHOD lif_object~get_metadata.
rs_metadata = get_metadata( ).
ENDMETHOD. "lif_object~get_metadata
METHOD lif_object~exists.
DATA: lv_object TYPE tnro-object.
SELECT SINGLE object FROM tnro INTO lv_object
WHERE object = ms_item-obj_name.
rv_bool = boolc( sy-subrc = 0 ).
ENDMETHOD. "lif_object~exists
METHOD lif_object~serialize.
DATA: lv_object TYPE tnro-object,
ls_attributes TYPE tnro,
ls_text TYPE tnrot.
lv_object = ms_item-obj_name.
CALL FUNCTION 'NUMBER_RANGE_OBJECT_READ'
EXPORTING
language = mv_language
object = lv_object
IMPORTING
object_attributes = ls_attributes
object_text = ls_text
EXCEPTIONS
object_not_found = 1
OTHERS = 2.
IF sy-subrc = 1.
RETURN.
ELSEIF sy-subrc <> 0.
lcx_exception=>raise( 'error from NUMBER_RANGE_OBJECT_READ' ).
ENDIF.
io_xml->add( iv_name = 'ATTRIBUTES'
ig_data = ls_attributes ).
io_xml->add( iv_name = 'TEXT'
ig_data = ls_text ).
ENDMETHOD. "serialize
METHOD lif_object~deserialize.
DATA: lt_errors TYPE TABLE OF inoer,
ls_attributes TYPE tnro,
ls_text TYPE tnrot.
io_xml->read( EXPORTING iv_name = 'ATTRIBUTES'
CHANGING cg_data = ls_attributes ).
io_xml->read( EXPORTING iv_name = 'TEXT'
CHANGING cg_data = ls_text ).
CALL FUNCTION 'NUMBER_RANGE_OBJECT_UPDATE'
EXPORTING
indicator = 'I'
object_attributes = ls_attributes
object_text = ls_text
TABLES
errors = lt_errors
EXCEPTIONS
object_already_exists = 1
object_attributes_missing = 2
object_not_found = 3
object_text_missing = 4
wrong_indicator = 5
OTHERS = 6.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from NUMBER_RANGE_OBJECT_UPDATE' ).
ENDIF.
CALL FUNCTION 'NUMBER_RANGE_OBJECT_CLOSE'
EXPORTING
object = ls_attributes-object
EXCEPTIONS
object_not_initialized = 1.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from NUMBER_RANGE_OBJECT_CLOSE' ).
ENDIF.
CALL FUNCTION 'TR_TADIR_INTERFACE'
EXPORTING
wi_test_modus = abap_false
wi_tadir_pgmid = 'R3TR'
wi_tadir_object = 'NROB'
wi_tadir_obj_name = ms_item-obj_name
wi_tadir_author = sy-uname
wi_tadir_devclass = iv_package
wi_tadir_masterlang = mv_language
wi_set_genflag = abap_true
EXCEPTIONS
OTHERS = 1.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from TR_TADIR_INTERFACE' ).
ENDIF.
ENDMETHOD. "deserialize
METHOD delete_intervals.
DATA: lv_error TYPE c LENGTH 1,
ls_error TYPE inrer,
lt_list TYPE STANDARD TABLE OF inriv WITH DEFAULT KEY,
lt_error_iv TYPE STANDARD TABLE OF inriv WITH DEFAULT KEY.
FIELD-SYMBOLS: <ls_list> LIKE LINE OF lt_list.
CALL FUNCTION 'NUMBER_RANGE_INTERVAL_LIST'
EXPORTING
object = iv_object
TABLES
interval = lt_list
EXCEPTIONS
nr_range_nr1_not_found = 1
nr_range_nr1_not_intern = 2
nr_range_nr2_must_be_space = 3
nr_range_nr2_not_extern = 4
nr_range_nr2_not_found = 5
object_not_found = 6
subobject_must_be_space = 7
subobject_not_found = 8
OTHERS = 9.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from NUMBER_RANGE_INTERVAL_LIST' ).
ENDIF.
IF lines( lt_list ) = 0.
RETURN.
ENDIF.
LOOP AT lt_list ASSIGNING <ls_list>.
CLEAR <ls_list>-nrlevel.
<ls_list>-procind = 'D'.
ENDLOOP.
CALL FUNCTION 'NUMBER_RANGE_INTERVAL_UPDATE'
EXPORTING
object = iv_object
IMPORTING
error = ls_error
error_occured = lv_error
TABLES
error_iv = lt_error_iv
interval = lt_list
EXCEPTIONS
object_not_found = 1
OTHERS = 2.
IF sy-subrc <> 0 OR lv_error = abap_true.
lcx_exception=>raise( 'error from NUMBER_RANGE_INTERVAL_UPDATE' ).
ENDIF.
CALL FUNCTION 'NUMBER_RANGE_UPDATE_CLOSE'
EXPORTING
object = iv_object
EXCEPTIONS
no_changes_made = 1
object_not_initialized = 2
OTHERS = 3.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from NUMBER_RANGE_UPDATE_CLOSE' ).
ENDIF.
ENDMETHOD.
METHOD lif_object~delete.
DATA: lv_object TYPE tnro-object.
lv_object = ms_item-obj_name.
delete_intervals( lv_object ).
CALL FUNCTION 'NUMBER_RANGE_OBJECT_DELETE'
EXPORTING
language = mv_language
object = lv_object
EXCEPTIONS
delete_not_allowed = 1
object_not_found = 2
wrong_indicator = 3
OTHERS = 4.
IF sy-subrc <> 0.
lcx_exception=>raise( 'error from NUMBER_RANGE_OBJECT_DELETE' ).
ENDIF.
ENDMETHOD. "delete
METHOD lif_object~jump.
lcx_exception=>raise( 'todo' ).
ENDMETHOD. "jump
ENDCLASS. "lcl_object_nrob IMPLEMENTATION
|
delete intervals, close #378
|
NROB: delete intervals, close #378
|
ABAP
|
mit
|
larshp/abapGit,nununo/abapGit,sbcgua/abapGit,apex8/abapGit,EduardoCopat/abapGit,sbcgua/abapGit,nununo/abapGit,EduardoCopat/abapGit,larshp/abapGit,apex8/abapGit
|
267297b8f1e2ad6a0e885dd1b98234391053fb21
|
ztest.abap
|
ztest.abap
|
REPORT ztest.
TYPES: BEGIN OF ty_alv,
program TYPE string,
class TYPE string,
method TYPE string,
seconds TYPE p DECIMALS 2,
devclass TYPE tadir-devclass,
END OF ty_alv.
TYPES: ty_alv_tt TYPE STANDARD TABLE OF ty_alv WITH EMPTY KEY.
TABLES: tadir.
SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.
SELECT-OPTIONS: s_devc FOR tadir-devclass OBLIGATORY,
s_name FOR tadir-obj_name.
SELECTION-SCREEN END OF BLOCK b1.
PARAMETERS: p_nocov TYPE c RADIOBUTTON GROUP g1,
p_cov TYPE c RADIOBUTTON GROUP g1.
PARAMETERS: p_risk TYPE saunit_d_allowed_risk_level DEFAULT '11',
p_dura TYPE saunit_d_allowed_rt_duration DEFAULT '24'.
START-OF-SELECTION.
PERFORM run.
CLASS lcl_runner DEFINITION FINAL.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING is_tadir TYPE sabp_s_tadir_key,
run
RETURNING VALUE(rt_alv) TYPE ty_alv_tt.
PRIVATE SECTION.
METHODS:
get_runner
RETURNING VALUE(ro_runner) TYPE REF TO cl_aucv_test_runner_abstract.
DATA: ms_tadir TYPE sabp_s_tadir_key.
ENDCLASS.
CLASS lcl_runner IMPLEMENTATION.
METHOD constructor.
ms_tadir = is_tadir.
ENDMETHOD.
METHOD run.
DATA: lo_casted TYPE REF TO cl_saunit_internal_result,
lv_seconds TYPE p DECIMALS 2,
t1 TYPE i,
t2 TYPE i.
GET RUN TIME FIELD t1.
get_runner( )->run_for_program_keys(
EXPORTING
i_limit_on_duration_category = p_dura
i_limit_on_risk_level = p_risk
i_program_keys = VALUE #( ( CORRESPONDING #( ms_tadir ) ) )
IMPORTING
e_coverage_result = DATA(li_coverage)
e_aunit_result = DATA(li_aunit) ).
GET RUN TIME FIELD t2.
lo_casted ?= li_aunit.
LOOP AT lo_casted->f_task_data-programs INTO DATA(ls_program).
lv_seconds = ( t2 - t1 ) / 1000000.
LOOP AT ls_program-classes INTO DATA(ls_class).
LOOP AT ls_class-methods INTO DATA(ls_method).
APPEND VALUE #(
program = ls_program-info-name
class = ls_class-info-name
method = ls_method-info-name
seconds = lv_seconds ) TO rt_alv.
CLEAR lv_seconds.
ENDLOOP.
ENDLOOP.
ENDLOOP.
ENDMETHOD.
METHOD get_runner.
DATA: lo_passport TYPE REF TO object.
CALL METHOD ('\PROGRAM=SAPLSAUCV_GUI_RUNNER\CLASS=PASSPORT')=>get
RECEIVING
result = lo_passport.
IF p_cov = abap_true.
ro_runner = cl_aucv_test_runner_coverage=>create( lo_passport ).
ELSE.
ro_runner = cl_aucv_test_runner_standard=>create( lo_passport ).
ENDIF.
ENDMETHOD.
ENDCLASS.
FORM run RAISING cx_salv_msg.
DATA: lt_alv TYPE ty_alv_tt.
SELECT obj_name, object, devclass FROM tadir
INTO TABLE @DATA(lt_tadir)
WHERE devclass IN @s_devc
AND obj_name IN @s_name
AND object = 'CLAS'.
LOOP AT lt_tadir INTO DATA(ls_tadir).
cl_progress_indicator=>progress_indicate(
i_text = |Processing { sy-tabix }/{ lines( lt_tadir ) }|
i_processed = sy-tabix
i_total = lines( lt_tadir )
i_output_immediately = abap_true ).
DATA(ls_aunit_info) = cl_aunit_prog_info=>get_program_info(
allow_commit = abap_true
obj_type = ls_tadir-object
obj_name = ls_tadir-obj_name ).
IF ls_aunit_info-has_tests = abap_false.
CONTINUE.
ENDIF.
DATA(ls_key) = VALUE sabp_s_tadir_key(
obj_name = ls_tadir-obj_name
obj_type = ls_tadir-object ).
DATA(lt_lines) = NEW lcl_runner( ls_key )->run( ).
LOOP AT lt_lines ASSIGNING FIELD-SYMBOL(<ls_line>).
<ls_line>-devclass = ls_tadir-devclass.
ENDLOOP.
APPEND LINES OF lt_lines TO lt_alv.
ENDLOOP.
cl_salv_table=>factory(
IMPORTING
r_salv_table = DATA(lo_alv)
CHANGING
t_table = lt_alv ).
lo_alv->get_columns( )->set_optimize( ).
lo_alv->get_functions( )->set_all( ).
lo_alv->display( ).
ENDFORM.
|
Create ztest.abap
|
Create ztest.abap
|
ABAP
|
mit
|
larshp/abapOpenTest,larshp/abapOpenTest
|
|
3ffdce4a12934e83d207c71816aec9f00e9cf5f2
|
src/aerys/minko/render/resource/Context3DResource.as
|
src/aerys/minko/render/resource/Context3DResource.as
|
package aerys.minko.render.resource
{
import flash.display.BitmapData;
import flash.display3D.Context3D;
import flash.display3D.IndexBuffer3D;
import flash.display3D.Program3D;
import flash.display3D.VertexBuffer3D;
import flash.display3D.textures.CubeTexture;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Rectangle;
import aerys.minko.ns.minko_render;
public final class Context3DResource
{
private var _context : Context3D;
private var _enableErrorChecking : Boolean;
private var _rttTarget : TextureBase;
private var _rttDepthAndStencil : Boolean;
private var _rttAntiAliasing : int;
private var _rttSurfaceSelector : int;
private var _rectangle : Rectangle;
private var _depthMask : Boolean;
private var _passCompareMode : String;
private var _program : Program3D;
private var _blendingSource : String;
private var _blendingDestination : String;
private var _triangleCulling : String;
private var _vertexBuffers : Vector.<VertexBuffer3D>;
private var _vertexBuffersOffsets : Vector.<int>;
private var _vertexBuffersFormats : Vector.<String>;
private var _textures : Vector.<TextureBase>;
private var _colorMaskRed : Boolean;
private var _colorMaskGreen : Boolean;
private var _colorMaskBlue : Boolean;
private var _colorMaskAlpha : Boolean;
private var _stencilRefNum : uint;
private var _stencilReadMask : uint;
private var _stencilWriteMask : uint;
private var _stencilTriangleFace : String;
private var _stencilCompareMode : String;
private var _stencilActionOnBothPass : String;
private var _stencilActionOnDepthFail : String;
private var _stencilActionOnDepthPassStencilFail : String;
minko_render function get context() : Context3D
{
return _context;
}
public function get enabledErrorChecking() : Boolean
{
return _enableErrorChecking;
}
public function set enableErrorChecking(value : Boolean) : void
{
if (value != _enableErrorChecking)
{
_enableErrorChecking = value;
_context.enableErrorChecking = value;
}
}
public function Context3DResource(context : Context3D)
{
_context = context;
initialize();
}
private function initialize() : void
{
_vertexBuffers = new Vector.<VertexBuffer3D>(8, true);
_vertexBuffersOffsets = new Vector.<int>(8, true);
_vertexBuffersFormats = new Vector.<String>(8, true);
_textures = new Vector.<TextureBase>(8, true);
}
public function clear(red : Number = 0.0,
green : Number = 0.0,
blue : Number = 0.0,
alpha : Number = 1.0,
depth : Number = 1.0,
stencil : uint = 0,
mask : uint = 0xffffffff) : void
{
_context.clear(red, green, blue, alpha, depth, stencil, mask);
}
public function configureBackBuffer(width : int,
height : int,
antiAlias : int,
enabledDepthAndStencil : Boolean) : Context3DResource
{
_context.configureBackBuffer(width, height, antiAlias, enabledDepthAndStencil);
return this;
}
public function createCubeTexture(size : int,
format : String,
optimizeForRenderToTexture : Boolean) : CubeTexture
{
return _context.createCubeTexture(size, format, optimizeForRenderToTexture);
}
public function createIndexBuffer(numIndices : int) : IndexBuffer3D
{
return _context.createIndexBuffer(numIndices);
}
public function createProgram() : Program3D
{
return _context.createProgram();
}
public function createTexture(width : int,
height : int,
format : String,
optimizeForRenderToTexture : Boolean) : Texture
{
return _context.createTexture(width, height, format, optimizeForRenderToTexture);
}
public function createVertexBuffer(numVertices : int, data32PerVertex : int) : VertexBuffer3D
{
return _context.createVertexBuffer(numVertices, data32PerVertex);
}
public function dispose() : void
{
_context.dispose();
}
public function drawToBitmapData(destination : BitmapData) : Context3DResource
{
_context.drawToBitmapData(destination);
return this;
}
public function drawTriangles(indexBuffer : IndexBuffer3D,
firstIndex : int = 0,
numTriangles : int = -1) : Context3DResource
{
_context.drawTriangles(indexBuffer, firstIndex, numTriangles);
return this;
}
public function present() : Context3DResource
{
_context.present();
return this;
}
public function setBlendFactors(source : String, destination : String) : Context3DResource
{
if (source != _blendingSource || destination != _blendingDestination)
{
_blendingSource = source;
_blendingDestination = destination;
_context.setBlendFactors(_blendingSource, _blendingDestination);
}
return this;
}
public function setColorMask(red : Boolean,
green : Boolean,
blue : Boolean,
alpha : Boolean) : Context3DResource
{
if (red != _colorMaskRed || green != _colorMaskGreen
|| blue != _colorMaskBlue || alpha != _colorMaskAlpha)
{
_colorMaskRed = red;
_colorMaskGreen = green;
_colorMaskBlue = blue;
_colorMaskAlpha = alpha;
_context.setColorMask(
_colorMaskRed,
_colorMaskGreen,
_colorMaskBlue,
_colorMaskAlpha
);
}
return this;
}
public function setCulling(triangleCulling : String) : Context3DResource
{
if (triangleCulling != _triangleCulling)
{
_triangleCulling = triangleCulling;
_context.setCulling(triangleCulling);
}
return this;
}
public function setDepthTest(depthMask : Boolean, passCompareMode : String) : Context3DResource
{
if (depthMask != _depthMask || passCompareMode != _passCompareMode)
{
_depthMask = depthMask;
_passCompareMode = passCompareMode;
_context.setDepthTest(_depthMask, _passCompareMode);
}
return this;
}
public function setProgram(program : Program3D) : Context3DResource
{
if (_program != program)
{
_program = program;
_context.setProgram(program);
}
return this;
}
public function setProgramConstantsFromVector(programeType : String,
offset : uint,
values : Vector.<Number>,
numRegisters : int = -1) : Context3DResource
{
_context.setProgramConstantsFromVector(programeType, offset, values, numRegisters);
return this;
}
public function setRenderToBackBuffer() : Context3DResource
{
if (_rttTarget != null)
{
_rttTarget = null;
_context.setRenderToBackBuffer();
}
return this;
}
public function setRenderToTexture(texture : TextureBase,
enableDepthAndStencil : Boolean = false,
antiAlias : int = 0,
surfaceSelector : int = 0) : Context3DResource
{
if (texture != _rttTarget || enableDepthAndStencil != _rttDepthAndStencil
|| antiAlias != _rttAntiAliasing || surfaceSelector != _rttSurfaceSelector)
{
_rttTarget = texture;
_rttDepthAndStencil = enableDepthAndStencil;
_rttAntiAliasing = antiAlias;
_rttSurfaceSelector = surfaceSelector;
_context.setRenderToTexture(
texture,
enableDepthAndStencil,
antiAlias,
surfaceSelector
);
}
return this;
}
public function setScissorRectangle(rectangle : Rectangle) : Context3DResource
{
if (_rectangle != rectangle)
{
_rectangle = rectangle;
_context.setScissorRectangle(_rectangle);
}
return this;
}
public function setTextureAt(sampler : uint,
texture : TextureBase) : Context3DResource
{
if (_textures[sampler] != texture)
{
_textures[sampler] = texture;
_context.setTextureAt(sampler, texture);
}
return this;
}
public function setVertexBufferAt(index : int,
vertexBuffer : VertexBuffer3D,
bufferOffset : int = 0,
format : String = 'float4') : Context3DResource
{
if (_vertexBuffers[index] != vertexBuffer
|| _vertexBuffersOffsets[index] != bufferOffset
|| _vertexBuffersFormats[index] != format)
{
_vertexBuffers[index] = vertexBuffer;
_vertexBuffersOffsets[index] = bufferOffset;
_vertexBuffersFormats[index] = format;
_context.setVertexBufferAt(
index,
vertexBuffer,
bufferOffset,
format
);
}
return this;
}
public function setStencilReferenceValue(refNum : uint = 0,
readMask : uint = 255,
writeMask : uint = 255) : Context3DResource
{
if (refNum != _stencilRefNum
|| readMask != _stencilReadMask
|| writeMask != _stencilWriteMask
)
{
_context.setStencilReferenceValue(refNum, readMask, writeMask);
_stencilRefNum = refNum;
_stencilReadMask = readMask;
_stencilWriteMask = writeMask;
}
return this;
}
public function setStencilActions(triangleFace : String = 'frontAndBack',
compareMode : String = 'always',
actionOnBothPass : String = 'keep',
actionOnDepthFail : String = 'keep',
actionOnDepthPassStencilFail : String = 'keep') : Context3DResource
{
if (triangleFace != _stencilTriangleFace
|| compareMode != _stencilCompareMode
|| actionOnBothPass != _stencilActionOnBothPass
|| actionOnDepthFail != _stencilActionOnDepthFail
|| actionOnDepthPassStencilFail != _stencilActionOnDepthPassStencilFail
)
{
_context.setStencilActions(
triangleFace,
compareMode,
actionOnBothPass,
actionOnDepthFail,
actionOnDepthPassStencilFail
);
_stencilTriangleFace = triangleFace;
_stencilCompareMode = compareMode;
_stencilActionOnBothPass = actionOnBothPass;
_stencilActionOnDepthFail = actionOnDepthFail;
_stencilActionOnDepthPassStencilFail = actionOnDepthPassStencilFail;
}
return this;
}
}
}
|
package aerys.minko.render.resource
{
import flash.display.BitmapData;
import flash.display3D.Context3D;
import flash.display3D.IndexBuffer3D;
import flash.display3D.Program3D;
import flash.display3D.VertexBuffer3D;
import flash.display3D.textures.CubeTexture;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Rectangle;
import aerys.minko.ns.minko_render;
public final class Context3DResource
{
private var _context : Context3D;
private var _enableErrorChecking : Boolean;
private var _rttTarget : TextureBase;
private var _rttDepthAndStencil : Boolean;
private var _rttAntiAliasing : int;
private var _rttSurfaceSelector : int;
private var _rectangle : Rectangle;
private var _depthMask : Boolean;
private var _passCompareMode : String;
private var _program : Program3D;
private var _blendingSource : String;
private var _blendingDestination : String;
private var _triangleCulling : String;
private var _vertexBuffers : Vector.<VertexBuffer3D>;
private var _vertexBuffersOffsets : Vector.<int>;
private var _vertexBuffersFormats : Vector.<String>;
private var _textures : Vector.<TextureBase>;
private var _colorMaskRed : Boolean;
private var _colorMaskGreen : Boolean;
private var _colorMaskBlue : Boolean;
private var _colorMaskAlpha : Boolean;
private var _stencilRefNum : uint;
private var _stencilReadMask : uint;
private var _stencilWriteMask : uint;
private var _stencilTriangleFace : String;
private var _stencilCompareMode : String;
private var _stencilActionOnBothPass : String;
private var _stencilActionOnDepthFail : String;
private var _stencilActionOnDepthPassStencilFail : String;
public function get context() : Context3D
{
return _context;
}
public function get enabledErrorChecking() : Boolean
{
return _enableErrorChecking;
}
public function set enableErrorChecking(value : Boolean) : void
{
if (value != _enableErrorChecking)
{
_enableErrorChecking = value;
_context.enableErrorChecking = value;
}
}
public function Context3DResource(context : Context3D)
{
_context = context;
initialize();
}
private function initialize() : void
{
_vertexBuffers = new Vector.<VertexBuffer3D>(8, true);
_vertexBuffersOffsets = new Vector.<int>(8, true);
_vertexBuffersFormats = new Vector.<String>(8, true);
_textures = new Vector.<TextureBase>(8, true);
}
public function clear(red : Number = 0.0,
green : Number = 0.0,
blue : Number = 0.0,
alpha : Number = 1.0,
depth : Number = 1.0,
stencil : uint = 0,
mask : uint = 0xffffffff) : void
{
_context.clear(red, green, blue, alpha, depth, stencil, mask);
}
public function configureBackBuffer(width : int,
height : int,
antiAlias : int,
enabledDepthAndStencil : Boolean) : Context3DResource
{
_context.configureBackBuffer(width, height, antiAlias, enabledDepthAndStencil);
return this;
}
public function createCubeTexture(size : int,
format : String,
optimizeForRenderToTexture : Boolean) : CubeTexture
{
return _context.createCubeTexture(size, format, optimizeForRenderToTexture);
}
public function createIndexBuffer(numIndices : int) : IndexBuffer3D
{
return _context.createIndexBuffer(numIndices);
}
public function createProgram() : Program3D
{
return _context.createProgram();
}
public function createTexture(width : int,
height : int,
format : String,
optimizeForRenderToTexture : Boolean) : Texture
{
return _context.createTexture(width, height, format, optimizeForRenderToTexture);
}
public function createVertexBuffer(numVertices : int, data32PerVertex : int) : VertexBuffer3D
{
return _context.createVertexBuffer(numVertices, data32PerVertex);
}
public function dispose() : void
{
_context.dispose();
}
public function drawToBitmapData(destination : BitmapData) : Context3DResource
{
_context.drawToBitmapData(destination);
return this;
}
public function drawTriangles(indexBuffer : IndexBuffer3D,
firstIndex : int = 0,
numTriangles : int = -1) : Context3DResource
{
_context.drawTriangles(indexBuffer, firstIndex, numTriangles);
return this;
}
public function present() : Context3DResource
{
_context.present();
return this;
}
public function setBlendFactors(source : String, destination : String) : Context3DResource
{
if (source != _blendingSource || destination != _blendingDestination)
{
_blendingSource = source;
_blendingDestination = destination;
_context.setBlendFactors(_blendingSource, _blendingDestination);
}
return this;
}
public function setColorMask(red : Boolean,
green : Boolean,
blue : Boolean,
alpha : Boolean) : Context3DResource
{
if (red != _colorMaskRed || green != _colorMaskGreen
|| blue != _colorMaskBlue || alpha != _colorMaskAlpha)
{
_colorMaskRed = red;
_colorMaskGreen = green;
_colorMaskBlue = blue;
_colorMaskAlpha = alpha;
_context.setColorMask(
_colorMaskRed,
_colorMaskGreen,
_colorMaskBlue,
_colorMaskAlpha
);
}
return this;
}
public function setCulling(triangleCulling : String) : Context3DResource
{
if (triangleCulling != _triangleCulling)
{
_triangleCulling = triangleCulling;
_context.setCulling(triangleCulling);
}
return this;
}
public function setDepthTest(depthMask : Boolean, passCompareMode : String) : Context3DResource
{
if (depthMask != _depthMask || passCompareMode != _passCompareMode)
{
_depthMask = depthMask;
_passCompareMode = passCompareMode;
_context.setDepthTest(_depthMask, _passCompareMode);
}
return this;
}
public function setProgram(program : Program3D) : Context3DResource
{
if (_program != program)
{
_program = program;
_context.setProgram(program);
}
return this;
}
public function setProgramConstantsFromVector(programeType : String,
offset : uint,
values : Vector.<Number>,
numRegisters : int = -1) : Context3DResource
{
_context.setProgramConstantsFromVector(programeType, offset, values, numRegisters);
return this;
}
public function setRenderToBackBuffer() : Context3DResource
{
if (_rttTarget != null)
{
_rttTarget = null;
_context.setRenderToBackBuffer();
}
return this;
}
public function setRenderToTexture(texture : TextureBase,
enableDepthAndStencil : Boolean = false,
antiAlias : int = 0,
surfaceSelector : int = 0) : Context3DResource
{
if (texture != _rttTarget || enableDepthAndStencil != _rttDepthAndStencil
|| antiAlias != _rttAntiAliasing || surfaceSelector != _rttSurfaceSelector)
{
_rttTarget = texture;
_rttDepthAndStencil = enableDepthAndStencil;
_rttAntiAliasing = antiAlias;
_rttSurfaceSelector = surfaceSelector;
_context.setRenderToTexture(
texture,
enableDepthAndStencil,
antiAlias,
surfaceSelector
);
}
return this;
}
public function setScissorRectangle(rectangle : Rectangle) : Context3DResource
{
if (_rectangle != rectangle)
{
_rectangle = rectangle;
_context.setScissorRectangle(_rectangle);
}
return this;
}
public function setTextureAt(sampler : uint,
texture : TextureBase) : Context3DResource
{
if (_textures[sampler] != texture)
{
_textures[sampler] = texture;
_context.setTextureAt(sampler, texture);
}
return this;
}
public function setVertexBufferAt(index : int,
vertexBuffer : VertexBuffer3D,
bufferOffset : int = 0,
format : String = 'float4') : Context3DResource
{
if (_vertexBuffers[index] != vertexBuffer
|| _vertexBuffersOffsets[index] != bufferOffset
|| _vertexBuffersFormats[index] != format)
{
_vertexBuffers[index] = vertexBuffer;
_vertexBuffersOffsets[index] = bufferOffset;
_vertexBuffersFormats[index] = format;
_context.setVertexBufferAt(
index,
vertexBuffer,
bufferOffset,
format
);
}
return this;
}
public function setStencilReferenceValue(refNum : uint = 0,
readMask : uint = 255,
writeMask : uint = 255) : Context3DResource
{
if (refNum != _stencilRefNum
|| readMask != _stencilReadMask
|| writeMask != _stencilWriteMask
)
{
_context.setStencilReferenceValue(refNum, readMask, writeMask);
_stencilRefNum = refNum;
_stencilReadMask = readMask;
_stencilWriteMask = writeMask;
}
return this;
}
public function setStencilActions(triangleFace : String = 'frontAndBack',
compareMode : String = 'always',
actionOnBothPass : String = 'keep',
actionOnDepthFail : String = 'keep',
actionOnDepthPassStencilFail : String = 'keep') : Context3DResource
{
if (triangleFace != _stencilTriangleFace
|| compareMode != _stencilCompareMode
|| actionOnBothPass != _stencilActionOnBothPass
|| actionOnDepthFail != _stencilActionOnDepthFail
|| actionOnDepthPassStencilFail != _stencilActionOnDepthPassStencilFail
)
{
_context.setStencilActions(
triangleFace,
compareMode,
actionOnBothPass,
actionOnDepthFail,
actionOnDepthPassStencilFail
);
_stencilTriangleFace = triangleFace;
_stencilCompareMode = compareMode;
_stencilActionOnBothPass = actionOnBothPass;
_stencilActionOnDepthFail = actionOnDepthFail;
_stencilActionOnDepthPassStencilFail = actionOnDepthPassStencilFail;
}
return this;
}
}
}
|
Fix context3D getter
|
Fix context3D getter
|
ActionScript
|
mit
|
aerys/minko-as3
|
cf1f3366aa9ff246cfe8bc6639e9aa5d7678c04f
|
driver/src/main/flex/org/postgresql/util/format.as
|
driver/src/main/flex/org/postgresql/util/format.as
|
package org.postgresql.util {
/**
* Format the template by substituting any parameter marker with its
* corresponding argument. Parameter markers are defined by a number
* (indicating the argument index to replace) enclosed by curly braces.
* E.g., an invocation such as <code>format("{1} {0}!", 'world', 'hello')</code>
* would return the string <code>hello world!</code>.
* @param template String in which to perform parameter substitution
* @param args arguments to substitute
*/
public function format(template:String, ...args):String {
return template.replace(/{(\d+)}/g, function():String {
var replacementIndex:int = int(arguments[1]);
return replacementIndex < args.length ?
args[replacementIndex] :
arguments[0];
});
}
}
|
package org.postgresql.util {
/**
* Format the template by substituting any parameter marker with its
* corresponding argument. Parameter markers are defined by a number
* (indicating the argument index to replace) enclosed by curly braces.
* <p/>
* E.g., an invocation such as <code>format("{1} {0}!", 'world', 'hello')</code>
* would return the string <code>hello world!</code>.
* <p/>
* If the replacement values are not Strings, they are coerced to
* Strings before substitution, as per the <code>String</code> function.
*
* @param template String in which to perform parameter substitution
* @param args arguments to substitute
* @return a String with all token references subtituted with their corresponding values
* @throws ArgumentException if more values are referenced than provided
* @see String
*/
public function format(template:String, ...args):String {
return template.replace(/{(\d+)}/g, function():String {
var replacementIndex:int = int(arguments[1]);
if (replacementIndex > args.length) {
throw new ArgumentError("Invalid log argument index: " + replacementIndex);
} else {
return String(args[replacementIndex]);
}
});
}
}
|
Format method cleanup.
|
Format method cleanup.
|
ActionScript
|
bsd-3-clause
|
uhoh-itsmaciek/pegasus
|
2a97729d6f76d8f761ba8a18c40f5ec7d42eaa14
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/Tracker.as
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/Tracker.as
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker
{
import com.snowplowanalytics.snowplow.tracker.emitter.Emitter;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import com.snowplowanalytics.snowplow.tracker.payload.TrackerPayload;
import com.snowplowanalytics.snowplow.tracker.util.Preconditions;
import flash.display.Stage;
import flash.external.ExternalInterface;
import flash.net.LocalConnection;
import flash.net.SharedObject;
import flash.system.Capabilities;
public class Tracker
{
private var base64Encoded:Boolean = true;
private var emitter:Emitter;
private var platform:String;
private var appId:String;
private var namespace:String;
private var trackerVersion:String;
private var subject:Subject;
private var stage:Stage;
private var playerType:String;
private var playerVersion:String;
private var isDebugger:Boolean;
private var hasLocalStorage:Boolean;
private var hasScriptAccess:Boolean;
/**
* @param emitter Emitter to which events will be sent
* @param subject Subject to be tracked
* @param namespace Identifier for the Tracker instance
* @param appId Application ID
* @param stage The flash stage object. used for adding stage info to payload.
* @param base64Encoded Whether JSONs in the payload should be base-64 encoded
*/
function Tracker(emitter:Emitter, subject:Subject, namespace:String, appId:String, stage:Stage = null, base64Encoded:Boolean = true) {
this.emitter = emitter;
this.appId = appId;
this.base64Encoded = base64Encoded;
this.namespace = namespace;
this.subject = subject;
this.trackerVersion = Version.TRACKER;
this.platform = DevicePlatform.DESKTOP;
this.stage = stage;
this.playerType = Capabilities.playerType;
this.playerVersion = Capabilities.version;
this.isDebugger = Capabilities.isDebugger;
try
{
SharedObject.getLocal("test");
this.hasLocalStorage = true;
}
catch (e:Error)
{
this.hasLocalStorage = false;
}
this.hasScriptAccess = ExternalInterface.available;
}
/**
* @param payload Payload builder
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
* @return A completed Payload
*/
protected function completePayload(payload:IPayload,
context:Array,
timestamp:Number):IPayload {
payload.add(Parameter.PLATFORM, this.platform);
payload.add(Parameter.APPID, this.appId);
payload.add(Parameter.NAMESPACE, this.namespace);
payload.add(Parameter.TRACKER_VERSION, this.trackerVersion);
payload.add(Parameter.EID, Util.getEventId());
// If timestamp is set to 0, generate one
payload.add(Parameter.TIMESTAMP,
(timestamp == 0 ? Util.getTimestamp() : String(timestamp)));
// Add flash information
if (context == null) {
context = [];
}
var flashData:TrackerPayload = new TrackerPayload();
flashData.add(Parameter.FLASH_PLAYER_TYPE, playerType);
flashData.add(Parameter.FLASH_VERSION, playerVersion);
flashData.add(Parameter.FLASH_IS_DEBUGGER, isDebugger);
flashData.add(Parameter.FLASH_HAS_LOCAL_STORAGE, hasLocalStorage);
flashData.add(Parameter.FLASH_HAS_SCRIPT_ACCESS, hasScriptAccess);
if (stage != null) {
flashData.add(Parameter.FLASH_STAGE_SIZE, { "width": stage.stageWidth, "height": stage.stageHeight});
}
var flashPayload:SchemaPayload = new SchemaPayload();
flashPayload.setSchema(Constants.SCHEMA_FLASH);
flashPayload.setData(flashData.getMap());
context.push(flashPayload);
// Encodes context data
if (context != null && context.length > 0) {
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_CONTEXTS);
// We can do better here, rather than re-iterate through the list
var contextDataList:Array = [];
for each(var schemaPayload:SchemaPayload in context) {
contextDataList.push(schemaPayload.getMap());
}
envelope.setData(contextDataList);
payload.addMap(envelope.getMap(), this.base64Encoded, Parameter.CONTEXT_ENCODED, Parameter.CONTEXT);
}
if (this.subject != null) {
payload.addMap(Util.copyObject(subject.getSubject(), true));
}
return payload;
}
public function setPlatform(platform:String):void {
this.platform = platform;
}
public function getPlatform():String {
return this.platform;
}
protected function setTrackerVersion(version:String):void {
this.trackerVersion = version;
}
private function addTrackerPayload(payload:IPayload):void {
this.emitter.addToBuffer(payload);
}
public function setSubject(subject:Subject):void {
this.subject = subject;
}
public function getSubject():Subject {
return this.subject;
}
/**
* @param pageUrl URL of the viewed page
* @param pageTitle Title of the viewed page
* @param referrer Referrer of the page
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackPageView(pageUrl:String, pageTitle:String, referrer:String, context:Array = null, timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(pageUrl);
Preconditions.checkArgument(!Util.isNullOrEmpty(pageUrl), "pageUrl cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(pageTitle), "pageTitle cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(referrer), "referrer cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_PAGE_VIEW);
payload.add(Parameter.PAGE_URL, pageUrl);
payload.add(Parameter.PAGE_TITLE, pageTitle);
payload.add(Parameter.PAGE_REFR, referrer);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* @param category Category of the event
* @param action The event itself
* @param label Refer to the object the action is performed on
* @param property Property associated with either the action or the object
* @param value A value associated with the user action
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackStructuredEvent(category:String,
action:String,
label:String,
property:String,
value:int,
context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(label);
Preconditions.checkNotNull(property);
Preconditions.checkArgument(!Util.isNullOrEmpty(label), "label cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(property), "property cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(action), "action cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_STRUCTURED);
payload.add(Parameter.SE_CATEGORY, category);
payload.add(Parameter.SE_ACTION, action);
payload.add(Parameter.SE_LABEL, label);
payload.add(Parameter.SE_PROPERTY, property);
payload.add(Parameter.SE_VALUE, String(value));
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
*
* @param eventData The properties of the event. Has two field:
* A "data" field containing the event properties and
* A "schema" field identifying the schema against which the data is validated
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackUnstructuredEvent(eventData:SchemaPayload, context:Array = null,
timestamp:Number = 0):void
{
var payload:IPayload = new TrackerPayload();
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_UNSTRUCT_EVENT);
envelope.setData(eventData.getMap());
payload.add(Parameter.EVENT, Constants.EVENT_UNSTRUCTURED);
payload.addMap(envelope.getMap());
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* This is an internal method called by track_ecommerce_transaction. It is not for public use.
* @param order_id Order ID
* @param sku Item SKU
* @param price Item price
* @param quantity Item quantity
* @param name Item name
* @param category Item category
* @param currency The currency the price is expressed in
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
protected function trackEcommerceTransactionItem(order_id:String, sku:String, price:Number,
quantity:int, name:String, category:String,
currency:String, context:Array,
timestamp:Number):void
{
// Precondition checks
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(category);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(sku), "sku cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(name), "name cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM_ITEM);
payload.add(Parameter.TI_ITEM_ID, order_id);
payload.add(Parameter.TI_ITEM_SKU, sku);
payload.add(Parameter.TI_ITEM_NAME, name);
payload.add(Parameter.TI_ITEM_CATEGORY, category);
payload.add(Parameter.TI_ITEM_PRICE, String(price));
payload.add(Parameter.TI_ITEM_QUANTITY, String(quantity));
payload.add(Parameter.TI_ITEM_CURRENCY, currency);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* @param order_id ID of the eCommerce transaction
* @param total_value Total transaction value
* @param affiliation Transaction affiliation
* @param tax_value Transaction tax value
* @param shipping Delivery cost charged
* @param city Delivery address city
* @param state Delivery address state
* @param country Delivery address country
* @param currency The currency the price is expressed in
* @param items The items in the transaction
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackEcommerceTransaction(order_id:String, total_value:Number, affiliation:String,
tax_value:Number, shipping:Number, city:String,
state:String, country:String, currency:String,
items:Array, context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(affiliation);
Preconditions.checkNotNull(city);
Preconditions.checkNotNull(state);
Preconditions.checkNotNull(country);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(affiliation), "affiliation cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(city), "city cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(state), "state cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(country), "country cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM);
payload.add(Parameter.TR_ID, order_id);
payload.add(Parameter.TR_TOTAL, String(total_value));
payload.add(Parameter.TR_AFFILIATION, affiliation);
payload.add(Parameter.TR_TAX, String(tax_value));
payload.add(Parameter.TR_SHIPPING, String(shipping));
payload.add(Parameter.TR_CITY, city);
payload.add(Parameter.TR_STATE, state);
payload.add(Parameter.TR_COUNTRY, country);
payload.add(Parameter.TR_CURRENCY, currency);
completePayload(payload, context, timestamp);
for each(var item:TransactionItem in items) {
trackEcommerceTransactionItem(
String(item.get(Parameter.TI_ITEM_ID)),
String(item.get(Parameter.TI_ITEM_SKU)),
Number(item.get(Parameter.TI_ITEM_PRICE)),
parseInt(item.get(Parameter.TI_ITEM_QUANTITY)),
String(item.get(Parameter.TI_ITEM_NAME)),
String(item.get(Parameter.TI_ITEM_CATEGORY)),
String(item.get(Parameter.TI_ITEM_CURRENCY)),
item.get(Parameter.CONTEXT),
timestamp);
}
addTrackerPayload(payload);
}
/**
* @param name The name of the screen view event
* @param id Screen view ID
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackScreenView(name:String, id:String, context:Array,
timestamp:Number):void {
Preconditions.checkArgument(name != null || id != null);
var trackerPayload:TrackerPayload = new TrackerPayload();
trackerPayload.add(Parameter.SV_NAME, name);
trackerPayload.add(Parameter.SV_ID, id);
var payload:SchemaPayload = new SchemaPayload();
payload.setSchema(Constants.SCHEMA_SCREEN_VIEW);
payload.setData(trackerPayload);
trackUnstructuredEvent(payload, context, timestamp);
}
}
}
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker
{
import com.snowplowanalytics.snowplow.tracker.emitter.Emitter;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import com.snowplowanalytics.snowplow.tracker.payload.TrackerPayload;
import com.snowplowanalytics.snowplow.tracker.util.Preconditions;
import flash.display.Stage;
import flash.external.ExternalInterface;
import flash.net.LocalConnection;
import flash.net.SharedObject;
import flash.system.Capabilities;
public class Tracker
{
private var base64Encoded:Boolean = true;
private var emitter:Emitter;
private var platform:String;
private var appId:String;
private var namespace:String;
private var trackerVersion:String;
private var subject:Subject;
private var stage:Stage;
private var playerType:String;
private var playerVersion:String;
private var isDebugger:Boolean;
private var hasLocalStorage:Boolean;
private var hasScriptAccess:Boolean;
/**
* @param emitter Emitter to which events will be sent
* @param subject Subject to be tracked
* @param namespace Identifier for the Tracker instance
* @param appId Application ID
* @param stage The flash stage object. used for adding stage info to payload.
* @param base64Encoded Whether JSONs in the payload should be base-64 encoded
*/
function Tracker(emitter:Emitter, subject:Subject, namespace:String, appId:String, stage:Stage = null, base64Encoded:Boolean = true) {
this.emitter = emitter;
this.appId = appId;
this.base64Encoded = base64Encoded;
this.namespace = namespace;
this.subject = subject;
this.trackerVersion = Version.TRACKER;
this.platform = DevicePlatform.DESKTOP;
this.stage = stage;
this.playerType = Capabilities.playerType;
this.playerVersion = Capabilities.version;
this.isDebugger = Capabilities.isDebugger;
try
{
SharedObject.getLocal("test");
this.hasLocalStorage = true;
}
catch (e:Error)
{
this.hasLocalStorage = false;
}
this.hasScriptAccess = ExternalInterface.available;
}
/**
* @param payload Payload builder
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
* @return A completed Payload
*/
protected function completePayload(payload:IPayload,
context:Array,
timestamp:Number):IPayload {
payload.add(Parameter.PLATFORM, this.platform);
payload.add(Parameter.APPID, this.appId);
payload.add(Parameter.NAMESPACE, this.namespace);
payload.add(Parameter.TRACKER_VERSION, this.trackerVersion);
payload.add(Parameter.EID, Util.getEventId());
// If timestamp is set to 0, generate one
payload.add(Parameter.TIMESTAMP,
(timestamp == 0 ? Util.getTimestamp() : String(timestamp)));
// Add flash information
if (context == null) {
context = [];
}
var flashData:TrackerPayload = new TrackerPayload();
flashData.add(Parameter.FLASH_PLAYER_TYPE, playerType);
flashData.add(Parameter.FLASH_VERSION, playerVersion);
flashData.add(Parameter.FLASH_IS_DEBUGGER, isDebugger);
flashData.add(Parameter.FLASH_HAS_LOCAL_STORAGE, hasLocalStorage);
flashData.add(Parameter.FLASH_HAS_SCRIPT_ACCESS, hasScriptAccess);
if (stage != null) {
flashData.add(Parameter.FLASH_STAGE_SIZE, { "width": stage.stageWidth, "height": stage.stageHeight});
}
var flashPayload:SchemaPayload = new SchemaPayload();
flashPayload.setSchema(Constants.SCHEMA_FLASH);
flashPayload.setData(flashData.getMap());
context.push(flashPayload);
// Encodes context data
if (context != null && context.length > 0) {
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_CONTEXTS);
// We can do better here, rather than re-iterate through the list
var contextDataList:Array = [];
for each(var schemaPayload:SchemaPayload in context) {
contextDataList.push(schemaPayload.getMap());
}
envelope.setData(contextDataList);
payload.addMap(envelope.getMap(), this.base64Encoded, Parameter.CONTEXT_ENCODED, Parameter.CONTEXT);
}
if (this.subject != null) {
payload.addMap(Util.copyObject(subject.getSubject(), true));
}
return payload;
}
public function setPlatform(platform:String):void {
this.platform = platform;
}
public function getPlatform():String {
return this.platform;
}
protected function setTrackerVersion(version:String):void {
this.trackerVersion = version;
}
private function addTrackerPayload(payload:IPayload):void {
this.emitter.addToBuffer(payload);
}
public function setSubject(subject:Subject):void {
this.subject = subject;
}
public function getSubject():Subject {
return this.subject;
}
/**
* @param pageUrl URL of the viewed page
* @param pageTitle Title of the viewed page
* @param referrer Referrer of the page
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackPageView(pageUrl:String, pageTitle:String, referrer:String, context:Array = null, timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(pageUrl);
Preconditions.checkArgument(!Util.isNullOrEmpty(pageUrl), "pageUrl cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(pageTitle), "pageTitle cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(referrer), "referrer cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_PAGE_VIEW);
payload.add(Parameter.PAGE_URL, pageUrl);
payload.add(Parameter.PAGE_TITLE, pageTitle);
payload.add(Parameter.PAGE_REFR, referrer);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* @param category Category of the event
* @param action The event itself
* @param label Refer to the object the action is performed on
* @param property Property associated with either the action or the object
* @param value A value associated with the user action
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackStructuredEvent(category:String,
action:String,
label:String,
property:String,
value:int,
context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(label);
Preconditions.checkNotNull(property);
Preconditions.checkArgument(!Util.isNullOrEmpty(label), "label cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(property), "property cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(action), "action cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_STRUCTURED);
payload.add(Parameter.SE_CATEGORY, category);
payload.add(Parameter.SE_ACTION, action);
payload.add(Parameter.SE_LABEL, label);
payload.add(Parameter.SE_PROPERTY, property);
payload.add(Parameter.SE_VALUE, String(value));
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
*
* @param eventData The properties of the event. Has two field:
* A "data" field containing the event properties and
* A "schema" field identifying the schema against which the data is validated
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackUnstructuredEvent(eventData:SchemaPayload, context:Array = null,
timestamp:Number = 0):void
{
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_UNSTRUCT_EVENT);
envelope.setData(eventData.getMap());
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_UNSTRUCTURED);
payload.addMap(envelope.getMap(), base64Encoded,
Parameter.UNSTRUCTURED_ENCODED, Parameter.UNSTRUCTURED);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* This is an internal method called by track_ecommerce_transaction. It is not for public use.
* @param order_id Order ID
* @param sku Item SKU
* @param price Item price
* @param quantity Item quantity
* @param name Item name
* @param category Item category
* @param currency The currency the price is expressed in
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
protected function trackEcommerceTransactionItem(order_id:String, sku:String, price:Number,
quantity:int, name:String, category:String,
currency:String, context:Array,
timestamp:Number):void
{
// Precondition checks
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(category);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(sku), "sku cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(name), "name cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM_ITEM);
payload.add(Parameter.TI_ITEM_ID, order_id);
payload.add(Parameter.TI_ITEM_SKU, sku);
payload.add(Parameter.TI_ITEM_NAME, name);
payload.add(Parameter.TI_ITEM_CATEGORY, category);
payload.add(Parameter.TI_ITEM_PRICE, String(price));
payload.add(Parameter.TI_ITEM_QUANTITY, String(quantity));
payload.add(Parameter.TI_ITEM_CURRENCY, currency);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* @param order_id ID of the eCommerce transaction
* @param total_value Total transaction value
* @param affiliation Transaction affiliation
* @param tax_value Transaction tax value
* @param shipping Delivery cost charged
* @param city Delivery address city
* @param state Delivery address state
* @param country Delivery address country
* @param currency The currency the price is expressed in
* @param items The items in the transaction
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackEcommerceTransaction(order_id:String, total_value:Number, affiliation:String,
tax_value:Number, shipping:Number, city:String,
state:String, country:String, currency:String,
items:Array, context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(affiliation);
Preconditions.checkNotNull(city);
Preconditions.checkNotNull(state);
Preconditions.checkNotNull(country);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(affiliation), "affiliation cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(city), "city cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(state), "state cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(country), "country cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM);
payload.add(Parameter.TR_ID, order_id);
payload.add(Parameter.TR_TOTAL, String(total_value));
payload.add(Parameter.TR_AFFILIATION, affiliation);
payload.add(Parameter.TR_TAX, String(tax_value));
payload.add(Parameter.TR_SHIPPING, String(shipping));
payload.add(Parameter.TR_CITY, city);
payload.add(Parameter.TR_STATE, state);
payload.add(Parameter.TR_COUNTRY, country);
payload.add(Parameter.TR_CURRENCY, currency);
completePayload(payload, context, timestamp);
for each(var item:TransactionItem in items) {
trackEcommerceTransactionItem(
String(item.get(Parameter.TI_ITEM_ID)),
String(item.get(Parameter.TI_ITEM_SKU)),
Number(item.get(Parameter.TI_ITEM_PRICE)),
parseInt(item.get(Parameter.TI_ITEM_QUANTITY)),
String(item.get(Parameter.TI_ITEM_NAME)),
String(item.get(Parameter.TI_ITEM_CATEGORY)),
String(item.get(Parameter.TI_ITEM_CURRENCY)),
item.get(Parameter.CONTEXT),
timestamp);
}
addTrackerPayload(payload);
}
/**
* @param name The name of the screen view event
* @param id Screen view ID
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackScreenView(name:String, id:String, context:Array,
timestamp:Number):void {
Preconditions.checkArgument(name != null || id != null);
var trackerPayload:TrackerPayload = new TrackerPayload();
trackerPayload.add(Parameter.SV_NAME, name);
trackerPayload.add(Parameter.SV_ID, id);
var payload:SchemaPayload = new SchemaPayload();
payload.setSchema(Constants.SCHEMA_SCREEN_VIEW);
payload.setData(trackerPayload);
trackUnstructuredEvent(payload, context, timestamp);
}
}
}
|
fix trackUnstructuredEvent to place unstructured data into serialized json instead of on the payload itself.
|
fix trackUnstructuredEvent to place unstructured data into serialized json instead of on the payload itself.
|
ActionScript
|
apache-2.0
|
snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker
|
a82369ef86f3999820935c7ee57e0edc676ad173
|
src/aerys/minko/scene/node/light/DirectionalLight.as
|
src/aerys/minko/scene/node/light/DirectionalLight.as
|
package aerys.minko.scene.node.light
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.scene.controller.light.DirectionalLightController;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.type.enum.ShadowMappingType;
import aerys.minko.type.math.Vector4;
use namespace minko_scene;
/**
*
* @author Romain Gilliotte
* @author Jean-Marc Le Roux
*
*/
public class DirectionalLight extends AbstractLight
{
public static const LIGHT_TYPE : uint = 1;
public function get diffuse() : Number
{
return lightData.getLightProperty('diffuse') as Number;
}
public function set diffuse(v : Number) : void
{
lightData.setLightProperty('diffuse', v);
if (lightData.getLightProperty('diffuseEnabled') != (v != 0))
lightData.setLightProperty('diffuseEnabled', v != 0);
}
public function get specular() : Number
{
return lightData.getLightProperty('specular') as Number;
}
public function set specular(v : Number) : void
{
lightData.setLightProperty('specular', v);
if (lightData.getLightProperty('specularEnabled') != (v != 0))
lightData.setLightProperty('specularEnabled', v != 0);
}
public function get shininess() : Number
{
return lightData.getLightProperty('shininess') as Number;
}
public function set shininess(value : Number) : void
{
lightData.setLightProperty('shininess', value);
}
public function get shadowWidth() : Number
{
return lightData.getLightProperty('shadowWidth');
}
public function set shadowWidth(v : Number) : void
{
lightData.setLightProperty('shadowWidth', v);
}
public function get shadowZNear() : Number
{
return lightData.getLightProperty('shadowZNear');
}
public function set shadowZNear(v : Number) : void
{
lightData.setLightProperty('shadowZNear', v);
}
public function get shadowZFar() : Number
{
return lightData.getLightProperty('shadowZFar');
}
public function set shadowZFar(v : Number) : void
{
lightData.setLightProperty('shadowZFar', v);
}
public function get shadowQuality() : uint
{
return lightData.getLightProperty('shadowQuality');
}
public function set shadowQuality(v : uint) : void
{
lightData.setLightProperty('shadowQuality', v);
}
public function get shadowSpread() : uint
{
return lightData.getLightProperty('shadowSpread');
}
public function set shadowSpread(v : uint) : void
{
lightData.setLightProperty('shadowSpread', v);
}
public function get shadowMapSize() : uint
{
return lightData.getLightProperty('shadowMapSize');
}
public function set shadowMapSize(v : uint) : void
{
lightData.setLightProperty('shadowMapSize', v);
}
public function get shadowMappingType() : uint
{
return lightData.getLightProperty('shadowMappingType');
}
public function set shadowMappingType(value : uint) : void
{
lightData.setLightProperty('shadowMappingType', value);
}
public function get shadowBias() : Number
{
return lightData.getLightProperty(PhongProperties.SHADOW_BIAS);
}
public function set shadowBias(value : Number) : void
{
lightData.setLightProperty(PhongProperties.SHADOW_BIAS, value);
}
public function DirectionalLight(color : uint = 0xFFFFFFFF,
diffuse : Number = .6,
specular : Number = .8,
shininess : Number = 64,
emissionMask : uint = 0x1,
shadowMappingType : uint = 0,
shadowMapSize : uint = 512,
shadowZFar : Number = 1000,
shadowWidth : Number = 20,
shadowQuality : uint = 0,
shadowSpread : uint = 1,
shadowBias : Number = .002,
shadowColor : uint = 0x0)
{
super(
new DirectionalLightController(),
LIGHT_TYPE,
color,
emissionMask
);
this.diffuse = diffuse;
this.specular = specular;
this.shininess = shininess;
this.shadowMappingType = shadowMappingType;
this.shadowZFar = shadowZFar;
this.shadowWidth = shadowWidth;
this.shadowMapSize = shadowMapSize;
this.shadowQuality = shadowQuality;
this.shadowSpread = shadowSpread;
this.shadowBias = shadowBias;
this.shadowColor = shadowColor;
transform.lookAt(Vector4.ZERO, new Vector4(1, 1, 1));
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var light : DirectionalLight = new DirectionalLight(
color,
diffuse,
specular,
shininess,
emissionMask,
ShadowMappingType.NONE, // @fixme clone light with shadow triggered errors
shadowMapSize,
shadowZFar,
shadowWidth,
shadowQuality,
shadowSpread,
shadowBias
);
light.name = this.name;
light.userData.setProperties(userData);
light.transform.copyFrom(this.transform);
return light;
}
}
}
|
package aerys.minko.scene.node.light
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.scene.controller.light.DirectionalLightController;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.type.enum.ShadowMappingType;
import aerys.minko.type.math.Vector4;
use namespace minko_scene;
/**
*
* @author Romain Gilliotte
* @author Jean-Marc Le Roux
*
*/
public class DirectionalLight extends AbstractLight
{
public static const LIGHT_TYPE : uint = 1;
public function get diffuse() : Number
{
return lightData.getLightProperty('diffuse') as Number;
}
public function set diffuse(v : Number) : void
{
lightData.setLightProperty('diffuse', v);
if (lightData.getLightProperty('diffuseEnabled') != (v != 0))
lightData.setLightProperty('diffuseEnabled', v != 0);
}
public function get specular() : Number
{
return lightData.getLightProperty('specular') as Number;
}
public function set specular(v : Number) : void
{
lightData.setLightProperty('specular', v);
if (lightData.getLightProperty('specularEnabled') != (v != 0))
lightData.setLightProperty('specularEnabled', v != 0);
}
public function get shininess() : Number
{
return lightData.getLightProperty('shininess') as Number;
}
public function set shininess(value : Number) : void
{
lightData.setLightProperty('shininess', value);
}
public function get shadowWidth() : Number
{
return lightData.getLightProperty('shadowWidth');
}
public function set shadowWidth(v : Number) : void
{
lightData.setLightProperty('shadowWidth', v);
}
public function get shadowZNear() : Number
{
return lightData.getLightProperty('shadowZNear');
}
public function set shadowZNear(v : Number) : void
{
lightData.setLightProperty('shadowZNear', v);
}
public function get shadowZFar() : Number
{
return lightData.getLightProperty('shadowZFar');
}
public function set shadowZFar(v : Number) : void
{
lightData.setLightProperty('shadowZFar', v);
}
public function get shadowQuality() : uint
{
return lightData.getLightProperty('shadowQuality');
}
public function set shadowQuality(v : uint) : void
{
lightData.setLightProperty('shadowQuality', v);
}
public function get shadowSpread() : uint
{
return lightData.getLightProperty('shadowSpread');
}
public function set shadowSpread(v : uint) : void
{
lightData.setLightProperty('shadowSpread', v);
}
public function get shadowMapSize() : uint
{
return lightData.getLightProperty('shadowMapSize');
}
public function set shadowMapSize(v : uint) : void
{
lightData.setLightProperty('shadowMapSize', v);
}
public function get shadowMappingType() : uint
{
return lightData.getLightProperty('shadowMappingType');
}
public function set shadowMappingType(value : uint) : void
{
lightData.setLightProperty('shadowMappingType', value);
}
public function get shadowBias() : Number
{
return lightData.getLightProperty(PhongProperties.SHADOW_BIAS);
}
public function set shadowBias(value : Number) : void
{
lightData.setLightProperty(PhongProperties.SHADOW_BIAS, value);
}
public function DirectionalLight(color : uint = 0xFFFFFFFF,
diffuse : Number = .6,
specular : Number = .8,
shininess : Number = 64,
emissionMask : uint = 0x1,
shadowMappingType : uint = 0,
shadowMapSize : uint = 512,
shadowZFar : Number = 1000,
shadowWidth : Number = 20,
shadowQuality : uint = 0,
shadowSpread : uint = 1,
shadowBias : Number = .002,
shadowColor : uint = 0x0)
{
super(
new DirectionalLightController(),
LIGHT_TYPE,
color,
emissionMask
);
this.diffuse = diffuse;
this.specular = specular;
this.shininess = shininess;
this.shadowMappingType = shadowMappingType;
this.shadowZFar = shadowZFar;
this.shadowWidth = shadowWidth;
this.shadowMapSize = shadowMapSize;
this.shadowQuality = shadowQuality;
this.shadowSpread = shadowSpread;
this.shadowBias = shadowBias;
this.shadowColor = shadowColor;
this.shadowZNear = 0;
transform.lookAt(Vector4.ZERO, new Vector4(1, 1, 1));
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var light : DirectionalLight = new DirectionalLight(
color,
diffuse,
specular,
shininess,
emissionMask,
ShadowMappingType.NONE, // @fixme clone light with shadow triggered errors
shadowMapSize,
shadowZFar,
shadowWidth,
shadowQuality,
shadowSpread,
shadowBias
);
light.name = this.name;
light.userData.setProperties(userData);
light.transform.copyFrom(this.transform);
return light;
}
}
}
|
Fix default znear value
|
Fix default znear value
|
ActionScript
|
mit
|
aerys/minko-as3
|
cb9c5304885b981b091e1225d1dd38d204895643
|
src/com/esri/builder/components/serviceBrowser/supportClasses/ServiceDirectoryBuilder.as
|
src/com/esri/builder/components/serviceBrowser/supportClasses/ServiceDirectoryBuilder.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed 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 com.esri.builder.components.serviceBrowser.supportClasses
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.components.supportClasses.Credential;
import com.esri.ags.tasks.JSONTask;
import com.esri.builder.components.serviceBrowser.filters.GPTaskFilter;
import com.esri.builder.components.serviceBrowser.filters.GeocoderFilter;
import com.esri.builder.components.serviceBrowser.filters.INodeFilter;
import com.esri.builder.components.serviceBrowser.filters.MapLayerFilter;
import com.esri.builder.components.serviceBrowser.filters.MapServerFilter;
import com.esri.builder.components.serviceBrowser.filters.QueryableLayerFilter;
import com.esri.builder.components.serviceBrowser.filters.RouteLayerFilter;
import com.esri.builder.components.serviceBrowser.nodes.ServiceDirectoryRootNode;
import com.esri.builder.model.Model;
import com.esri.builder.supportClasses.LogUtil;
import flash.events.EventDispatcher;
import flash.net.URLVariables;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
public final class ServiceDirectoryBuilder extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(ServiceDirectoryBuilder);
private static const DEFAULT_REQUEST_TIMEOUT_IN_SECONDS:Number = 10;
private var count:int;
private var searchType:String;
private var hasCrossDomain:Boolean;
private var crossDomainRequest:HTTPService;
private var credential:Credential;
private var rootNode:ServiceDirectoryRootNode;
private var currentNodeFilter:INodeFilter;
private var isServiceSecured:Boolean;
private var securityWarning:String;
private var owningSystemURL:String;
public function buildServiceDirectory(serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest):void
{
if (Log.isInfo())
{
LOG.info("Building service directory");
}
try
{
checkCrossDomainBeforeBuildingDirectory(serviceDirectoryBuildRequest);
}
catch (error:Error)
{
//TODO: handle error
}
}
private function checkCrossDomainBeforeBuildingDirectory(serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest):void
{
if (Log.isDebug())
{
LOG.debug("Checking service URL crossdomain.xml");
}
crossDomainRequest = new HTTPService();
crossDomainRequest.url = extractCrossDomainPolicyFileURL(serviceDirectoryBuildRequest.url);
crossDomainRequest.addEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.addEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest.requestTimeout = DEFAULT_REQUEST_TIMEOUT_IN_SECONDS;
crossDomainRequest.send();
function crossDomainRequest_resultHandler(event:ResultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Found service crossdomain.xml");
}
crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest = null;
hasCrossDomain = true;
checkIfServiceIsSecure(serviceDirectoryBuildRequest);
}
function crossDomainRequest_faultHandler(event:FaultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Could not find service crossdomain.xml");
}
crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest = null;
hasCrossDomain = false;
checkIfServiceIsSecure(serviceDirectoryBuildRequest);
}
}
private function extractCrossDomainPolicyFileURL(url:String):String
{
var baseURL:RegExp = /(https?:\/\/)([^\/]+\/)/
var baseURLMatch:Array = url.match(baseURL);
return baseURLMatch[0] + 'crossdomain.xml';
}
private function checkIfServiceIsSecure(serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest):void
{
if (Log.isInfo())
{
LOG.info("Checking if service is secure");
}
var serviceSecurityRequest:JSONTask = new JSONTask();
serviceSecurityRequest.url = extractServiceInfoURL(serviceDirectoryBuildRequest.url);
const param:URLVariables = new URLVariables();
param.f = 'json';
serviceSecurityRequest.execute(param, new AsyncResponder(serviceSecurityRequest_resultHandler, serviceSecurityRequest_faultHandler));
function serviceSecurityRequest_resultHandler(serverInfo:Object, token:Object = null):void
{
isServiceSecured = (serverInfo.currentVersion >= 10.01
&& serverInfo.authInfo
&& serverInfo.authInfo.isTokenBasedSecurity);
owningSystemURL = serverInfo.owningSystemUrl;
if (isServiceSecured)
{
if (Log.isDebug())
{
LOG.debug("Service is secure");
}
if (Log.isDebug())
{
LOG.debug("Checking token service crossdomain.xml");
}
const tokenServiceCrossDomainRequest:HTTPService = new HTTPService();
tokenServiceCrossDomainRequest.url = extractCrossDomainPolicyFileURL(serverInfo.authInfo.tokenServicesUrl);
tokenServiceCrossDomainRequest.resultFormat = HTTPService.RESULT_FORMAT_E4X;
tokenServiceCrossDomainRequest.addEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.addEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
tokenServiceCrossDomainRequest.send();
function tokenServiceSecurityRequest_resultHandler(event:ResultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Found token service crossdomain.xml");
}
tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
const startsWithHTTPS:RegExp = /^https/;
if (startsWithHTTPS.test(tokenServiceCrossDomainRequest.url))
{
const tokenServiceCrossDomainXML:XML = event.result as XML;
const hasSecurityEnabled:Boolean =
tokenServiceCrossDomainXML.child("allow-access-from").(attribute("secure") == "false").length() == 0
|| tokenServiceCrossDomainXML.child("allow-http-request-headers-from").(attribute("secure") == "false").length() == 0;
if (hasSecurityEnabled
&& !startsWithHTTPS.test(Model.instance.appDir.url))
{
securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceWithSecureCrossDomain');
}
}
}
function tokenServiceSecurityRequest_faultHandler(event:FaultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Could not find token service crossdomain.xml");
}
tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceMissingCrossDomain');
}
}
//continue with building service directory
startBuildingDirectory(serviceDirectoryBuildRequest);
}
function serviceSecurityRequest_faultHandler(fault:Fault, token:Object = null):void
{
//continue with building service directory
startBuildingDirectory(serviceDirectoryBuildRequest);
}
}
private function extractServiceInfoURL(url:String):String
{
return url.replace('/rest/services', '/rest/info');
}
private function startBuildingDirectory(serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest):void
{
if (Log.isInfo())
{
LOG.info('Building serviced directory {0}', serviceDirectoryBuildRequest.url);
}
const servicesDirectoryURL:RegExp = /.+\/rest\/services\/?/;
const serviceURLRootMatch:Array = servicesDirectoryURL.exec(serviceDirectoryBuildRequest.url);
if (!serviceURLRootMatch)
{
return;
}
currentNodeFilter = filterFromSearchType(serviceDirectoryBuildRequest.searchType);
rootNode = new ServiceDirectoryRootNode(serviceDirectoryBuildRequest.url, currentNodeFilter);
rootNode.addEventListener(URLNodeTraversalEvent.END_REACHED, rootNode_completeHandler);
rootNode.addEventListener(FaultEvent.FAULT, rootNode_faultHandler);
credential = IdentityManager.instance.findCredential(serviceURLRootMatch[0]);
if (credential)
{
rootNode.token = credential.token;
}
rootNode.loadChildren();
}
private function filterFromSearchType(searchType:String):INodeFilter
{
if (searchType == ServiceDirectoryBuildRequest.QUERYABLE_LAYER_SEARCH)
{
return new QueryableLayerFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.GEOPROCESSING_TASK_SEARCH)
{
return new GPTaskFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.GEOCODER_SEARCH)
{
return new GeocoderFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.ROUTE_LAYER_SEARCH)
{
return new RouteLayerFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.MAP_SERVER_SEARCH)
{
return new MapServerFilter();
}
else //MAP LAYER SEARCH
{
return new MapLayerFilter();
}
}
private function rootNode_completeHandler(event:URLNodeTraversalEvent):void
{
if (Log.isInfo())
{
LOG.info("Finished building service directory");
}
dispatchEvent(
new ServiceDirectoryBuilderEvent(ServiceDirectoryBuilderEvent.COMPLETE,
new ServiceDirectoryInfo(rootNode,
event.urlNodes,
currentNodeFilter,
hasCrossDomain,
isServiceSecured,
securityWarning,
owningSystemURL)));
}
protected function rootNode_faultHandler(event:FaultEvent):void
{
if (Log.isInfo())
{
LOG.info("Could not build service directory");
}
dispatchEvent(event);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed 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 com.esri.builder.components.serviceBrowser.supportClasses
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.components.supportClasses.Credential;
import com.esri.ags.tasks.JSONTask;
import com.esri.builder.components.serviceBrowser.filters.GPTaskFilter;
import com.esri.builder.components.serviceBrowser.filters.GeocoderFilter;
import com.esri.builder.components.serviceBrowser.filters.INodeFilter;
import com.esri.builder.components.serviceBrowser.filters.MapLayerFilter;
import com.esri.builder.components.serviceBrowser.filters.MapServerFilter;
import com.esri.builder.components.serviceBrowser.filters.QueryableLayerFilter;
import com.esri.builder.components.serviceBrowser.filters.RouteLayerFilter;
import com.esri.builder.components.serviceBrowser.nodes.ServiceDirectoryRootNode;
import com.esri.builder.model.Model;
import com.esri.builder.supportClasses.LogUtil;
import flash.events.EventDispatcher;
import flash.net.URLVariables;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
public final class ServiceDirectoryBuilder extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(ServiceDirectoryBuilder);
private static const DEFAULT_REQUEST_TIMEOUT_IN_SECONDS:Number = 10;
private var count:int;
private var searchType:String;
private var serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest;
private var hasCrossDomain:Boolean;
private var crossDomainRequest:HTTPService;
private var credential:Credential;
private var rootNode:ServiceDirectoryRootNode;
private var currentNodeFilter:INodeFilter;
private var isServiceSecured:Boolean;
private var securityWarning:String;
private var owningSystemURL:String;
public function buildServiceDirectory(serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest):void
{
if (Log.isInfo())
{
LOG.info("Building service directory");
}
this.serviceDirectoryBuildRequest = serviceDirectoryBuildRequest;
try
{
checkCrossDomainBeforeBuildingDirectory();
}
catch (error:Error)
{
//TODO: handle error
}
}
private function checkCrossDomainBeforeBuildingDirectory():void
{
if (Log.isDebug())
{
LOG.debug("Checking service URL crossdomain.xml");
}
crossDomainRequest = new HTTPService();
crossDomainRequest.url = extractCrossDomainPolicyFileURL(serviceDirectoryBuildRequest.url);
crossDomainRequest.addEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.addEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest.requestTimeout = DEFAULT_REQUEST_TIMEOUT_IN_SECONDS;
crossDomainRequest.send();
function crossDomainRequest_resultHandler(event:ResultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Found service crossdomain.xml");
}
crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest = null;
hasCrossDomain = true;
checkIfServiceIsSecure();
}
function crossDomainRequest_faultHandler(event:FaultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Could not find service crossdomain.xml");
}
crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler);
crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler);
crossDomainRequest = null;
hasCrossDomain = false;
checkIfServiceIsSecure();
}
}
private function extractCrossDomainPolicyFileURL(url:String):String
{
var baseURL:RegExp = /(https?:\/\/)([^\/]+\/)/
var baseURLMatch:Array = url.match(baseURL);
return baseURLMatch[0] + 'crossdomain.xml';
}
private function checkIfServiceIsSecure():void
{
if (Log.isInfo())
{
LOG.info("Checking if service is secure");
}
var serviceSecurityRequest:JSONTask = new JSONTask();
serviceSecurityRequest.url = extractServiceInfoURL(serviceDirectoryBuildRequest.url);
const param:URLVariables = new URLVariables();
param.f = 'json';
serviceSecurityRequest.execute(param, new AsyncResponder(serviceSecurityRequest_resultHandler, serviceSecurityRequest_faultHandler));
function serviceSecurityRequest_resultHandler(serverInfo:Object, token:Object = null):void
{
isServiceSecured = (serverInfo.currentVersion >= 10.01
&& serverInfo.authInfo
&& serverInfo.authInfo.isTokenBasedSecurity);
owningSystemURL = serverInfo.owningSystemUrl;
if (isServiceSecured)
{
if (Log.isDebug())
{
LOG.debug("Service is secure");
}
if (Log.isDebug())
{
LOG.debug("Checking token service crossdomain.xml");
}
const tokenServiceCrossDomainRequest:HTTPService = new HTTPService();
tokenServiceCrossDomainRequest.url = extractCrossDomainPolicyFileURL(serverInfo.authInfo.tokenServicesUrl);
tokenServiceCrossDomainRequest.resultFormat = HTTPService.RESULT_FORMAT_E4X;
tokenServiceCrossDomainRequest.addEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.addEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
tokenServiceCrossDomainRequest.send();
function tokenServiceSecurityRequest_resultHandler(event:ResultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Found token service crossdomain.xml");
}
tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
const startsWithHTTPS:RegExp = /^https/;
if (startsWithHTTPS.test(tokenServiceCrossDomainRequest.url))
{
const tokenServiceCrossDomainXML:XML = event.result as XML;
const hasSecurityEnabled:Boolean =
tokenServiceCrossDomainXML.child("allow-access-from").(attribute("secure") == "false").length() == 0
|| tokenServiceCrossDomainXML.child("allow-http-request-headers-from").(attribute("secure") == "false").length() == 0;
if (hasSecurityEnabled
&& !startsWithHTTPS.test(Model.instance.appDir.url))
{
securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceWithSecureCrossDomain');
}
}
}
function tokenServiceSecurityRequest_faultHandler(event:FaultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Could not find token service crossdomain.xml");
}
tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler);
tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler);
securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceMissingCrossDomain');
}
}
//continue with building service directory
startBuildingDirectory();
}
function serviceSecurityRequest_faultHandler(fault:Fault, token:Object = null):void
{
//continue with building service directory
startBuildingDirectory();
}
}
private function extractServiceInfoURL(url:String):String
{
return url.replace('/rest/services', '/rest/info');
}
private function startBuildingDirectory():void
{
if (Log.isInfo())
{
LOG.info('Building serviced directory {0}', serviceDirectoryBuildRequest.url);
}
const servicesDirectoryURL:RegExp = /.+\/rest\/services\/?/;
const serviceURLRootMatch:Array = servicesDirectoryURL.exec(serviceDirectoryBuildRequest.url);
if (!serviceURLRootMatch)
{
return;
}
currentNodeFilter = filterFromSearchType(serviceDirectoryBuildRequest.searchType);
rootNode = new ServiceDirectoryRootNode(serviceDirectoryBuildRequest.url, currentNodeFilter);
rootNode.addEventListener(URLNodeTraversalEvent.END_REACHED, rootNode_completeHandler);
rootNode.addEventListener(FaultEvent.FAULT, rootNode_faultHandler);
credential = IdentityManager.instance.findCredential(serviceURLRootMatch[0]);
if (credential)
{
rootNode.token = credential.token;
}
rootNode.loadChildren();
}
private function filterFromSearchType(searchType:String):INodeFilter
{
if (searchType == ServiceDirectoryBuildRequest.QUERYABLE_LAYER_SEARCH)
{
return new QueryableLayerFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.GEOPROCESSING_TASK_SEARCH)
{
return new GPTaskFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.GEOCODER_SEARCH)
{
return new GeocoderFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.ROUTE_LAYER_SEARCH)
{
return new RouteLayerFilter();
}
else if (searchType == ServiceDirectoryBuildRequest.MAP_SERVER_SEARCH)
{
return new MapServerFilter();
}
else //MAP LAYER SEARCH
{
return new MapLayerFilter();
}
}
private function rootNode_completeHandler(event:URLNodeTraversalEvent):void
{
if (Log.isInfo())
{
LOG.info("Finished building service directory");
}
dispatchEvent(
new ServiceDirectoryBuilderEvent(ServiceDirectoryBuilderEvent.COMPLETE,
new ServiceDirectoryInfo(rootNode,
event.urlNodes,
currentNodeFilter,
hasCrossDomain,
isServiceSecured,
securityWarning,
owningSystemURL)));
}
protected function rootNode_faultHandler(event:FaultEvent):void
{
if (Log.isInfo())
{
LOG.info("Could not build service directory");
}
dispatchEvent(event);
}
}
}
|
Add field for service directory build request (ServiceDirectoryBuilder).
|
Add field for service directory build request (ServiceDirectoryBuilder).
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
920a9df3ac3c42aef52c6668693af96caa983b8d
|
src/as/com/threerings/flash/MenuUtil.as
|
src/as/com/threerings/flash/MenuUtil.as
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flash {
import flash.ui.ContextMenuItem;
import flash.events.ContextMenuEvent;
import com.threerings.util.CommandEvent;
/**
*/
public class MenuUtil
{
/**
* Create a menu item that will submit a controller command when selected.
*/
public static function createControllerMenuItem (
caption :String, cmd :String, arg :Object = null,
separatorBefore :Boolean = false, enabled :Boolean = true,
visible :Boolean = true) :ContextMenuItem
{
var item :ContextMenuItem =
new ContextMenuItem(caption, separatorBefore, enabled, visible);
item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,
function (event :ContextMenuEvent) :void {
CommandEvent.dispatch(event.mouseTarget, cmd, arg);
});
return item;
}
}
}
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flash {
import flash.ui.ContextMenuItem;
import flash.events.ContextMenuEvent;
import com.threerings.util.CommandEvent;
/**
*/
public class MenuUtil
{
/**
* Create a menu item that will submit a controller command when selected.
*/
public static function createControllerMenuItem (
caption :String, cmdOrFn :Object, arg :Object = null,
separatorBefore :Boolean = false, enabled :Boolean = true,
visible :Boolean = true) :ContextMenuItem
{
var item :ContextMenuItem =
new ContextMenuItem(caption, separatorBefore, enabled, visible);
item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,
function (event :ContextMenuEvent) :void {
CommandEvent.dispatch(event.mouseTarget, cmdOrFn, arg);
});
return item;
}
}
}
|
Allow a function to be specified here, too.
|
Allow a function to be specified here, too.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@174 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
67b084138b2282a7126077eed16a65a982bd220f
|
src/RTMP.as
|
src/RTMP.as
|
package {
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.system.Security;
import flash.net.NetStream;
import flash.events.*;
import flash.utils.setTimeout;
import org.osmf.containers.MediaContainer;
import org.osmf.elements.VideoElement;
import org.osmf.net.NetStreamLoadTrait;
import org.osmf.media.DefaultMediaFactory;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaPlayer;
import org.osmf.media.URLResource;
import org.osmf.events.TimeEvent;
import org.osmf.events.BufferEvent;
import org.osmf.events.MediaElementEvent;
import org.osmf.events.LoadEvent;
import org.osmf.traits.MediaTraitType;
[SWF(width="640", height="360")]
public class RTMP extends Sprite {
private var playbackId:String;
private var mediaFactory:DefaultMediaFactory;
private var mediaContainer:MediaContainer;
private var mediaPlayer:MediaPlayer;
private var netStream:NetStream;
private var mediaElement:MediaElement;
private var netStreamLoadTrait:NetStreamLoadTrait;
private var playbackState:String = "IDLE";
public function RTMP() {
Security.allowDomain('*');
Security.allowInsecureDomain('*');
playbackId = this.root.loaderInfo.parameters.playbackId;
mediaFactory = new DefaultMediaFactory();
mediaContainer = new MediaContainer();
setupCallbacks();
setupGetters();
ExternalInterface.call('console.log', 'clappr rtmp 0.8-alpha');
_triggerEvent('flashready');
}
private function setupCallbacks():void {
ExternalInterface.addCallback("playerPlay", playerPlay);
ExternalInterface.addCallback("playerResume", playerPlay);
ExternalInterface.addCallback("playerPause", playerPause);
ExternalInterface.addCallback("playerStop", playerStop);
ExternalInterface.addCallback("playerSeek", playerSeek);
ExternalInterface.addCallback("playerVolume", playerVolume);
}
private function setupGetters():void {
ExternalInterface.addCallback("getState", getState);
ExternalInterface.addCallback("getPosition", getPosition);
ExternalInterface.addCallback("getDuration", getDuration);
}
private function onTraitAdd(event:MediaElementEvent):void {
if (mediaElement.hasTrait(MediaTraitType.LOAD)) {
netStreamLoadTrait = mediaElement.getTrait(MediaTraitType.LOAD) as NetStreamLoadTrait;
netStreamLoadTrait.addEventListener(LoadEvent.LOAD_STATE_CHANGE, onLoaded);
}
}
private function onLoaded(event:LoadEvent):void {
netStream = netStreamLoadTrait.netStream;
netStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
mediaPlayer.play();
}
private function netStatusHandler(event:NetStatusEvent):void {
if (playbackState == "ENDED") {
return;
} else if (event.info.code == "NetStream.Buffer.Full") {
playbackState = "PLAYING";
_triggerEvent('statechanged');
} else if (event.info.code == "NetStream.Buffer.Empty" || event.info.code == "NetStream.Seek.Notify") {
playbackState = "PLAYING_BUFFERING";
_triggerEvent('statechanged');
}
}
private function playerPlay(url:String=null):void {
if (!mediaElement) {
playbackState = "PLAYING_BUFFERING";
_triggerEvent('statechanged');
mediaElement = mediaFactory.createMediaElement(new URLResource(url));
mediaElement.addEventListener(MediaElementEvent.TRAIT_ADD, onTraitAdd);
mediaPlayer = new MediaPlayer(mediaElement);
mediaPlayer.autoPlay = false;
mediaPlayer.addEventListener(TimeEvent.CURRENT_TIME_CHANGE, onTimeUpdated);
mediaPlayer.addEventListener(TimeEvent.DURATION_CHANGE, onTimeUpdated);
mediaPlayer.addEventListener(TimeEvent.COMPLETE, onFinish);
mediaContainer.addMediaElement(mediaElement);
addChild(mediaContainer);
} else {
ExternalInterface.call('console.log', 'playing with media element');
mediaPlayer.play();
}
}
private function playerPause():void {
ExternalInterface.call('console.log', 'player pause');
mediaPlayer.pause();
playbackState = "PAUSED";
}
private function playerSeek(seconds:Number):void {
mediaPlayer.seek(seconds);
}
private function playerStop():void {
mediaPlayer.stop();
playbackState = "IDLE";
}
private function playerVolume(level:Number):void {
mediaPlayer.volume = level/100;
}
private function getState():String {
return playbackState;
}
private function getPosition():Number {
return mediaPlayer.currentTime;
}
private function getDuration():Number {
return mediaPlayer.duration;
}
private function onTimeUpdated(event:TimeEvent):void {
_triggerEvent('progress');
_triggerEvent('timeupdate');
}
private function onFinish(event:TimeEvent):void {
mediaPlayer.stop();
playbackState = 'ENDED';
_triggerEvent('statechanged');
}
private function _triggerEvent(name: String):void {
ExternalInterface.call('Clappr.Mediator.trigger("' + playbackId + ':' + name +'")');
}
}
}
|
package {
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.system.Security;
import flash.net.NetStream;
import flash.events.*;
import flash.utils.setTimeout;
import org.osmf.containers.MediaContainer;
import org.osmf.elements.VideoElement;
import org.osmf.net.NetStreamLoadTrait;
import org.osmf.media.DefaultMediaFactory;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaPlayer;
import org.osmf.media.URLResource;
import org.osmf.events.TimeEvent;
import org.osmf.events.BufferEvent;
import org.osmf.events.MediaElementEvent;
import org.osmf.events.LoadEvent;
import org.osmf.traits.MediaTraitType;
[SWF(width="640", height="360")]
public class RTMP extends Sprite {
private var playbackId:String;
private var mediaFactory:DefaultMediaFactory;
private var mediaContainer:MediaContainer;
private var mediaPlayer:MediaPlayer;
private var netStream:NetStream;
private var mediaElement:MediaElement;
private var netStreamLoadTrait:NetStreamLoadTrait;
private var playbackState:String = "IDLE";
public function RTMP() {
Security.allowDomain('*');
Security.allowInsecureDomain('*');
playbackId = this.root.loaderInfo.parameters.playbackId;
mediaFactory = new DefaultMediaFactory();
mediaContainer = new MediaContainer();
setupCallbacks();
setupGetters();
ExternalInterface.call('console.log', 'clappr rtmp 0.8-alpha');
_triggerEvent('flashready');
}
private function setupCallbacks():void {
ExternalInterface.addCallback("playerPlay", playerPlay);
ExternalInterface.addCallback("playerResume", playerPlay);
ExternalInterface.addCallback("playerPause", playerPause);
ExternalInterface.addCallback("playerStop", playerStop);
ExternalInterface.addCallback("playerSeek", playerSeek);
ExternalInterface.addCallback("playerVolume", playerVolume);
}
private function setupGetters():void {
ExternalInterface.addCallback("getState", getState);
ExternalInterface.addCallback("getPosition", getPosition);
ExternalInterface.addCallback("getDuration", getDuration);
}
private function onTraitAdd(event:MediaElementEvent):void {
if (mediaElement.hasTrait(MediaTraitType.LOAD)) {
netStreamLoadTrait = mediaElement.getTrait(MediaTraitType.LOAD) as NetStreamLoadTrait;
netStreamLoadTrait.addEventListener(LoadEvent.LOAD_STATE_CHANGE, onLoaded);
}
}
private function onLoaded(event:LoadEvent):void {
netStream = netStreamLoadTrait.netStream;
netStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
mediaPlayer.play();
}
private function netStatusHandler(event:NetStatusEvent):void {
if (playbackState == "ENDED") {
return;
} else if (event.info.code == "NetStream.Buffer.Full") {
playbackState = "PLAYING";
_triggerEvent('statechanged');
} else if (event.info.code == "NetStream.Buffer.Empty" || event.info.code == "NetStream.Seek.Notify") {
playbackState = "PLAYING_BUFFERING";
_triggerEvent('statechanged');
}
}
private function playerPlay(url:String=null):void {
if (!mediaElement) {
playbackState = "PLAYING_BUFFERING";
_triggerEvent('statechanged');
mediaElement = mediaFactory.createMediaElement(new URLResource(url));
mediaElement.addEventListener(MediaElementEvent.TRAIT_ADD, onTraitAdd);
mediaPlayer = new MediaPlayer(mediaElement);
mediaPlayer.autoPlay = false;
mediaPlayer.addEventListener(TimeEvent.CURRENT_TIME_CHANGE, onTimeUpdated);
mediaPlayer.addEventListener(TimeEvent.DURATION_CHANGE, onTimeUpdated);
mediaPlayer.addEventListener(TimeEvent.COMPLETE, onFinish);
mediaContainer.addMediaElement(mediaElement);
addChild(mediaContainer);
} else {
mediaPlayer.play();
}
}
private function playerPause():void {
mediaPlayer.pause();
playbackState = "PAUSED";
}
private function playerSeek(seconds:Number):void {
mediaPlayer.seek(seconds);
}
private function playerStop():void {
mediaPlayer.stop();
playbackState = "IDLE";
}
private function playerVolume(level:Number):void {
mediaPlayer.volume = level/100;
}
private function getState():String {
return playbackState;
}
private function getPosition():Number {
return mediaPlayer.currentTime;
}
private function getDuration():Number {
return mediaPlayer.duration;
}
private function onTimeUpdated(event:TimeEvent):void {
_triggerEvent('progress');
_triggerEvent('timeupdate');
}
private function onFinish(event:TimeEvent):void {
mediaPlayer.stop();
playbackState = 'ENDED';
_triggerEvent('statechanged');
}
private function _triggerEvent(name: String):void {
ExternalInterface.call('Clappr.Mediator.trigger("' + playbackId + ':' + name +'")');
}
}
}
|
remove logs
|
RTMP.as: remove logs
|
ActionScript
|
apache-2.0
|
hxl-dy/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin
|
ee28b307c32e7fddbee4e6af0982b8cb0715732e
|
WeaveAdmin/src/weave/services/EntityCache.as
|
WeaveAdmin/src/weave/services/EntityCache.as
|
package weave.services
{
import flash.utils.Dictionary;
import mx.rpc.events.ResultEvent;
import weave.api.getCallbackCollection;
import weave.api.core.ICallbackCollection;
import weave.api.core.ILinkableObject;
import weave.api.data.ColumnMetadata;
import weave.services.beans.Entity;
import weave.services.beans.EntityMetadata;
import weave.services.beans.EntityTableInfo;
import weave.utils.Dictionary2D;
public class EntityCache implements ILinkableObject
{
public static const ROOT_ID:int = -1;
private var cache_dirty:Object = {}; // id -> Boolean
private var cache_entity:Object = {}; // id -> Array <Entity>
private var d2d_child_parent:Dictionary2D = new Dictionary2D(); // <child_id,parent_id> -> Boolean
private var delete_later:Object = {}; // id -> Boolean
private var _dataTableIds:Array = []; // array of EntityTableInfo
private var _dataTableLookup:Object = {}; // id -> EntityTableInfo
public function EntityCache()
{
callbacks.addGroupedCallback(this, fetchDirtyEntities);
Admin.service.addHook(Admin.service.authenticate, null, fetchDirtyEntities);
}
public function invalidate(id:int, alsoInvalidateParents:Boolean = false):void
{
callbacks.delayCallbacks();
if (!cache_dirty[id])
callbacks.triggerCallbacks();
cache_dirty[id] = true;
if (!cache_entity[id])
{
var entity:Entity = new Entity(id);
cache_entity[id] = entity;
}
if (alsoInvalidateParents)
{
var parents:Dictionary = d2d_child_parent.dictionary[id];
if (parents)
{
// when a child is deleted, invalidate parents
for (var parentId:* in parents)
invalidate(parentId);
}
else
{
// invalidate root when child has no parents
invalidate(ROOT_ID);
}
}
callbacks.resumeCallbacks();
}
private function get callbacks():ICallbackCollection { return getCallbackCollection(this); }
public function getEntity(id:int):Entity
{
// if there is no cached value, call invalidate() to create a placeholder.
if (!cache_entity[id])
invalidate(id);
return cache_entity[id];
}
private function fetchDirtyEntities(..._):void
{
if (!Admin.instance.userHasAuthenticated)
return;
var id:*;
// delete marked entities
var deleted:Boolean = false;
var idsToRemove:Array = [];
for (id in delete_later)
idsToRemove.push(id);
if (idsToRemove.length)
{
addAsyncResponder(Admin.service.removeEntities(idsToRemove), handleRemoveEntities);
delete_later = {};
}
// request invalidated entities
var ids:Array = [];
for (id in cache_dirty)
{
if (id == ROOT_ID)
addAsyncResponder(Admin.service.getDataTableList(), handleDataTableList);
ids.push(int(id));
}
if (ids.length > 0)
{
cache_dirty = {};
addAsyncResponder(Admin.service.getEntitiesById(ids), getEntityHandler);
}
}
private function handleRemoveEntities(event:ResultEvent, token:Object):void
{
for each (var id:int in event.result as Array)
invalidate(id, true);
}
private function getEntityHandler(event:ResultEvent, token:Object):void
{
for each (var result:Object in event.result)
{
var id:int = Entity.getEntityIdFromResult(result);
var entity:Entity = cache_entity[id] || new Entity(id);
entity.copyFromResult(result);
cache_entity[id] = entity;
// cache child-to-parent mappings
for each (var childId:int in entity.childIds)
d2d_child_parent.set(childId, id, true);
}
callbacks.triggerCallbacks();
}
private function handleDataTableList(event:ResultEvent, token:Object = null):void
{
var items:Array = event.result as Array;
for (var i:int = 0; i < items.length; i++)
{
var item:EntityTableInfo = new EntityTableInfo(items[i]);
_dataTableLookup[item.id] = item;
items[i] = item.id;
}
_dataTableIds = items;
callbacks.triggerCallbacks();
}
public function getDataTableIds():Array
{
getEntity(ROOT_ID);
return _dataTableIds;
}
public function getDataTableInfo(id:int):EntityTableInfo
{
getEntity(ROOT_ID);
return _dataTableLookup[id];
}
public function clearCache():void
{
//TODO: clearCache() still causes full data table metadata to be requested
callbacks.delayCallbacks();
// we don't want to delete the cache because we can still use the cached values for display in the meantime.
for (var id:* in cache_entity)
invalidate(id);
callbacks.triggerCallbacks();
callbacks.resumeCallbacks();
}
public function update_metadata(id:int, diff:EntityMetadata):void
{
Admin.service.updateEntity(id, diff);
invalidate(id);
}
public function add_tag(label:String, parentId:int):void
{
/* Entity creation should usually impact root, so we'll invalidate root's cache entry and refetch. */
var em:EntityMetadata = new EntityMetadata();
em.publicMetadata[ColumnMetadata.TITLE] = label;
Admin.service.newEntity(Entity.TYPE_CATEGORY, em, parentId);
invalidate(parentId);
}
public function delete_entity(id:int):void
{
/* Entity deletion should usually impact root, so we'll invalidate root's cache entry and refetch. */
delete_later[id] = true;
invalidate(id, true);
}
public function add_child(parent_id:int, child_id:int, index:int):void
{
if (parent_id == ROOT_ID && delete_later[child_id])
{
// prevent hierarchy-dragged-to-root from removing the hierarchy
delete delete_later[child_id];
return;
}
Admin.service.addParentChildRelationship(parent_id, child_id, index);
invalidate(parent_id);
}
public function remove_child(parent_id:int, child_id:int):void
{
// remove from root not supported, but invalidate root anyway in case the child is added via add_child later
if (parent_id == ROOT_ID)
{
delete_later[child_id] = true;
invalidate(ROOT_ID);
}
else
{
Admin.service.removeParentChildRelationship(parent_id, child_id);
}
invalidate(child_id, true);
}
}
}
|
package weave.services
{
import flash.utils.Dictionary;
import mx.rpc.events.ResultEvent;
import weave.api.getCallbackCollection;
import weave.api.core.ICallbackCollection;
import weave.api.core.ILinkableObject;
import weave.api.data.ColumnMetadata;
import weave.services.beans.Entity;
import weave.services.beans.EntityMetadata;
import weave.services.beans.EntityTableInfo;
import weave.utils.Dictionary2D;
public class EntityCache implements ILinkableObject
{
public static const ROOT_ID:int = -1;
private var cache_dirty:Object = {}; // id -> Boolean
private var cache_entity:Object = {}; // id -> Array <Entity>
private var d2d_child_parent:Dictionary2D = new Dictionary2D(); // <child_id,parent_id> -> Boolean
private var delete_later:Object = {}; // id -> Boolean
private var _dataTableIds:Array = []; // array of EntityTableInfo
private var _dataTableLookup:Object = {}; // id -> EntityTableInfo
private var pending_invalidate:Object = {}; // id -> Boolean; used to remember which ids to invalidate the next time the entity is requested
public function EntityCache()
{
callbacks.addGroupedCallback(this, fetchDirtyEntities);
Admin.service.addHook(Admin.service.authenticate, null, fetchDirtyEntities);
}
public function invalidate(id:int, alsoInvalidateParents:Boolean = false):void
{
callbacks.delayCallbacks();
if (!cache_dirty[id])
callbacks.triggerCallbacks();
pending_invalidate[id] = false;
cache_dirty[id] = true;
if (!cache_entity[id])
{
var entity:Entity = new Entity(id);
cache_entity[id] = entity;
}
if (alsoInvalidateParents)
{
var parents:Dictionary = d2d_child_parent.dictionary[id];
if (parents)
{
// when a child is deleted, invalidate parents
for (var parentId:* in parents)
invalidate(parentId);
}
else
{
// invalidate root when child has no parents
invalidate(ROOT_ID);
}
}
callbacks.resumeCallbacks();
}
private function get callbacks():ICallbackCollection { return getCallbackCollection(this); }
public function getEntity(id:int):Entity
{
// if there is no cached value, call invalidate() to create a placeholder.
if (!cache_entity[id] || pending_invalidate[id])
invalidate(id);
return cache_entity[id];
}
private function fetchDirtyEntities(..._):void
{
if (!Admin.instance.userHasAuthenticated)
return;
var id:*;
// delete marked entities
var deleted:Boolean = false;
var idsToRemove:Array = [];
for (id in delete_later)
idsToRemove.push(id);
if (idsToRemove.length)
{
addAsyncResponder(Admin.service.removeEntities(idsToRemove), handleRemoveEntities);
delete_later = {};
}
// request invalidated entities
var ids:Array = [];
for (id in cache_dirty)
{
// when requesting root, also request data table list
if (id == ROOT_ID)
addAsyncResponder(Admin.service.getDataTableList(), handleDataTableList);
ids.push(int(id));
}
if (ids.length > 0)
{
cache_dirty = {};
addAsyncResponder(Admin.service.getEntitiesById(ids), getEntityHandler);
}
}
private function handleRemoveEntities(event:ResultEvent, token:Object):void
{
for each (var id:int in event.result as Array)
invalidate(id, true);
}
private function getEntityHandler(event:ResultEvent, token:Object):void
{
for each (var result:Object in event.result)
{
var id:int = Entity.getEntityIdFromResult(result);
var entity:Entity = cache_entity[id] || new Entity(id);
entity.copyFromResult(result);
cache_entity[id] = entity;
// cache child-to-parent mappings
for each (var childId:int in entity.childIds)
d2d_child_parent.set(childId, id, true);
}
callbacks.triggerCallbacks();
}
private function handleDataTableList(event:ResultEvent, token:Object = null):void
{
var items:Array = event.result as Array;
for (var i:int = 0; i < items.length; i++)
{
var item:EntityTableInfo = new EntityTableInfo(items[i]);
_dataTableLookup[item.id] = item;
items[i] = item.id;
}
_dataTableIds = items;
callbacks.triggerCallbacks();
}
public function getDataTableIds():Array
{
getEntity(ROOT_ID);
return _dataTableIds;
}
public function getDataTableInfo(id:int):EntityTableInfo
{
getEntity(ROOT_ID);
return _dataTableLookup[id];
}
public function clearCache():void
{
callbacks.delayCallbacks();
// we don't want to delete the cache because we can still use the cached values for display in the meantime.
for (var id:* in cache_entity)
pending_invalidate[id] = true;
callbacks.triggerCallbacks();
callbacks.resumeCallbacks();
}
public function update_metadata(id:int, diff:EntityMetadata):void
{
Admin.service.updateEntity(id, diff);
invalidate(id);
}
public function add_tag(label:String, parentId:int):void
{
/* Entity creation should usually impact root, so we'll invalidate root's cache entry and refetch. */
var em:EntityMetadata = new EntityMetadata();
em.publicMetadata[ColumnMetadata.TITLE] = label;
Admin.service.newEntity(Entity.TYPE_CATEGORY, em, parentId);
invalidate(parentId);
}
public function delete_entity(id:int):void
{
/* Entity deletion should usually impact root, so we'll invalidate root's cache entry and refetch. */
delete_later[id] = true;
invalidate(id, true);
}
public function add_child(parent_id:int, child_id:int, index:int):void
{
if (parent_id == ROOT_ID && delete_later[child_id])
{
// prevent hierarchy-dragged-to-root from removing the hierarchy
delete delete_later[child_id];
return;
}
Admin.service.addParentChildRelationship(parent_id, child_id, index);
invalidate(parent_id);
}
public function remove_child(parent_id:int, child_id:int):void
{
// remove from root not supported, but invalidate root anyway in case the child is added via add_child later
if (parent_id == ROOT_ID)
{
delete_later[child_id] = true;
invalidate(ROOT_ID);
}
else
{
Admin.service.removeParentChildRelationship(parent_id, child_id);
}
invalidate(child_id, true);
}
}
}
|
refresh button no longer causes everything to be requested at once.
|
refresh button no longer causes everything to be requested at once.
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
b38c7037e20f45004d4c78d3c8c70db6f1c0ea80
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/core/MXMLBeadViewBaseDataBinding.as
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/core/MXMLBeadViewBaseDataBinding.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.core
{
import org.apache.flex.binding.ConstantBinding;
import org.apache.flex.binding.GenericBinding;
import org.apache.flex.binding.PropertyWatcher;
import org.apache.flex.binding.SimpleBinding;
import org.apache.flex.binding.WatcherBase;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The ViewBaseDataBinding class implements databinding for
* ViewBase instances. Different classes can have
* different databinding implementation that optimize for
* the different lifecycles. For example, an item renderer
* databinding implementation can wait to execute databindings
* until the data property is set.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class MXMLBeadViewBaseDataBinding extends DataBindingBase implements IBead
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function MXMLBeadViewBaseDataBinding()
{
super();
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(_strand).addEventListener("initBindings", initCompleteHandler);
}
private function initCompleteHandler(event:Event):void
{
var fieldWatcher:Object;
var sb:SimpleBinding;
if (!("_bindings" in _strand))
return;
var bindingData:Array = _strand["_bindings"];
var n:int = bindingData[0];
var bindings:Array = [];
var i:int;
var index:int = 1;
for (i = 0; i < n; i++)
{
var binding:Object = {};
binding.source = bindingData[index++];
binding.destFunc = bindingData[index++];
binding.destination = bindingData[index++];
bindings.push(binding);
}
var watchers:Object = decodeWatcher(bindingData.slice(index));
for (i = 0; i < n; i++)
{
binding = bindings[i];
if (binding.source is Array)
{
if (binding.source[0] == "model")
{
if (binding.source.length == 2 && binding.destination.length == 2)
{
var destObject:Object;
var destination:IStrand;
// can be simplebinding or constantbinding
var modelWatcher:Object = watchers.watcherMap["model"];
fieldWatcher = modelWatcher.children.watcherMap[binding.source[1]];
if (fieldWatcher.eventNames is String)
{
sb = new SimpleBinding();
sb.destinationPropertyName = binding.destination[1];
sb.eventName = fieldWatcher.eventNames as String;
sb.sourceID = binding.source[0];
sb.sourcePropertyName = binding.source[1];
sb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(sb);
else
{
if (destObject)
{
sb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
else if (fieldWatcher.eventNames == null)
{
var cb:ConstantBinding = new ConstantBinding();
cb.destinationPropertyName = binding.destination[1];
cb.sourceID = binding.source[0];
cb.sourcePropertyName = binding.source[1];
cb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(cb);
else
{
if (destObject)
{
cb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
}
}
}
else if (binding.source is String)
{
fieldWatcher = watchers.watcherMap[binding.source];
if (fieldWatcher.eventNames is String)
{
sb = new SimpleBinding();
sb.destinationPropertyName = binding.destination[1];
sb.eventName = fieldWatcher.eventNames as String;
sb.sourcePropertyName = binding.source;
sb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(sb);
else
{
if (destObject)
{
sb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
}
else
{
makeGenericBinding(binding, i, watchers);
}
}
}
private function makeGenericBinding(binding:Object, index:int, watchers:Object):void
{
var gb:GenericBinding = new GenericBinding();
gb.setDocument(_strand);
gb.destinationData = binding.destination;
gb.destinationFunction = binding.destFunc;
gb.source = binding.source;
setupWatchers(gb, index, watchers.watchers, null);
}
private function setupWatchers(gb:GenericBinding, index:int, watchers:Array, parentWatcher:WatcherBase):void
{
var n:int = watchers.length;
for (var i:int = 0; i < n; i++)
{
var watcher:Object = watchers[i];
if (watcher.bindings.indexOf(index) != -1)
{
var type:String = watcher.type;
switch (type)
{
case "property":
{
var pw:PropertyWatcher = new PropertyWatcher(this,
watcher.propertyName,
watcher.eventNames,
watcher.getterFunction);
watcher.watcher = pw;
if (parentWatcher)
pw.parentChanged(parentWatcher.value);
else
pw.parentChanged(_strand);
if (parentWatcher)
parentWatcher.addChild(pw);
if (watcher.children == null)
pw.addBinding(gb);
break;
}
}
if (watcher.children)
{
setupWatchers(gb, index, watcher.children, watcher.watcher);
}
}
}
}
private function decodeWatcher(bindingData:Array):Object
{
var watcherMap:Object = {};
var watchers:Array = [];
var n:int = bindingData.length;
var index:int = 0;
var watcherData:Object;
// FalconJX adds an extra null to the data so make sure
// we have enough data for a complete watcher otherwise
// say we are done
while (index < n - 2)
{
var watcherIndex:int = bindingData[index++];
var type:int = bindingData[index++];
switch (type)
{
case 0:
{
watcherData = { type: "function" };
watcherData.functionName = bindingData[index++];
watcherData.paramFunction = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
break;
}
case 1:
{
watcherData = { type: "static" };
watcherData.propertyName = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherData.getterFunction = bindingData[index++];
watcherData.parentObj = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
case 2:
{
watcherData = { type: "property" };
watcherData.propertyName = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherData.getterFunction = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
case 3:
{
watcherData = { type: "xml" };
watcherData.propertyName = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
}
watcherData.children = bindingData[index++];
if (watcherData.children != null)
{
watcherData.children = decodeWatcher(watcherData.children);
}
watcherData.index = watcherIndex;
watchers.push(watcherData);
}
return { watchers: watchers, watcherMap: watcherMap };
}
private var deferredBindings:Object = {};
private function deferredBindingsHandler(event:Event):void
{
for (var p:String in deferredBindings)
{
if (_strand[p] != null)
{
var destination:IStrand = _strand[p] as IStrand;
destination.addBead(deferredBindings[p]);
delete deferredBindings[p];
}
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.core
{
import org.apache.flex.binding.ConstantBinding;
import org.apache.flex.binding.GenericBinding;
import org.apache.flex.binding.PropertyWatcher;
import org.apache.flex.binding.SimpleBinding;
import org.apache.flex.binding.WatcherBase;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The ViewBaseDataBinding class implements databinding for
* ViewBase instances. Different classes can have
* different databinding implementation that optimize for
* the different lifecycles. For example, an item renderer
* databinding implementation can wait to execute databindings
* until the data property is set.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class MXMLBeadViewBaseDataBinding extends DataBindingBase implements IBead
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function MXMLBeadViewBaseDataBinding()
{
super();
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(_strand).addEventListener("initBindings", initCompleteHandler);
}
private function initCompleteHandler(event:Event):void
{
var fieldWatcher:Object;
var sb:SimpleBinding;
if (!("_bindings" in _strand))
return;
var bindingData:Array = _strand["_bindings"];
var n:int = bindingData[0];
var bindings:Array = [];
var i:int;
var index:int = 1;
for (i = 0; i < n; i++)
{
var binding:Object = {};
binding.source = bindingData[index++];
binding.destFunc = bindingData[index++];
binding.destination = bindingData[index++];
bindings.push(binding);
}
var watchers:Object = decodeWatcher(bindingData.slice(index));
for (i = 0; i < n; i++)
{
binding = bindings[i];
if (binding.source is Array)
{
if (binding.source[0] in _strand)
{
if (binding.source.length == 2 && binding.destination.length == 2)
{
var destObject:Object;
var destination:IStrand;
// can be simplebinding or constantbinding
var modelWatcher:Object = watchers.watcherMap[binding.source[0]];
fieldWatcher = modelWatcher.children.watcherMap[binding.source[1]];
if (fieldWatcher.eventNames is String)
{
sb = new SimpleBinding();
sb.destinationPropertyName = binding.destination[1];
sb.eventName = fieldWatcher.eventNames as String;
sb.sourceID = binding.source[0];
sb.sourcePropertyName = binding.source[1];
sb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(sb);
else
{
if (destObject)
{
sb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
else if (fieldWatcher.eventNames == null)
{
var cb:ConstantBinding = new ConstantBinding();
cb.destinationPropertyName = binding.destination[1];
cb.sourceID = binding.source[0];
cb.sourcePropertyName = binding.source[1];
cb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(cb);
else
{
if (destObject)
{
cb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
}
}
}
else if (binding.source is String)
{
fieldWatcher = watchers.watcherMap[binding.source];
if (fieldWatcher.eventNames is String)
{
sb = new SimpleBinding();
sb.destinationPropertyName = binding.destination[1];
sb.eventName = fieldWatcher.eventNames as String;
sb.sourcePropertyName = binding.source;
sb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(sb);
else
{
if (destObject)
{
sb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
}
else
{
makeGenericBinding(binding, i, watchers);
}
}
}
private function makeGenericBinding(binding:Object, index:int, watchers:Object):void
{
var gb:GenericBinding = new GenericBinding();
gb.setDocument(_strand);
gb.destinationData = binding.destination;
gb.destinationFunction = binding.destFunc;
gb.source = binding.source;
setupWatchers(gb, index, watchers.watchers, null);
}
private function setupWatchers(gb:GenericBinding, index:int, watchers:Array, parentWatcher:WatcherBase):void
{
var n:int = watchers.length;
for (var i:int = 0; i < n; i++)
{
var watcher:Object = watchers[i];
if (watcher.bindings.indexOf(index) != -1)
{
var type:String = watcher.type;
switch (type)
{
case "property":
{
var pw:PropertyWatcher = new PropertyWatcher(this,
watcher.propertyName,
watcher.eventNames,
watcher.getterFunction);
watcher.watcher = pw;
if (parentWatcher)
pw.parentChanged(parentWatcher.value);
else
pw.parentChanged(_strand);
if (parentWatcher)
parentWatcher.addChild(pw);
if (watcher.children == null)
pw.addBinding(gb);
break;
}
}
if (watcher.children)
{
setupWatchers(gb, index, watcher.children, watcher.watcher);
}
}
}
}
private function decodeWatcher(bindingData:Array):Object
{
var watcherMap:Object = {};
var watchers:Array = [];
var n:int = bindingData.length;
var index:int = 0;
var watcherData:Object;
// FalconJX adds an extra null to the data so make sure
// we have enough data for a complete watcher otherwise
// say we are done
while (index < n - 2)
{
var watcherIndex:int = bindingData[index++];
var type:int = bindingData[index++];
switch (type)
{
case 0:
{
watcherData = { type: "function" };
watcherData.functionName = bindingData[index++];
watcherData.paramFunction = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
break;
}
case 1:
{
watcherData = { type: "static" };
watcherData.propertyName = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherData.getterFunction = bindingData[index++];
watcherData.parentObj = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
case 2:
{
watcherData = { type: "property" };
watcherData.propertyName = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherData.getterFunction = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
case 3:
{
watcherData = { type: "xml" };
watcherData.propertyName = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
}
watcherData.children = bindingData[index++];
if (watcherData.children != null)
{
watcherData.children = decodeWatcher(watcherData.children);
}
watcherData.index = watcherIndex;
watchers.push(watcherData);
}
return { watchers: watchers, watcherMap: watcherMap };
}
private var deferredBindings:Object = {};
private function deferredBindingsHandler(event:Event):void
{
for (var p:String in deferredBindings)
{
if (_strand[p] != null)
{
var destination:IStrand = _strand[p] as IStrand;
destination.addBead(deferredBindings[p]);
delete deferredBindings[p];
}
}
}
}
}
|
handle more than just models
|
handle more than just models
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
5f0f26beebafb080239f4e9bd210f6607f322fc1
|
build-aux/base.as
|
build-aux/base.as
|
## -*- shell-script -*-
## base.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_pattern_forbid([^_?URBI_])dnl
# m4_define([_m4_divert(M4SH-INIT)], 5)
m4_define([_m4_divert(URBI-INIT)], 10)
m4_defun([_URBI_ABSOLUTE_PREPARE],
[
# is_absolute PATH
# ----------------
is_absolute ()
{
case $[1] in
([[\\/]]* | ?:[[\\/]]*) return 0;;
( *) return 1;;
esac
}
# absolute NAME -> ABS-NAME
# -------------------------
# Return an absolute path to NAME.
absolute ()
{
local res
AS_IF([is_absolute "$[1]"],
[# Absolute paths do not need to be expanded.
res=$[1]],
[local dir=$(pwd)/$(dirname "$[1]")
if test -d "$dir"; then
res=$(cd "$dir" 2>/dev/null && pwd)/$(basename "$[1]")
else
fatal "absolute: not a directory: $dir"
fi])
# On Windows, we must make sure we have a Windows-like UNIX-friendly path (of
# the form C:/cygwin/path/to/somewhere instead of /path/to/somewhere, notice
# the use of forward slashes in the Windows path. Windows *does* understand
# paths with forward slashes).
case $(uname -s) in
(CYGWIN*) res=$(cygpath "$res")
esac
echo "$res"
}
])
m4_defun([_URBI_FIND_PROG_PREPARE],
[# find_file FILE PATH
# -------------------
# Return full path to FILE in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
_AS_PATH_WALK([$[2]],
[AS_IF([test -f $as_dir/$[1]],
[echo "$as_dir/$[1]"; break])])
}
# xfind_file PROG PATH
# --------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_file ()
{
local res
res=$(find_prog "$[1]" "$[2]")
test -n "$res" ||
error OSFILE "cannot find $[1] in $[2]"
echo "$res"
}
# find_prog PROG [PATH=$PATH]
# ---------------------------
# Return full path to PROG in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
local path=$PATH
test -z "$[2]" || path=$[2]
_AS_PATH_WALK([$path],
[AS_IF([AS_TEST_X([$as_dir/$[1]])],
[echo "$as_dir/$[1]"; break])])
}
# xfind_prog PROG [PATH=$PATH]
# ----------------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_prog ()
{
local path=$PATH
test -z "$[2]" || path=$[2]
local res
res=$(find_prog "$[1]" "$path")
test -n "$res" ||
error OSFILE "cannot find executable $[1] in $path"
echo "$res"
}
# require_thing TEST-FLAG ERROR_MESSAGE THING [HINT]
# --------------------------------------------------
require_thing ()
{
local flag=$[1]
local error="$[2]: $[3]"
local thing=$[3]
shift 3
test $flag "$thing" ||
error OSFILE "$error" "$[@]"
}
# require_dir DIR [HINT]
# ----------------------
require_dir ()
{
require_thing -d "no such directory" "$[@]"
}
# require_file FILE [HINT]
# ------------------------
require_file ()
{
require_thing -f "no such file" "$[@]"
}
])
m4_defun([_URBI_STDERR_PREPARE],
[
# stderr LINES
# ------------
stderr ()
{
local i
for i
do
echo >&2 "$as_me: $i"
done
# This line is a nuisance in usual output, yet it makes sense in debug
# output in RST files. But the problem should be solved there
# instead.
#
# echo >&2
}
# verbose LINES
# -------------
verbose ()
{
case $verbose:" $VERBOSE " in
(*true:*|*" $me "*) stderr "$@";;
esac
}
# error EXIT MESSAGES
# -------------------
error ()
{
local exit=$[1]
shift
stderr "$[@]"
ex_exit $exit
}
# fatal MESSAGES
# --------------
fatal ()
{
# To help the user, just make sure that she is not confused between
# the prototypes of fatal and error: the first argument is unlikely
# to be integer.
case $[1] in
(*[[!0-9]]*|'') ;;
(*) stderr "warning: possible confusion between fatal and error" \
"fatal $[*]";;
esac
error 1 "$[@]"
}
# ex_to_string EXIT
# -----------------
# Return a decoding of EXIT status if available, nothing otherwise.
ex_to_string ()
{
case $[1] in
( 0) echo ' (EX_OK: successful termination)';;
( 64) echo ' (EX_USAGE: command line usage error)';;
( 65) echo ' (EX_DATAERR: data format error)';;
( 66) echo ' (EX_NOINPUT: cannot open input)';;
( 67) echo ' (EX_NOUSER: addressee unknown)';;
( 68) echo ' (EX_NOHOST: host name unknown)';;
( 69) echo ' (EX_UNAVAILABLE: service unavailable)';;
( 70) echo ' (EX_SOFTWARE: internal software error)';;
( 71) echo ' (EX_OSERR: system error (e.g., cannot fork))';;
( 72) echo ' (EX_OSFILE: critical OS file missing)';;
( 73) echo ' (EX_CANTCREAT: cannot create (user) output file)';;
( 74) echo ' (EX_IOERR: input/output error)';;
( 75) echo ' (EX_TEMPFAIL: temp failure; user is invited to retry)';;
( 76) echo ' (EX_PROTOCOL: remote error in protocol)';;
( 77) echo ' (EX_NOPERM: permission denied)';;
( 78) echo ' (EX_CONFIG: configuration error)';;
(176) echo ' (EX_SKIP: skip this test with unmet dependencies)';;
(177) echo ' (EX_HARD: hard error that cannot be saved)';;
(242) echo ' (killed by Valgrind)';;
( *) if test 127 -lt $[1]; then
echo " (SIG$(kill -l $[1] || true))"
fi;;
esac
}
# ex_to_int CODE
# --------------
# Decode the CODE and return the corresponding int.
ex_to_int ()
{
case $[1] in
(OK |EX_OK) echo 0;;
(USAGE |EX_USAGE) echo 64;;
(DATAERR |EX_DATAERR) echo 65;;
(NOINPUT |EX_NOINPUT) echo 66;;
(NOUSER |EX_NOUSER) echo 67;;
(NOHOST |EX_NOHOST) echo 68;;
(UNAVAILABLE|EX_UNAVAILABLE) echo 69;;
(SOFTWARE |EX_SOFTWARE) echo 70;;
(OSERR |EX_OSERR) echo 71;;
(OSFILE |EX_OSFILE) echo 72;;
(CANTCREAT |EX_CANTCREAT) echo 73;;
(IOERR |EX_IOERR) echo 74;;
(TEMPFAIL |EX_TEMPFAIL) echo 75;;
(PROTOCOL |EX_PROTOCOL) echo 76;;
(NOPERM |EX_NOPERM) echo 77;;
(CONFIG |EX_CONFIG) echo 78;;
(SKIP |EX_SKIP) echo 176;;
(HARD |EX_HARD) echo 177;;
(*) echo $[1];;
esac
}
ex_exit ()
{
exit $(ex_to_int $[1])
}
])
# URBI_GET_OPTIONS
# ----------------
# Generate get_options().
m4_define([URBI_GET_OPTIONS],
[# Parse command line options
get_options ()
{
while test $[#] -ne 0; do
case $[1] in
(--*=*)
opt=$(echo "$[1]" | sed -e 's/=.*//')
val=$(echo "$[1]" | sed -e ['s/[^=]*=//'])
shift
set dummy "$opt" "$val" ${1+"$[@]"};
shift
;;
esac
case $[1] in
$@
esac
shift
done
}
])
m4_defun([_URBI_PREPARE],
[
# mkcd DIR
# --------
# Remove, create, and cd into DIR.
mkcd ()
{
local dir=$1
rm -rf "$dir"
mkdir -p "$dir"
cd "$dir"
}
# truth TEST-ARGUMENTS...
# -----------------------
# Run "test TEST-ARGUMENTS" and echo true/false depending on the result.
truth ()
{
if test "$[@]"; then
echo true
else
echo false
fi
}
_URBI_ABSOLUTE_PREPARE
_URBI_FIND_PROG_PREPARE
_URBI_STDERR_PREPARE
])
# URBI_PREPARE
# ------------
# Output all the M4sh possible initialization into the initialization
# diversion.
m4_defun([URBI_PREPARE],
[m4_divert_text([M4SH-INIT], [_URBI_PREPARE])dnl
URBI_RST_PREPARE()dnl
URBI_INSTRUMENT_PREPARE()dnl
URBI_CHILDREN_PREPARE()dnl
])
# URBI_INIT
# ---------
# Replaces the AS_INIT invocation.
# Must be defined via "m4_define", not "m4_defun" since it is AS_INIT
# which will set up the diversions used for "m4_defun".
m4_define([URBI_INIT],
[AS_INIT()dnl
URBI_PREPARE()
set -e
case $VERBOSE in
(x) set -x;;
esac
: ${abs_builddir='@abs_builddir@'}
: ${abs_srcdir='@abs_srcdir@'}
: ${abs_top_builddir='@abs_top_builddir@'}
check_dir abs_top_builddir config.status
: ${abs_top_srcdir='@abs_top_srcdir@'}
check_dir abs_top_srcdir configure.ac
: ${builddir='@builddir@'}
: ${srcdir='@srcdir@'}
: ${top_builddir='@top_builddir@'}
check_dir top_builddir config.status
: ${top_srcdir='@top_srcdir@'}
check_dir top_srcdir configure.ac
# Bounce the signals to trap 0, passing the signal as exit value.
for signal in 1 2 13 15; do
trap 'error $((128 + $signal)) \
"received signal $signal ($(kill -l $signal))"' $signal
done
])
|
## -*- shell-script -*-
## base.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_pattern_forbid([^_?URBI_])dnl
# m4_define([_m4_divert(M4SH-INIT)], 5)
m4_define([_m4_divert(URBI-INIT)], 10)
m4_defun([_URBI_ABSOLUTE_PREPARE],
[
# is_absolute PATH
# ----------------
is_absolute ()
{
case $[1] in
([[\\/]]* | ?:[[\\/]]*) return 0;;
( *) return 1;;
esac
}
# absolute NAME -> ABS-NAME
# -------------------------
# Return an absolute path to NAME.
absolute ()
{
local res
AS_IF([is_absolute "$[1]"],
[# Absolute paths do not need to be expanded.
res=$[1]],
[local dir=$(pwd)/$(dirname "$[1]")
if test -d "$dir"; then
res=$(cd "$dir" 2>/dev/null && pwd)/$(basename "$[1]")
else
fatal "absolute: not a directory: $dir"
fi])
# On Windows, we must make sure we have a Windows-like UNIX-friendly path (of
# the form C:/cygwin/path/to/somewhere instead of /path/to/somewhere, notice
# the use of forward slashes in the Windows path. Windows *does* understand
# paths with forward slashes).
case $(uname -s) in
(CYGWIN*) res=$(cygpath "$res")
esac
echo "$res"
}
])
m4_defun([_URBI_FIND_PROG_PREPARE],
[# find_file FILE PATH
# -------------------
# Return full path to FILE in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
_AS_PATH_WALK([$[2]],
[AS_IF([test -f $as_dir/$[1]],
[echo "$as_dir/$[1]"; break])])
}
# xfind_file PROG PATH
# --------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_file ()
{
local res
res=$(find_prog "$[1]" "$[2]")
test -n "$res" ||
error OSFILE "cannot find $[1] in $[2]"
echo "$res"
}
# find_prog PROG [PATH=$PATH]
# ---------------------------
# Return full path to PROG in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
local path=$PATH
test -z "$[2]" || path=$[2]
_AS_PATH_WALK([$path],
[AS_IF([AS_TEST_X([$as_dir/$[1]])],
[echo "$as_dir/$[1]"; break])])
}
# xfind_prog PROG [PATH=$PATH]
# ----------------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_prog ()
{
local path=$PATH
test -z "$[2]" || path=$[2]
local res
res=$(find_prog "$[1]" "$path")
test -n "$res" ||
error OSFILE "cannot find executable $[1] in $path"
echo "$res"
}
# require_thing TEST-FLAG ERROR_MESSAGE THING [HINT]
# --------------------------------------------------
require_thing ()
{
local flag=$[1]
local error="$[2]: $[3]"
local thing=$[3]
shift 3
test $flag "$thing" ||
error OSFILE "$error" "$[@]"
}
# require_dir DIR [HINT]
# ----------------------
require_dir ()
{
require_thing -d "no such directory" "$[@]"
}
# require_file FILE [HINT]
# ------------------------
require_file ()
{
require_thing -f "no such file" "$[@]"
}
])
m4_defun([_URBI_STDERR_PREPARE],
[
# stderr LINES
# ------------
stderr ()
{
local i
for i
do
echo >&2 "$as_me: $i"
done
# This line is a nuisance in usual output, yet it makes sense in debug
# output in RST files. But the problem should be solved there
# instead.
#
# echo >&2
}
# verbose LINES
# -------------
verbose ()
{
case $verbose:" $VERBOSE " in
(*true:*|*" $me "*) stderr "$@";;
esac
}
# error EXIT MESSAGES
# -------------------
error ()
{
local exit=$[1]
shift
stderr "$[@]"
ex_exit $exit
}
# fatal MESSAGES
# --------------
fatal ()
{
# To help the user, just make sure that she is not confused between
# the prototypes of fatal and error: the first argument is unlikely
# to be integer.
case $[1] in
(*[[!0-9]]*|'') ;;
(*) stderr "warning: possible confusion between fatal and error" \
"fatal $[*]";;
esac
error 1 "$[@]"
}
# ex_to_string EXIT
# -----------------
# Return a decoding of EXIT status if available, nothing otherwise.
ex_to_string ()
{
case $[1] in
( 0) echo ' (EX_OK: successful termination)';;
( 64) echo ' (EX_USAGE: command line usage error)';;
( 65) echo ' (EX_DATAERR: data format error)';;
( 66) echo ' (EX_NOINPUT: cannot open input)';;
( 67) echo ' (EX_NOUSER: addressee unknown)';;
( 68) echo ' (EX_NOHOST: host name unknown)';;
( 69) echo ' (EX_UNAVAILABLE: service unavailable)';;
( 70) echo ' (EX_SOFTWARE: internal software error)';;
( 71) echo ' (EX_OSERR: system error (e.g., cannot fork))';;
( 72) echo ' (EX_OSFILE: critical OS file missing)';;
( 73) echo ' (EX_CANTCREAT: cannot create (user) output file)';;
( 74) echo ' (EX_IOERR: input/output error)';;
( 75) echo ' (EX_TEMPFAIL: temp failure; user is invited to retry)';;
( 76) echo ' (EX_PROTOCOL: remote error in protocol)';;
( 77) echo ' (EX_NOPERM: permission denied)';;
( 78) echo ' (EX_CONFIG: configuration error)';;
(176) echo ' (EX_SKIP: skip this test with unmet dependencies)';;
(177) echo ' (EX_HARD: hard error that cannot be saved)';;
(242) echo ' (killed by Valgrind)';;
( *) if test 127 -lt $[1]; then
echo " (SIG$(kill -l $[1] || true))"
fi;;
esac
}
# ex_to_int CODE
# --------------
# Decode the CODE and return the corresponding int.
ex_to_int ()
{
case $[1] in
(OK |EX_OK) echo 0;;
(USAGE |EX_USAGE) echo 64;;
(DATAERR |EX_DATAERR) echo 65;;
(NOINPUT |EX_NOINPUT) echo 66;;
(NOUSER |EX_NOUSER) echo 67;;
(NOHOST |EX_NOHOST) echo 68;;
(UNAVAILABLE|EX_UNAVAILABLE) echo 69;;
(SOFTWARE |EX_SOFTWARE) echo 70;;
(OSERR |EX_OSERR) echo 71;;
(OSFILE |EX_OSFILE) echo 72;;
(CANTCREAT |EX_CANTCREAT) echo 73;;
(IOERR |EX_IOERR) echo 74;;
(TEMPFAIL |EX_TEMPFAIL) echo 75;;
(PROTOCOL |EX_PROTOCOL) echo 76;;
(NOPERM |EX_NOPERM) echo 77;;
(CONFIG |EX_CONFIG) echo 78;;
(SKIP |EX_SKIP) echo 176;;
(HARD |EX_HARD) echo 177;;
(*) echo $[1];;
esac
}
ex_exit ()
{
exit $(ex_to_int $[1])
}
])
# URBI_GET_OPTIONS
# ----------------
# Generate get_options().
m4_define([URBI_GET_OPTIONS],
[# Parse command line options
get_options ()
{
while test $[#] -ne 0; do
case $[1] in
(--*=*)
opt=$(echo "$[1]" | sed -e 's/=.*//')
val=$(echo "$[1]" | sed -e ['s/[^=]*=//'])
shift
set dummy "$opt" "$val" ${1+"$[@]"};
shift
;;
esac
case $[1] in
$@
esac
shift
done
}
])
m4_defun([_URBI_PREPARE],
[
# mkcd DIR
# --------
# Remove, create, and cd into DIR.
mkcd ()
{
local dir=$[1]
rm -rf "$dir"
mkdir -p "$dir"
cd "$dir"
}
# truth TEST-ARGUMENTS...
# -----------------------
# Run "test TEST-ARGUMENTS" and echo true/false depending on the result.
truth ()
{
if test "$[@]"; then
echo true
else
echo false
fi
}
_URBI_ABSOLUTE_PREPARE
_URBI_FIND_PROG_PREPARE
_URBI_STDERR_PREPARE
])
# URBI_PREPARE
# ------------
# Output all the M4sh possible initialization into the initialization
# diversion.
m4_defun([URBI_PREPARE],
[m4_divert_text([M4SH-INIT], [_URBI_PREPARE])dnl
URBI_RST_PREPARE()dnl
URBI_INSTRUMENT_PREPARE()dnl
URBI_CHILDREN_PREPARE()dnl
])
# URBI_INIT
# ---------
# Replaces the AS_INIT invocation.
# Must be defined via "m4_define", not "m4_defun" since it is AS_INIT
# which will set up the diversions used for "m4_defun".
m4_define([URBI_INIT],
[AS_INIT()dnl
URBI_PREPARE()
set -e
case $VERBOSE in
(x) set -x;;
esac
: ${abs_builddir='@abs_builddir@'}
: ${abs_srcdir='@abs_srcdir@'}
: ${abs_top_builddir='@abs_top_builddir@'}
check_dir abs_top_builddir config.status
: ${abs_top_srcdir='@abs_top_srcdir@'}
check_dir abs_top_srcdir configure.ac
: ${builddir='@builddir@'}
: ${srcdir='@srcdir@'}
: ${top_builddir='@top_builddir@'}
check_dir top_builddir config.status
: ${top_srcdir='@top_srcdir@'}
check_dir top_srcdir configure.ac
# Bounce the signals to trap 0, passing the signal as exit value.
for signal in 1 2 13 15; do
trap 'error $((128 + $signal)) \
"received signal $signal ($(kill -l $signal))"' $signal
done
])
|
Fix m4 quotation.
|
Fix m4 quotation.
Blush...
* build-aux/base.as: here.
|
ActionScript
|
bsd-3-clause
|
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
|
c95a24c2b845a1d14c8852b5e45d2ffbc3d4b7d4
|
src/org/mangui/HLS/muxing/FLV.as
|
src/org/mangui/HLS/muxing/FLV.as
|
package org.mangui.HLS.muxing {
import flash.utils.ByteArray;
/** Helpers for the FLV file format. **/
public class FLV {
/** Return an EOS Video tag (16 bytes). **/
public static function getEosTag(stamp : Number) : ByteArray {
var tag : ByteArray = FLV.getTagHeader(false, 5, stamp);
// AVC Keyframe.
tag.writeByte(0x17);
// Sequence end, composition time
tag.writeUnsignedInt(0x02000000);
return tag;
};
/** Get the FLV file header. **/
public static function getHeader() : ByteArray {
var flv : ByteArray = new ByteArray();
flv.length = 13;
// "F" + "L" + "V".
flv.writeByte(0x46);
flv.writeByte(0x4C);
flv.writeByte(0x56);
// File version (1)
flv.writeByte(1);
// Audio + Video tags.
flv.writeByte(1);
// Length of the header.
flv.writeUnsignedInt(9);
// PreviousTagSize0
flv.writeUnsignedInt(0);
return flv;
};
/** Get an FLV Tag header (11 bytes). **/
public static function getTagHeader(audio : Boolean, length : Number, stamp : Number) : ByteArray {
var tag : ByteArray = new ByteArray();
tag.length = 11;
// Audio (8) or Video (9) tag
if (audio) {
tag.writeByte(8);
} else {
tag.writeByte(9);
}
// Size of the tag in bytes after StreamID.
tag.writeByte(length >> 16);
tag.writeByte(length >> 8);
tag.writeByte(length);
// Timestamp (lower 24 plus upper 8)
tag.writeByte(stamp >> 16);
tag.writeByte(stamp >> 8);
tag.writeByte(stamp);
tag.writeByte(stamp >> 24);
// StreamID (3 empty bytes)
tag.writeByte(0);
tag.writeByte(0);
tag.writeByte(0);
// All done
return tag;
};
}
}
|
package org.mangui.HLS.muxing {
import flash.utils.ByteArray;
/** Helpers for the FLV file format. **/
public class FLV {
/** Get the FLV file header. **/
public static function getHeader() : ByteArray {
var flv : ByteArray = new ByteArray();
flv.length = 13;
// "F" + "L" + "V".
flv.writeByte(0x46);
flv.writeByte(0x4C);
flv.writeByte(0x56);
// File version (1)
flv.writeByte(1);
// Audio + Video tags.
flv.writeByte(1);
// Length of the header.
flv.writeUnsignedInt(9);
// PreviousTagSize0
flv.writeUnsignedInt(0);
return flv;
};
/** Get an FLV Tag header (11 bytes). **/
public static function getTagHeader(audio : Boolean, length : Number, stamp : Number) : ByteArray {
var tag : ByteArray = new ByteArray();
tag.length = 11;
// Audio (8) or Video (9) tag
if (audio) {
tag.writeByte(8);
} else {
tag.writeByte(9);
}
// Size of the tag in bytes after StreamID.
tag.writeByte(length >> 16);
tag.writeByte(length >> 8);
tag.writeByte(length);
// Timestamp (lower 24 plus upper 8)
tag.writeByte(stamp >> 16);
tag.writeByte(stamp >> 8);
tag.writeByte(stamp);
tag.writeByte(stamp >> 24);
// StreamID (3 empty bytes)
tag.writeByte(0);
tag.writeByte(0);
tag.writeByte(0);
// All done
return tag;
};
}
}
|
remove unused method
|
remove unused method
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
69ce4b2ea108e4ef7036d7810e6a7205546d9b14
|
dolly-framework/src/test/resources/dolly/data/PropertyLevelCopyableCloneableClass.as
|
dolly-framework/src/test/resources/dolly/data/PropertyLevelCopyableCloneableClass.as
|
package dolly.data {
public class PropertyLevelCopyableCloneableClass {
[Copyable]
[Cloneable]
public static var staticProperty1:String = "Value of first-level static property.";
[Copyable]
[Cloneable]
private var _writableField1:String = "Value of first-level writable field.";
[Cloneable]
public var property1:String = "Value of first-level public property.";
public function PropertyLevelCopyableCloneableClass() {
}
[Copyable]
[Cloneable]
public function get writableField1():String {
return _writableField1;
}
public function set writableField1(value:String):void {
_writableField1 = value;
}
[Copyable]
[Cloneable]
public function get readOnlyField1():String {
return "Value of first-level read-only field.";
}
}
}
|
package dolly.data {
public class PropertyLevelCopyableCloneableClass {
[Copyable]
[Cloneable]
public static var staticProperty1:String = "Value of first-level static property.";
[Copyable]
[Cloneable]
private var _writableField1:String = "Value of first-level writable field.";
[Cloneable]
public var property1:String = "Value of first-level public property 1.";
public var property2:String = "Value of first-level public property 2.";
public function PropertyLevelCopyableCloneableClass() {
}
[Copyable]
[Cloneable]
public function get writableField1():String {
return _writableField1;
}
public function set writableField1(value:String):void {
_writableField1 = value;
}
[Copyable]
[Cloneable]
public function get readOnlyField1():String {
return "Value of first-level read-only field.";
}
}
}
|
Add new field "property2" to class PropertyLevelCopyableCloneableClass.
|
Add new field "property2" to class PropertyLevelCopyableCloneableClass.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
9c11585c563ec388a4910e1c2eddf0d5b7a33eca
|
src/aerys/minko/scene/controller/TransformController.as
|
src/aerys/minko/scene/controller/TransformController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>
private var _parentId : Vector.<int>
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
{
var rootTransform : Matrix4x4 = _transforms[0];
var isDirty : Boolean = rootTransform._hasChanged;
if (isDirty)
{
_localToWorldTransforms[0].copyFrom(rootTransform);
rootTransform._hasChanged = false;
}
updateLocalToWorld();
}
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var isDirty : Boolean = localToWorld._hasChanged;
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged;
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function updateLocalToWorldAncestorsAndSelf(nodeId : int) : void
{
var dirtyRoot : int = nodeId;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged)
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_localToWorldTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_localToWorldTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
updateLocalToWorldAncestorsAndSelf(nodeId);
return _localToWorldTransforms[nodeId];
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>
private var _parentId : Vector.<int>
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
{
var rootTransform : Matrix4x4 = _transforms[0];
var isDirty : Boolean = rootTransform._hasChanged;
if (isDirty)
{
_localToWorldTransforms[0].copyFrom(rootTransform);
rootTransform._hasChanged = false;
}
updateLocalToWorld();
}
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var isDirty : Boolean = localToWorld._hasChanged;
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged;
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function updateAncestorsAndSelfLocalToWorld(nodeId : int) : void
{
var dirtyRoot : int = nodeId;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged)
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_localToWorldTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_localToWorldTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
return _localToWorldTransforms[nodeId];
}
}
}
|
fix typo
|
fix typo
|
ActionScript
|
mit
|
aerys/minko-as3
|
a64663f104c0e0dd322b9fecc1c746096ab95dc5
|
plugins/bitrateDetectionPlugin/src/com/kaltura/kdpfl/plugin/component/BitrateDetectionMediator.as
|
plugins/bitrateDetectionPlugin/src/com/kaltura/kdpfl/plugin/component/BitrateDetectionMediator.as
|
package com.kaltura.kdpfl.plugin.component
{
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.SequenceProxy;
import com.kaltura.kdpfl.model.type.EnableType;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.types.KalturaMediaType;
import com.kaltura.vo.KalturaMediaEntry;
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.TimerEvent;
import flash.external.ExternalInterface;
import flash.net.SharedObject;
import flash.net.URLRequest;
import flash.utils.Timer;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class BitrateDetectionMediator extends Mediator
{
public static var NAME:String = "bitrateDetectionMediator";
/**
* Flag indicating autoPlay flashvar was true
*/
private var _wasAutoPlay:Boolean = false;
/**
* Flag indicating singleAutoPlay was true
*/
private var _wasSingleAutoPlay:Boolean = false;
/**
* The url loader
*/
private var _loader:Loader;
/**
* average download speed
*/
private var _avgSpeed:Number = 0;
/**
* counter for progress events, will be used to calculate average speed
*/
private var _progressCount:int;
/**
* timer for the download process
*/
private var _downloadTimer:Timer;
/**
* startTime of the download process
*/
private var _startTime:Number;
/**
* Indicating if player has already played
*/
private var _playedPlayed:Boolean = false;
private var _configProxy:ConfigProxy;
private var _prevTime:Number;
private var _prevBytesLoaded:int;
private var _forceBitrate:int;
public function BitrateDetectionMediator(viewComponentObject:Object = null , forceBitrate:int = 0)
{
_forceBitrate = forceBitrate;
super(NAME, viewComponentObject);
}
override public function listNotificationInterests():Array
{
return [
NotificationType.DO_SWITCH,
NotificationType.KDP_EMPTY,
NotificationType.KDP_READY,
NotificationType.PLAYER_PLAYED,
NotificationType.MEDIA_READY
];
}
private var _bandwidth:Number = 0;
private var _bandwidthByUser:Number = 0;
override public function handleNotification(notification:INotification):void
{
//check bitrate only before player played
/* if (_playedPlayed)
{
return;
}*/
switch (notification.getName())
{
//in case the user switched the flavor manually
case NotificationType.DO_SWITCH:
_bandwidthByUser = int(notification.getBody())
break;
case NotificationType.MEDIA_READY:
if(_bandwidthByUser)
{
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidthByUser});
return;
}
if(_bandwidth)
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidth});
break;
case NotificationType.KDP_EMPTY:
case NotificationType.KDP_READY:
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
if (!mediaProxy.vo.entry ||
((mediaProxy.vo.entry is KalturaMediaEntry) && (int(mediaProxy.vo.entry.mediaType)==KalturaMediaType.IMAGE)))
break;
trace("bitrate detection:", notification.getName());
_configProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
if ((viewComponent as bitrateDetectionPluginCode).useFlavorCookie)
{
var flavorCookie : SharedObject;
try
{
//Check to see if we have a cookie
flavorCookie = SharedObject.getLocal("kaltura");
}
catch (e: Error)
{
//if not just start download
trace ("no permissions to access partner's file system");
startDownload();
return;
}
if (flavorCookie && flavorCookie.data)
{
//If we are in Auto Switch or the first time we run it - do the download test
if(!flavorCookie.data.preferedFlavorBR || (flavorCookie.data.preferedFlavorBR == -1))
{
startDownload();
}
}
}
//disable bitrate cookie--> start detection
else
{
startDownload();
}
break;
case NotificationType.PLAYER_PLAYED:
if(_bandwidth)
return;
_playedPlayed = true;
break;
}
}
/**
* Start a download process to find the preferred bitrate
*
*/
public function startDownload() : void
{
trace ("bitrate detection: start download");
if (!(viewComponent as bitrateDetectionPluginCode).downloadUrl)
return;
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
//disable autoPlay - will change it back once the bitrate detection will finish
if (_configProxy.vo.flashvars.autoPlay == "true")
{
trace ("bitrate detection: was auto play");
_configProxy.vo.flashvars.autoPlay = "false";
_wasAutoPlay = true;
}
if (mediaProxy.vo.singleAutoPlay)
{
mediaProxy.vo.singleAutoPlay = false;
_wasSingleAutoPlay = true;
}
_startTime = ( new Date( ) ).getTime( );
_progressCount = 0;
_prevTime = _startTime;
_prevBytesLoaded = 0;
_loader = new Loader( );
_loader.contentLoaderInfo.addEventListener( Event.COMPLETE, downloadComplete );
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
_loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
_downloadTimer = new Timer ((viewComponent as bitrateDetectionPluginCode).downloadTimeoutMS, 1);
_downloadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: false, enableType: EnableType.FULL});
sendNotification( NotificationType.SWITCHING_CHANGE_STARTED, {newIndex: -2, newBitrate: null});
_loader.load( new URLRequest( (viewComponent as bitrateDetectionPluginCode).downloadUrl + "?" + ( Math.random( ) * 100000 )) );
_downloadTimer.start();
}
/**
* on download progress- calculate average speed
* @param event
*
*/
private function onProgress (event:ProgressEvent):void
{
var curTime:Number = ( new Date( ) ).getTime( );
_progressCount++;
if (event.bytesLoaded!=0)
{
var totalTime:Number =( curTime - _startTime ) / 1000;
var totalKB:Number = event.bytesLoaded / 1024;
_avgSpeed = totalKB / totalTime;
}
_prevTime = curTime;
_prevBytesLoaded = event.bytesLoaded;
}
/**
* download complete handler - set the preferred bitrate, enable GUI
*
*/
private function downloadComplete( e:Event = null):void
{
_downloadTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
_loader.contentLoaderInfo.removeEventListener( ProgressEvent.PROGRESS, onProgress );
var bitrateVal:int = _avgSpeed * 8;
trace("*** preferred bitrate for bitrate detection plugin:", bitrateVal);
//for debugging - force a bitrate value to override the calculated one
if(_forceBitrate > 0)
{
bitrateVal = _forceBitrate;
}
//for testing - expose the # via JS
try
{
ExternalInterface.call('bitrateValue' , bitrateVal);
}
catch(error:Error)
{
}
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: bitrateVal});
_bandwidth = bitrateVal;
//write to cookie
if (_configProxy.vo.flashvars.allowCookies=="true")
{
var flavorCookie : SharedObject;
try
{
flavorCookie = SharedObject.getLocal("kaltura");
}
catch (e : Error)
{
trace("No access to user's file system");
}
if (flavorCookie && flavorCookie.data)
{
flavorCookie.data.preferedFlavorBR = bitrateVal;
flavorCookie.flush();
}
}
finishDownloadProcess();
}
/**
* default timer time has passed, stop listening to progress event and continue the flow
* @param event
*
*/
private function onTimerComplete (event:TimerEvent):void {
downloadComplete();
}
/**
* I/O error getting the sample file, release the UI
* @param event
*
*/
private function ioErrorHandler(event:IOErrorEvent) : void
{
//Bypass: ignore #2124 error (loaded file is an unknown type)
if (!event.text || event.text.indexOf("Error #2124")==-1)
{
trace ("bitrate detection i/o error:", event.text);
finishDownloadProcess();
}
}
/**
* enable back the GUI.
* call Do_Play if we were in auto play and set back relevant flashvars
*
*/
private function finishDownloadProcess():void {
//if we changed variables, set them back
if (_wasAutoPlay || _wasSingleAutoPlay) {
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
var sequenceProxy:SequenceProxy = facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy;
if (_wasAutoPlay)
{
_configProxy.vo.flashvars.autoPlay = "true";
}
else
{
mediaProxy.vo.singleAutoPlay = true;
}
//play if we should have played
if (!_playedPlayed && !mediaProxy.vo.isMediaDisabled && !sequenceProxy.vo.isInSequence)
{
sendNotification(NotificationType.DO_PLAY);
}
}
sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: true, enableType: EnableType.FULL});
}
}
}
|
package com.kaltura.kdpfl.plugin.component
{
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.SequenceProxy;
import com.kaltura.kdpfl.model.type.EnableType;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.types.KalturaMediaType;
import com.kaltura.vo.KalturaMediaEntry;
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.TimerEvent;
import flash.external.ExternalInterface;
import flash.net.SharedObject;
import flash.net.URLRequest;
import flash.utils.Timer;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class BitrateDetectionMediator extends Mediator
{
public static var NAME:String = "bitrateDetectionMediator";
/**
* Flag indicating autoPlay flashvar was true
*/
private var _wasAutoPlay:Boolean = false;
/**
* Flag indicating singleAutoPlay was true
*/
private var _wasSingleAutoPlay:Boolean = false;
/**
* The url loader
*/
private var _loader:Loader;
/**
* average download speed
*/
private var _avgSpeed:Number = 0;
/**
* counter for progress events, will be used to calculate average speed
*/
private var _progressCount:int;
/**
* timer for the download process
*/
private var _downloadTimer:Timer;
/**
* startTime of the download process
*/
private var _startTime:Number;
/**
* Indicating if player has already played
*/
private var _playedPlayed:Boolean = false;
private var _configProxy:ConfigProxy;
private var _prevTime:Number;
private var _prevBytesLoaded:int;
private var _forceBitrate:int;
public function BitrateDetectionMediator(viewComponentObject:Object = null , forceBitrate:int = 0)
{
_forceBitrate = forceBitrate;
super(NAME, viewComponentObject);
}
override public function listNotificationInterests():Array
{
return [
NotificationType.DO_SWITCH,
NotificationType.KDP_EMPTY,
NotificationType.KDP_READY,
NotificationType.PLAYER_PLAYED,
NotificationType.MEDIA_READY
];
}
private var _bandwidth:Number = 0;
private var _bandwidthByUser:Number = 0;
override public function handleNotification(notification:INotification):void
{
//check bitrate only before player played
/* if (_playedPlayed)
{
return;
}*/
switch (notification.getName())
{
//in case the user switched the flavor manually
case NotificationType.DO_SWITCH:
_bandwidthByUser = int(notification.getBody())
break;
case NotificationType.MEDIA_READY:
if(_bandwidthByUser)
{
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidthByUser});
return;
}
if(_bandwidth)
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: _bandwidth});
break;
case NotificationType.KDP_EMPTY:
case NotificationType.KDP_READY:
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
if (!mediaProxy.vo.entry ||
((mediaProxy.vo.entry is KalturaMediaEntry) && (int(mediaProxy.vo.entry.mediaType)==KalturaMediaType.IMAGE)))
break;
trace("bitrate detection:", notification.getName());
_configProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
if ((viewComponent as bitrateDetectionPluginCode).useFlavorCookie)
{
var flavorCookie : SharedObject;
try
{
//Check to see if we have a cookie
flavorCookie = SharedObject.getLocal("kaltura");
}
catch (e: Error)
{
//if not just start download
trace ("no permissions to access partner's file system");
startDownload();
return;
}
if (flavorCookie && flavorCookie.data)
{
//If we are in Auto Switch or the first time we run it - do the download test
if(!flavorCookie.data.preferedFlavorBR || (flavorCookie.data.preferedFlavorBR == -1))
{
startDownload();
}
}
}
//disable bitrate cookie--> start detection
else
{
startDownload();
}
break;
case NotificationType.PLAYER_PLAYED:
if(_bandwidth)
return;
_playedPlayed = true;
break;
}
}
/**
* Start a download process to find the preferred bitrate
*
*/
public function startDownload() : void
{
trace ("bitrate detection: start download");
if (!(viewComponent as bitrateDetectionPluginCode).downloadUrl)
return;
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
//disable autoPlay - will change it back once the bitrate detection will finish
if (_configProxy.vo.flashvars.autoPlay == "true")
{
trace ("bitrate detection: was auto play");
_configProxy.vo.flashvars.autoPlay = "false";
_wasAutoPlay = true;
}
if (mediaProxy.vo.singleAutoPlay)
{
mediaProxy.vo.singleAutoPlay = false;
_wasSingleAutoPlay = true;
}
_startTime = ( new Date( ) ).getTime( );
_progressCount = 0;
_prevTime = _startTime;
_prevBytesLoaded = 0;
_loader = new Loader( );
_loader.contentLoaderInfo.addEventListener( Event.COMPLETE, downloadComplete );
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
_loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
_downloadTimer = new Timer ((viewComponent as bitrateDetectionPluginCode).downloadTimeoutMS, 1);
_downloadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: false, enableType: EnableType.FULL});
sendNotification( NotificationType.SWITCHING_CHANGE_STARTED, {newIndex: -2, newBitrate: null});
_loader.load( new URLRequest( (viewComponent as bitrateDetectionPluginCode).downloadUrl + "?" + ( Math.random( ) * 100000 )) );
_downloadTimer.start();
}
/**
* on download progress- calculate average speed
* @param event
*
*/
private function onProgress (event:ProgressEvent):void
{
var curTime:Number = ( new Date( ) ).getTime( );
_progressCount++;
if (event.bytesLoaded!=0)
{
var totalTime:Number =( curTime - _startTime ) / 1000;
var totalKB:Number = event.bytesLoaded / 1024;
_avgSpeed = totalKB / totalTime;
}
_prevTime = curTime;
_prevBytesLoaded = event.bytesLoaded;
}
/**
* download complete handler - set the preferred bitrate, enable GUI
*
*/
private function downloadComplete( e:Event = null):void
{
_downloadTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
_loader.contentLoaderInfo.removeEventListener( ProgressEvent.PROGRESS, onProgress );
var bitrateVal:int = _avgSpeed * 8;
trace("*** preferred bitrate for bitrate detection plugin:", bitrateVal);
//for debugging - force a bitrate value to override the calculated one
if(_forceBitrate > 0)
{
bitrateVal = _forceBitrate;
}
sendNotification(NotificationType.CHANGE_PREFERRED_BITRATE, {bitrate: bitrateVal});
_bandwidth = bitrateVal;
//write to cookie
if (_configProxy.vo.flashvars.allowCookies=="true")
{
var flavorCookie : SharedObject;
try
{
flavorCookie = SharedObject.getLocal("kaltura");
}
catch (e : Error)
{
trace("No access to user's file system");
}
if (flavorCookie && flavorCookie.data)
{
flavorCookie.data.preferedFlavorBR = bitrateVal;
flavorCookie.flush();
}
}
finishDownloadProcess();
}
/**
* default timer time has passed, stop listening to progress event and continue the flow
* @param event
*
*/
private function onTimerComplete (event:TimerEvent):void {
downloadComplete();
}
/**
* I/O error getting the sample file, release the UI
* @param event
*
*/
private function ioErrorHandler(event:IOErrorEvent) : void
{
//Bypass: ignore #2124 error (loaded file is an unknown type)
if (!event.text || event.text.indexOf("Error #2124")==-1)
{
trace ("bitrate detection i/o error:", event.text);
finishDownloadProcess();
}
}
/**
* enable back the GUI.
* call Do_Play if we were in auto play and set back relevant flashvars
*
*/
private function finishDownloadProcess():void {
//if we changed variables, set them back
if (_wasAutoPlay || _wasSingleAutoPlay) {
var mediaProxy:MediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
var sequenceProxy:SequenceProxy = facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy;
if (_wasAutoPlay)
{
_configProxy.vo.flashvars.autoPlay = "true";
}
else
{
mediaProxy.vo.singleAutoPlay = true;
}
//play if we should have played
if (!_playedPlayed && !mediaProxy.vo.isMediaDisabled && !sequenceProxy.vo.isInSequence)
{
sendNotification(NotificationType.DO_PLAY);
}
}
sendNotification(NotificationType.ENABLE_GUI, {guiEnabled: true, enableType: EnableType.FULL});
}
}
}
|
remove debugging code
|
qnd: remove debugging code
git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@87286 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp
|
24d052e976acc20b7822c54e8740ea61680139a3
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/charts/beads/ChartItemRendererFactory.as
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/charts/beads/ChartItemRendererFactory.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.charts.beads
{
import org.apache.flex.charts.core.IChart;
import org.apache.flex.charts.core.IChartItemRenderer;
import org.apache.flex.charts.core.IChartSeries;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IDataProviderItemRendererMapper;
import org.apache.flex.core.IItemRendererClassFactory;
import org.apache.flex.core.IItemRendererParent;
import org.apache.flex.core.ISelectionModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.html.beads.IListView;
/**
* The ChartItemRendererFactory class implements IDataProviderItemRendererMapper
* and creats the itemRenderers for each series in a chart. The itemRenderer class
* is identified on each series either through a property or through a CSS style.
* Once all of the itemRenderers are created, an itemsCreated event is dispatched
* causing the layout associated with the chart to size and position the items.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ChartItemRendererFactory implements IBead, IDataProviderItemRendererMapper
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ChartItemRendererFactory()
{
}
private var selectionModel:ISelectionModel;
protected var dataGroup:IItemRendererParent;
private var _seriesRenderers:Array;
/**
* The array of renderers created for each series.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get seriesRenderers():Array
{
return _seriesRenderers;
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
selectionModel = value.getBeadByType(ISelectionModel) as ISelectionModel;
var listView:IListView = value.getBeadByType(IListView) as IListView;
dataGroup = listView.dataGroup;
// selectionModel.addEventListener("dataProviderChanged", dataProviderChangeHandler);
var dp:Array = selectionModel.dataProvider as Array;
if (!dp)
return;
_seriesRenderers = new Array();
dataGroup.removeAllElements();
var series:Array = IChart(_strand).series;
for( var j:int=0; j < dp.length; j++)
{
var renderers:Array = new Array();
for( var i:int=0; i < series.length; i++)
{
var s:IChartSeries = series[i] as IChartSeries;
var k:IChartItemRenderer = s.itemRenderer.newInstance() as IChartItemRenderer;
k.itemRendererParent = dataGroup;
k.xField = s.xField;
k.yField = s.yField;
k.fillColor = s.fillColor;
k.data = dp[j];
k.index = j;
renderers.push(k);
dataGroup.addElement(k);
}
_seriesRenderers.push(renderers);
}
IEventDispatcher(_strand).dispatchEvent(new Event("itemsCreated"));
}
/**
* @private
*/
public function get itemRendererFactory():IItemRendererClassFactory
{
return null;
}
/**
* @private
*/
public function set itemRendererFactory(value:IItemRendererClassFactory):void
{
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.charts.beads
{
import org.apache.flex.charts.core.IChart;
import org.apache.flex.charts.core.IChartItemRenderer;
import org.apache.flex.charts.core.IChartSeries;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IDataProviderItemRendererMapper;
import org.apache.flex.core.IItemRendererClassFactory;
import org.apache.flex.core.IItemRendererParent;
import org.apache.flex.core.ISelectionModel;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.html.beads.IListView;
/**
* The ChartItemRendererFactory class implements IDataProviderItemRendererMapper
* and creats the itemRenderers for each series in a chart. The itemRenderer class
* is identified on each series either through a property or through a CSS style.
* Once all of the itemRenderers are created, an itemsCreated event is dispatched
* causing the layout associated with the chart to size and position the items.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ChartItemRendererFactory implements IBead, IDataProviderItemRendererMapper
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ChartItemRendererFactory()
{
}
private var selectionModel:ISelectionModel;
protected var dataGroup:IItemRendererParent;
private var _seriesRenderers:Array;
/**
* The array of renderers created for each series.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get seriesRenderers():Array
{
return _seriesRenderers;
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
selectionModel = value.getBeadByType(ISelectionModel) as ISelectionModel;
var listView:IListView = value.getBeadByType(IListView) as IListView;
dataGroup = listView.dataGroup;
// selectionModel.addEventListener("dataProviderChanged", dataProviderChangeHandler);
var dp:Array = selectionModel.dataProvider as Array;
if (!dp)
return;
_seriesRenderers = new Array();
dataGroup.removeAllElements();
var series:Array = IChart(_strand).series;
for( var j:int=0; j < dp.length; j++)
{
var renderers:Array = new Array();
for( var i:int=0; i < series.length; i++)
{
var s:IChartSeries = series[i] as IChartSeries;
var k:IChartItemRenderer = s.itemRenderer.newInstance() as IChartItemRenderer;
k.itemRendererParent = dataGroup;
k.xField = s.xField;
k.yField = s.yField;
//k.fillColor = s.fillColor;
k.data = dp[j];
k.index = j;
renderers.push(k);
dataGroup.addElement(k);
}
_seriesRenderers.push(renderers);
}
IEventDispatcher(_strand).dispatchEvent(new Event("itemsCreated"));
}
/**
* @private
*/
public function get itemRendererFactory():IItemRendererClassFactory
{
return null;
}
/**
* @private
*/
public function set itemRendererFactory(value:IItemRendererClassFactory):void
{
}
}
}
|
Remove reference to IChartItemRenderer.fillColor as that property does not exist. This fixes the FlexJSJX build.
|
Remove reference to IChartItemRenderer.fillColor as that property does not exist. This fixes the FlexJSJX build.
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
eec72dec0c3a185f987a1c2c96b81d772aef9fd9
|
src/com/mangui/HLS/muxing/TS.as
|
src/com/mangui/HLS/muxing/TS.as
|
package com.mangui.HLS.muxing {
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.utils.Log;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.ByteArray;
import flash.utils.Timer;
/** Representation of an MPEG transport stream. **/
public class TS extends EventDispatcher {
/** TS Sync byte. **/
public static const SYNCBYTE:uint = 0x47;
/** TS Packet size in byte. **/
public static const PACKETSIZE:uint = 188;
/** Identifier for read complete event **/
public static const READCOMPLETE:String = "readComplete"
private static const COUNT:uint = 5000;
/** Packet ID of the AAC audio stream. **/
private var _aacId:Number = -1;
/** List with audio frames. **/
public var audioTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AAC. **/
private var _audioPES:Vector.<PES> = new Vector.<PES>();
/** Packet ID of the video stream. **/
private var _avcId:Number = -1;
/** PES packet that contains the first keyframe. **/
private var _firstKey:Number = -1;
/** Packet ID of the MP3 audio stream. **/
private var _mp3Id:Number = -1;
/** Packet ID of the PAT (is always 0). **/
private var _patId:Number = 0;
/** Packet ID of the Program Map Table. **/
private var _pmtId:Number = -1;
/** List with video frames. **/
/** Packet ID of the SDT (is always 17). **/
private var _sdtId:Number = 17;
public var videoTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AVC. **/
private var _videoPES:Vector.<PES> = new Vector.<PES>();
/** Timer for reading packets **/
public var _timer:Timer;
/** Byte data to be read **/
private var _data:ByteArray;
/** Transmux the M2TS file into an FLV file. **/
public function TS(data:ByteArray) {
// Extract the elementary streams.
_data = data;
_timer = new Timer(0,0);
_timer.addEventListener(TimerEvent.TIMER, _readData);
};
/** Read a small chunk of packets each time to avoid blocking **/
private function _readData(e:Event):void {
var i:uint = 0;
while(_data.bytesAvailable && i < COUNT) {
_readPacket();
i++;
}
if (!_data.bytesAvailable) {
_timer.stop();
_extractFrames();
}
}
/** start the timer in order to start reading data **/
public function startReading():void {;
_timer.start();
}
/** setup the video and audio tag vectors from the read data **/
private function _extractFrames():void {
if (_videoPES.length == 0 && _audioPES.length == 0 ) {
throw new Error("No AAC audio and no AVC video stream found.");
}
// Extract the ADTS or MPEG audio frames.
if(_aacId > 0) {
_readADTS();
} else {
_readMPEG();
}
// Extract the NALU video frames.
_readNALU();
dispatchEvent(new Event(TS.READCOMPLETE));
}
/** Get audio configuration data. **/
public function getADIF():ByteArray {
if(_aacId > 0 && audioTags.length > 0) {
return AAC.getADIF(_audioPES[0].data,_audioPES[0].payload);
} else {
return new ByteArray();
}
};
/** Get video configuration data. **/
public function getAVCC():ByteArray {
if(_firstKey == -1) {
return new ByteArray();
}
return AVC.getAVCC(_videoPES[_firstKey].data,_videoPES[_firstKey].payload);
};
/** Read ADTS frames from audio PES streams. **/
private function _readADTS():void {
var frames:Array;
var overflow:Number = 0;
var tag:Tag;
var stamp:Number;
for(var i:Number=0; i<_audioPES.length; i++) {
// Parse the PES headers.
_audioPES[i].parse();
// Correct for Segmenter's "optimize", which cuts frames in half.
if(overflow > 0) {
_audioPES[i-1].data.position = _audioPES[i-1].data.length;
_audioPES[i-1].data.writeBytes(_audioPES[i].data,_audioPES[i].payload,overflow);
_audioPES[i].payload += overflow;
}
// Store ADTS frames in array.
frames = AAC.getFrames(_audioPES[i].data,_audioPES[i].payload);
for(var j:Number=0; j< frames.length; j++) {
// Increment the timestamp of subsequent frames.
stamp = Math.round(_audioPES[i].pts + j * 1024 * 1000 / frames[j].rate);
tag = new Tag(Tag.AAC_RAW, stamp, stamp, false);
if(i == _audioPES.length-1 && j == frames.length - 1) {
if((_audioPES[i].data.length - frames[j].start)>0) {
tag.push(_audioPES[i].data, frames[j].start, _audioPES[i].data.length - frames[j].start);
}
} else {
tag.push(_audioPES[i].data, frames[j].start, frames[j].length);
}
audioTags.push(tag);
}
// Correct for Segmenter's "optimize", which cuts frames in half.
overflow = frames[frames.length-1].start +
frames[frames.length-1].length - _audioPES[i].data.length;
}
};
/** Read MPEG data from audio PES streams. **/
private function _readMPEG():void {
var tag:Tag;
for(var i:Number=0; i<_audioPES.length; i++) {
_audioPES[i].parse();
tag = new Tag(Tag.MP3_RAW, _audioPES[i].pts,_audioPES[i].dts, false);
tag.push(_audioPES[i].data, _audioPES[i].payload, _audioPES[i].data.length-_audioPES[i].payload);
audioTags.push(tag);
}
};
/** Read NALU frames from video PES streams. **/
private function _readNALU():void {
var overflow:Number;
var units:Array;
var last:Number;
for(var i:Number=0; i<_videoPES.length; i++) {
// Parse the PES headers and NAL units.
try {
_videoPES[i].parse();
} catch (error:Error) {
Log.txt(error.message);
continue;
}
units = AVC.getNALU(_videoPES[i].data,_videoPES[i].payload);
// If there's no NAL unit, push all data in the previous tag.
if(!units.length) {
videoTags[videoTags.length-1].push(_videoPES[i].data, _videoPES[i].payload,
_videoPES[i].data.length - _videoPES[i].payload);
continue;
}
// If NAL units are offset, push preceding data into the previous tag.
overflow = units[0].start - units[0].header - _videoPES[i].payload;
if(overflow) {
videoTags[videoTags.length-1].push(_videoPES[i].data,_videoPES[i].payload,overflow);
}
videoTags.push(new Tag(Tag.AVC_NALU,_videoPES[i].pts,_videoPES[i].dts,false));
// Only push NAL units 1 to 5 into tag.
for(var j:Number = 0; j < units.length; j++) {
if (units[j].type < 6) {
videoTags[videoTags.length-1].push(_videoPES[i].data,units[j].start,units[j].length);
// Unit type 5 indicates a keyframe.
if(units[j].type == 5) {
videoTags[videoTags.length-1].keyframe = true;
if(_firstKey == -1) {
_firstKey = i;
}
}
}
}
}
};
/** Read TS packet. **/
private function _readPacket():void {
// Each packet is 188 bytes.
var todo:uint = TS.PACKETSIZE;
// Sync byte.
if(_data.readByte() != TS.SYNCBYTE) {
throw new Error("Could not parse TS file: sync byte not found.");
}
todo--;
// Payload unit start indicator.
var stt:uint = (_data.readUnsignedByte() & 64) >> 6;
_data.position--;
// Packet ID (last 13 bits of UI16).
var pid:uint = _data.readUnsignedShort() & 8191;
// Check for adaptation field.
todo -=2;
var atf:uint = (_data.readByte() & 48) >> 4;
todo --;
// Read adaptation field if available.
if(atf > 1) {
// Length of adaptation field.
var len:uint = _data.readUnsignedByte();
todo--;
// Random access indicator (keyframe).
//var rai:uint = data.readUnsignedByte() & 64;
_data.position += len;
todo -= len;
// Return if there's only adaptation field.
if(atf == 2 || len == 183) {
_data.position += todo;
return;
}
}
var pes:ByteArray = new ByteArray();
// Parse the PES, split by Packet ID.
switch (pid) {
case _patId:
todo -= _readPAT();
break;
case _pmtId:
todo -= _readPMT();
break;
case _aacId:
case _mp3Id:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_audioPES.push(new PES(pes,true));
} else if (_audioPES.length) {
_audioPES[_audioPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS audio packet with id "+pid);
}
break;
case _avcId:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_videoPES.push(new PES(pes,false));
} else if (_videoPES.length) {
_videoPES[_videoPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS video packet with id "+pid);
}
break;
case _sdtId:
break;
default:
// Ignored other packet IDs, only report error if PMT not yet parsed
// this helps to detect discarded TS packets because of PAT/PMT not being at beginning of TS fragment
if(_pmtId == -1)
Log.txt("Discarding unassignable TS packets with id "+pid);
break;
}
// Jump to the next packet.
_data.position += todo;
};
/** Read the Program Association Table. **/
private function _readPAT():Number {
// Check the section length for a single PMT.
_data.position += 3;
if(_data.readUnsignedByte() > 13) {
throw new Error("Multiple PMT/NIT entries are not supported.");
}
// Grab the PMT ID.
_data.position += 7;
_pmtId = _data.readUnsignedShort() & 8191;
return 13;
};
/** Read the Program Map Table. **/
private function _readPMT():Number {
// Check the section length for a single PMT.
_data.position += 3;
var len:uint = _data.readByte();
var read:uint = 13;
_data.position += 8;
var pil:Number = _data.readByte();
_data.position += pil;
read += pil;
// Loop through the streams in the PMT.
while(read < len) {
var typ:uint = _data.readByte();
var sid:uint = _data.readUnsignedShort() & 8191;
if(typ == 0x0F) {
_aacId = sid;
} else if (typ == 0x1B) {
_avcId = sid;
} else if (typ == 0x03 || typ == 0x04) {
_mp3Id = sid;
}
// descriptor loop length
_data.position++;
var sel:uint = _data.readByte() & 0x3F;
_data.position += sel;
read += sel + 5;
}
return len;
};
}
}
|
package com.mangui.HLS.muxing {
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.utils.Log;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.ByteArray;
import flash.utils.Timer;
/** Representation of an MPEG transport stream. **/
public class TS extends EventDispatcher {
/** TS Sync byte. **/
public static const SYNCBYTE:uint = 0x47;
/** TS Packet size in byte. **/
public static const PACKETSIZE:uint = 188;
/** Identifier for read complete event **/
public static const READCOMPLETE:String = "readComplete"
private static const COUNT:uint = 5000;
/** Packet ID of the AAC audio stream. **/
private var _aacId:Number = -1;
/** List with audio frames. **/
public var audioTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AAC. **/
private var _audioPES:Vector.<PES> = new Vector.<PES>();
/** has PMT been parsed ? **/
private var _pmtParsed:Boolean= false;
/** nb of AV packets before PMT **/
private var _AVpacketsBeforePMT:Number = 0;
/** Packet ID of the video stream. **/
private var _avcId:Number = -1;
/** PES packet that contains the first keyframe. **/
private var _firstKey:Number = -1;
/** Packet ID of the MP3 audio stream. **/
private var _mp3Id:Number = -1;
/** Packet ID of the PAT (is always 0). **/
private var _patId:Number = 0;
/** Packet ID of the Program Map Table. **/
private var _pmtId:Number = -1;
/** List with video frames. **/
/** Packet ID of the SDT (is always 17). **/
private var _sdtId:Number = 17;
public var videoTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AVC. **/
private var _videoPES:Vector.<PES> = new Vector.<PES>();
/** Timer for reading packets **/
public var _timer:Timer;
/** Byte data to be read **/
private var _data:ByteArray;
/* last key Frame PES packet */
private var _lastKeyFrame:PES = null;
/** Transmux the M2TS file into an FLV file. **/
public function TS(data:ByteArray) {
// Extract the elementary streams.
_data = data;
_timer = new Timer(0,0);
_timer.addEventListener(TimerEvent.TIMER, _readData);
};
/** add new data into Buffer */
public function addData(newData:ByteArray):void {
newData.readBytes(_data,_data.position);
_timer.start();
}
/** Read a small chunk of packets each time to avoid blocking **/
private function _readData(e:Event):void {
var i:uint = 0;
while(_data.bytesAvailable && i < COUNT) {
_readPacket();
i++;
}
if (!_data.bytesAvailable) {
_timer.stop();
_extractFrames();
}
}
/** start the timer in order to start reading data **/
public function startReading():void {;
_timer.start();
}
/** setup the video and audio tag vectors from the read data **/
private function _extractFrames():void {
if (_videoPES.length == 0 && _audioPES.length == 0 ) {
throw new Error("No AAC audio and no AVC video stream found.");
}
// Extract the ADTS or MPEG audio frames.
if(_aacId > 0) {
_readADTS();
} else {
_readMPEG();
}
// Extract the NALU video frames.
_readNALU();
dispatchEvent(new Event(TS.READCOMPLETE));
}
/** Get audio configuration data. **/
public function getADIF():ByteArray {
if(_aacId > 0 && audioTags.length > 0) {
return AAC.getADIF(_audioPES[0].data,_audioPES[0].payload);
} else {
return new ByteArray();
}
};
/** Get video configuration data. **/
public function getAVCC():ByteArray {
if(_firstKey == -1) {
return new ByteArray();
}
return AVC.getAVCC(_lastKeyFrame.data,_lastKeyFrame.payload);
};
/** Read ADTS frames from audio PES streams. **/
private function _readADTS():void {
var frames:Array;
var overflow:Number = 0;
var tag:Tag;
var stamp:Number;
for(var i:Number=0; i<_audioPES.length; i++) {
// Parse the PES headers.
_audioPES[i].parse();
// Correct for Segmenter's "optimize", which cuts frames in half.
if(overflow > 0) {
_audioPES[i-1].data.position = _audioPES[i-1].data.length;
_audioPES[i-1].data.writeBytes(_audioPES[i].data,_audioPES[i].payload,overflow);
_audioPES[i].payload += overflow;
}
// Store ADTS frames in array.
frames = AAC.getFrames(_audioPES[i].data,_audioPES[i].payload);
for(var j:Number=0; j< frames.length; j++) {
// Increment the timestamp of subsequent frames.
stamp = Math.round(_audioPES[i].pts + j * 1024 * 1000 / frames[j].rate);
tag = new Tag(Tag.AAC_RAW, stamp, stamp, false);
if(i == _audioPES.length-1 && j == frames.length - 1) {
if((_audioPES[i].data.length - frames[j].start)>0) {
tag.push(_audioPES[i].data, frames[j].start, _audioPES[i].data.length - frames[j].start);
}
} else {
tag.push(_audioPES[i].data, frames[j].start, frames[j].length);
}
audioTags.push(tag);
}
// Correct for Segmenter's "optimize", which cuts frames in half.
overflow = frames[frames.length-1].start +
frames[frames.length-1].length - _audioPES[i].data.length;
}
};
/** Read MPEG data from audio PES streams. **/
private function _readMPEG():void {
var tag:Tag;
for(var i:Number=0; i<_audioPES.length; i++) {
_audioPES[i].parse();
tag = new Tag(Tag.MP3_RAW, _audioPES[i].pts,_audioPES[i].dts, false);
tag.push(_audioPES[i].data, _audioPES[i].payload, _audioPES[i].data.length-_audioPES[i].payload);
audioTags.push(tag);
}
};
/** Read NALU frames from video PES streams. **/
private function _readNALU():void {
var overflow:Number;
var units:Array;
var last:Number;
for(var i:Number=0; i<_videoPES.length; i++) {
// Parse the PES headers and NAL units.
try {
_videoPES[i].parse();
} catch (error:Error) {
Log.txt(error.message);
continue;
}
units = AVC.getNALU(_videoPES[i].data,_videoPES[i].payload);
// If there's no NAL unit, push all data in the previous tag.
if(!units.length) {
videoTags[videoTags.length-1].push(_videoPES[i].data, _videoPES[i].payload,
_videoPES[i].data.length - _videoPES[i].payload);
continue;
}
// If NAL units are offset, push preceding data into the previous tag.
overflow = units[0].start - units[0].header - _videoPES[i].payload;
if(overflow) {
videoTags[videoTags.length-1].push(_videoPES[i].data,_videoPES[i].payload,overflow);
}
videoTags.push(new Tag(Tag.AVC_NALU,_videoPES[i].pts,_videoPES[i].dts,false));
// Only push NAL units 1 to 5 into tag.
for(var j:Number = 0; j < units.length; j++) {
if (units[j].type < 6) {
videoTags[videoTags.length-1].push(_videoPES[i].data,units[j].start,units[j].length);
// Unit type 5 indicates a keyframe.
if(units[j].type == 5) {
videoTags[videoTags.length-1].keyframe = true;
if(_firstKey == -1) {
_firstKey = i;
_lastKeyFrame=_videoPES[i];
}
}
}
}
}
};
/** Read TS packet. **/
private function _readPacket():void {
// Each packet is 188 bytes.
var todo:uint = TS.PACKETSIZE;
// Sync byte.
if(_data.readByte() != TS.SYNCBYTE) {
throw new Error("Could not parse TS file: sync byte not found.");
}
todo--;
// Payload unit start indicator.
var stt:uint = (_data.readUnsignedByte() & 64) >> 6;
_data.position--;
// Packet ID (last 13 bits of UI16).
var pid:uint = _data.readUnsignedShort() & 8191;
// Check for adaptation field.
todo -=2;
var atf:uint = (_data.readByte() & 48) >> 4;
todo --;
// Read adaptation field if available.
if(atf > 1) {
// Length of adaptation field.
var len:uint = _data.readUnsignedByte();
todo--;
// Random access indicator (keyframe).
//var rai:uint = data.readUnsignedByte() & 64;
_data.position += len;
todo -= len;
// Return if there's only adaptation field.
if(atf == 2 || len == 183) {
_data.position += todo;
return;
}
}
var pes:ByteArray = new ByteArray();
// Parse the PES, split by Packet ID.
switch (pid) {
case _patId:
todo -= _readPAT();
break;
case _pmtId:
todo -= _readPMT();
break;
case _aacId:
case _mp3Id:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_audioPES.push(new PES(pes,true));
} else if (_audioPES.length) {
_audioPES[_audioPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS audio packet with id "+pid);
}
break;
case _avcId:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_videoPES.push(new PES(pes,false));
} else if (_videoPES.length) {
_videoPES[_videoPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS video packet with id "+pid + " bad TS segmentation ?");
}
break;
case _sdtId:
break;
default:
_AVpacketsBeforePMT++;
break;
}
// Jump to the next packet.
_data.position += todo;
};
/** Read the Program Association Table. **/
private function _readPAT():Number {
// Check the section length for a single PMT.
_data.position += 3;
if(_data.readUnsignedByte() > 13) {
throw new Error("Multiple PMT entries are not supported.");
}
// Grab the PMT ID.
_data.position += 7;
_pmtId = _data.readUnsignedShort() & 8191;
return 13;
};
/** Read the Program Map Table. **/
private function _readPMT():Number {
// Check the section length for a single PMT.
_data.position += 3;
var len:uint = _data.readByte();
var read:uint = 13;
_data.position += 8;
var pil:Number = _data.readByte();
_data.position += pil;
read += pil;
// Loop through the streams in the PMT.
while(read < len) {
var typ:uint = _data.readByte();
var sid:uint = _data.readUnsignedShort() & 8191;
if(typ == 0x0F) {
_aacId = sid;
} else if (typ == 0x1B) {
_avcId = sid;
} else if (typ == 0x03 || typ == 0x04) {
_mp3Id = sid;
}
// descriptor loop length
_data.position++;
var sel:uint = _data.readByte() & 0x3F;
_data.position += sel;
read += sel + 5;
}
if(_pmtParsed == false) {
_pmtParsed = true;
// if PMT was not parsed before, and some unknown packets have been skipped in between, rewind to beginning of the stream
// it helps with fragment not segmented properly (in theory there should be no A/V packets before PAT/PMT)
if (_AVpacketsBeforePMT > 1) {
Log.txt("late PMT found, rewinding at beginning of TS");
return (-_data.position);
}
}
return len;
};
}
}
|
enhance TS parsing if PMT not at the beginning of the fragment and some AV packets were left before, rewind and parse those AV packets. this should help parsing bad segmented files
|
enhance TS parsing
if PMT not at the beginning of the fragment and some AV packets were left before, rewind and parse those AV packets.
this should help parsing bad segmented files
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
78438f207a62fcdd0e257acdab75abf2e4218544
|
src/org/jivesoftware/xiff/data/Presence.as
|
src/org/jivesoftware/xiff/data/Presence.as
|
package org.jivesoftware.xiff.data{
/*
* Copyright (C) 2003-2007
* Nick Velloff <[email protected]>
* Derrick Grigg <[email protected]>
* Sean Voisen <[email protected]>
* Sean Treadway <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
import org.jivesoftware.xiff.data.ISerializable;
import org.jivesoftware.xiff.data.XMPPStanza;
import flash.xml.XMLNode;
/**
* This class provides encapsulation for manipulation of presence data for sending and receiving.
*
* @author Sean Voisen
* @since 2.0.0
* @availability Flash Player 7
* @param recipient The recipient of the presence, usually in the form of a JID.
* @param sender The sender of the presence, usually in the form of a JID.
* @param presenceType The type of presence as a string. There are predefined static variables for this.
* @param showVal What to show for this presence (away, online, etc.) There are predefined static variables for this.
* @param statusVal The status; usually used for the "away message."
* @param priorityVal The priority of this presence; usually on a scale of 1-5.
* @toc-path Data
* @toc-sort 1
*/
public class Presence extends XMPPStanza implements ISerializable
{
// Static variables for specific type strings
public static var AVAILABLE_TYPE:String = "available";
public static var UNAVAILABLE_TYPE:String = "unavailable";
public static var PROBE_TYPE:String = "probe";
public static var SUBSCRIBE_TYPE:String = "subscribe";
public static var UNSUBSCRIBE_TYPE:String = "unsubscribe";
public static var SUBSCRIBED_TYPE:String = "subscribed";
public static var UNSUBSCRIBED_TYPE:String = "unsubscribed";
public static var ERROR_TYPE:String = "error";
// Static variables for show values
public static var SHOW_AWAY:String = "away";
public static var SHOW_CHAT:String = "chat";
public static var SHOW_DND:String = "dnd";
public static var SHOW_NORMAL:String = "normal";
public static var SHOW_XA:String = "xa";
public static var SHOW_OFFLINE:String = "offline";
// Private node references for property lookups
private var myShowNode:XMLNode;
private var myStatusNode:XMLNode;
private var myPriorityNode:XMLNode;
public function Presence( recipient:String=null, sender:String=null, presenceType:String=null, showVal:String=null, statusVal:String=null, priorityVal:Number=0 )
{
super( recipient, sender, presenceType, null, "presence" );
show = showVal;
status = statusVal;
priority = priorityVal;
}
/**
* Serializes the Presence into XML form for sending to a server.
*
* @return An indication as to whether serialization was successful
* @availability Flash Player 7
*/
override public function serialize( parentNode:XMLNode ):Boolean
{
return super.serialize( parentNode );
}
/**
* Deserializes an XML object and populates the Presence instance with its data.
*
* @param xmlNode The XML to deserialize
* @return An indication as to whether deserialization was sucessful
* @availability Flash Player 7
*/
override public function deserialize( xmlNode:XMLNode ):Boolean
{
var isDeserialized:Boolean = super.deserialize( xmlNode );
if (isDeserialized) {
var children:Array = xmlNode.childNodes;
for( var i:String in children )
{
switch( children[i].nodeName )
{
case "show":
myShowNode = children[i];
break;
case "status":
myStatusNode = children[i];
break;
case "priority":
myPriorityNode = children[i];
break;
}
}
}
return isDeserialized;
}
/**
* The show value; away, online, etc. There are predefined static variables in the Presence
* class for this:
* <ul>
* <li>Presence.SHOW_AWAY</li>
* <li>Presence.SHOW_CHAT</li>
* <li>Presence.SHOW_DND</li>
* <li>Presence.SHOW_NORMAL</li>
* <li>Presence.SHOW_XA</li>
* </ul>
*
* @availability Flash Player 7
*/
public function get show():String
{
if (myShowNode == null) return null;
if (!exists(myShowNode.firstChild)){
return Presence.SHOW_NORMAL;
}
return myShowNode.firstChild.nodeValue;
}
public function set show( showVal:String ):void
{
myShowNode = replaceTextNode(getNode(), myShowNode, "show", showVal);
}
/**
* The status; usually used for "away messages."
*
* @availability Flash Player 7
*/
public function get status():String {
if (myStatusNode == null || myStatusNode.firstChild == null) return null;
return myStatusNode.firstChild.nodeValue;
}
public function set status( statusVal:String ):void
{
myStatusNode = replaceTextNode(getNode(), myStatusNode, "status", statusVal);
}
/**
* The priority of the presence, usually on a scale of 1-5.
*
* @availability Flash Player 7
*/
public function get priority():Number
{
if (myPriorityNode == null) return NaN;
var p:Number = Number(myPriorityNode.firstChild.nodeValue);
if( isNaN( p ) ) {
return NaN;
}
else {
return p;
}
}
public function set priority( priorityVal:Number ):void
{
myPriorityNode = replaceTextNode(getNode(), myPriorityNode, "priority", priorityVal.toString());
}
}
}
|
package org.jivesoftware.xiff.data{
/*
* Copyright (C) 2003-2007
* Nick Velloff <[email protected]>
* Derrick Grigg <[email protected]>
* Sean Voisen <[email protected]>
* Sean Treadway <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
import org.jivesoftware.xiff.data.ISerializable;
import org.jivesoftware.xiff.data.XMPPStanza;
import flash.xml.XMLNode;
/**
* This class provides encapsulation for manipulation of presence data for sending and receiving.
*
* @author Sean Voisen
* @since 2.0.0
* @availability Flash Player 7
* @param recipient The recipient of the presence, usually in the form of a JID.
* @param sender The sender of the presence, usually in the form of a JID.
* @param presenceType The type of presence as a string. There are predefined static variables for this.
* @param showVal What to show for this presence (away, online, etc.) There are predefined static variables for this.
* @param statusVal The status; usually used for the "away message."
* @param priorityVal The priority of this presence; usually on a scale of 1-5.
* @toc-path Data
* @toc-sort 1
*/
public class Presence extends XMPPStanza implements ISerializable
{
// Static constants for specific type strings
public static const AVAILABLE_TYPE:String = "available";
public static const UNAVAILABLE_TYPE:String = "unavailable";
public static const PROBE_TYPE:String = "probe";
public static const SUBSCRIBE_TYPE:String = "subscribe";
public static const UNSUBSCRIBE_TYPE:String = "unsubscribe";
public static const SUBSCRIBED_TYPE:String = "subscribed";
public static const UNSUBSCRIBED_TYPE:String = "unsubscribed";
public static const ERROR_TYPE:String = "error";
// Static constants for show values
public static const SHOW_AWAY:String = "away";
public static const SHOW_CHAT:String = "chat";
public static const SHOW_DND:String = "dnd";
public static const SHOW_NORMAL:String = "normal";
public static const SHOW_XA:String = "xa";
public static const SHOW_OFFLINE:String = "offline";
// Private node references for property lookups
private var myShowNode:XMLNode;
private var myStatusNode:XMLNode;
private var myPriorityNode:XMLNode;
public function Presence( recipient:String=null, sender:String=null, presenceType:String=null, showVal:String=null, statusVal:String=null, priorityVal:Number=0 )
{
super( recipient, sender, presenceType, null, "presence" );
show = showVal;
status = statusVal;
priority = priorityVal;
}
/**
* Serializes the Presence into XML form for sending to a server.
*
* @return An indication as to whether serialization was successful
* @availability Flash Player 7
*/
override public function serialize( parentNode:XMLNode ):Boolean
{
return super.serialize( parentNode );
}
/**
* Deserializes an XML object and populates the Presence instance with its data.
*
* @param xmlNode The XML to deserialize
* @return An indication as to whether deserialization was sucessful
* @availability Flash Player 7
*/
override public function deserialize( xmlNode:XMLNode ):Boolean
{
var isDeserialized:Boolean = super.deserialize( xmlNode );
if (isDeserialized) {
var children:Array = xmlNode.childNodes;
for( var i:String in children )
{
switch( children[i].nodeName )
{
case "show":
myShowNode = children[i];
break;
case "status":
myStatusNode = children[i];
break;
case "priority":
myPriorityNode = children[i];
break;
}
}
}
return isDeserialized;
}
/**
* The show value; away, online, etc. There are predefined static variables in the Presence
* class for this:
* <ul>
* <li>Presence.SHOW_AWAY</li>
* <li>Presence.SHOW_CHAT</li>
* <li>Presence.SHOW_DND</li>
* <li>Presence.SHOW_NORMAL</li>
* <li>Presence.SHOW_XA</li>
* </ul>
*
* @availability Flash Player 7
*/
public function get show():String
{
if (myShowNode == null) return null;
if (!exists(myShowNode.firstChild)){
return Presence.SHOW_NORMAL;
}
return myShowNode.firstChild.nodeValue;
}
public function set show( showVal:String ):void
{
myShowNode = replaceTextNode(getNode(), myShowNode, "show", showVal);
}
/**
* The status; usually used for "away messages."
*
* @availability Flash Player 7
*/
public function get status():String {
if (myStatusNode == null || myStatusNode.firstChild == null) return null;
return myStatusNode.firstChild.nodeValue;
}
public function set status( statusVal:String ):void
{
myStatusNode = replaceTextNode(getNode(), myStatusNode, "status", statusVal);
}
/**
* The priority of the presence, usually on a scale of 1-5.
*
* @availability Flash Player 7
*/
public function get priority():Number
{
if (myPriorityNode == null) return NaN;
var p:Number = Number(myPriorityNode.firstChild.nodeValue);
if( isNaN( p ) ) {
return NaN;
}
else {
return p;
}
}
public function set priority( priorityVal:Number ):void
{
myPriorityNode = replaceTextNode(getNode(), myPriorityNode, "priority", priorityVal.toString());
}
}
}
|
Make the constants const so it doesn't warn when I use them in data binding expressions
|
Make the constants const so it doesn't warn when I use them in data binding expressions
git-svn-id: c197267f952b24206666de142881703007ca05d5@9514 b35dd754-fafc-0310-a699-88a17e54d16e
|
ActionScript
|
apache-2.0
|
nazoking/xiff
|
3544cef62324cb1e4c0a6eb61a71423f84702f63
|
src/org/mangui/HLS/muxing/TS.as
|
src/org/mangui/HLS/muxing/TS.as
|
package org.mangui.HLS.muxing {
import org.mangui.HLS.muxing.*;
import org.mangui.HLS.utils.Log;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.ByteArray;
import flash.utils.Timer;
/** Representation of an MPEG transport stream. **/
public class TS extends EventDispatcher {
/** TS Sync byte. **/
public static const SYNCBYTE:uint = 0x47;
/** TS Packet size in byte. **/
private static const PACKETSIZE:uint = 188;
/** loop counter to avoid blocking **/
private static const COUNT:uint = 5000;
/** Packet ID of the AAC audio stream. **/
private var _aacId:Number = -1;
/** List with audio frames. **/
private var audioTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AAC. **/
private var _audioPES:Vector.<PES> = new Vector.<PES>();
/** has PMT been parsed ? **/
private var _pmtParsed:Boolean= false;
/** nb of AV packets before PMT **/
private var _AVpacketsBeforePMT:Number = 0;
/** Packet ID of the video stream. **/
private var _avcId:Number = -1;
/** PES packet that contains the first keyframe. **/
private var _firstKey:Number = -1;
/** Packet ID of the MP3 audio stream. **/
private var _mp3Id:Number = -1;
/** Packet ID of the PAT (is always 0). **/
private var _patId:Number = 0;
/** Packet ID of the Program Map Table. **/
private var _pmtId:Number = -1;
/** List with video frames. **/
/** Packet ID of the SDT (is always 17). **/
private var _sdtId:Number = 17;
private var videoTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AVC. **/
private var _videoPES:Vector.<PES> = new Vector.<PES>();
/** Timer for reading packets **/
private var _timer:Timer;
/** Byte data to be read **/
private var _data:ByteArray;
/* last PES packet containing AVCC Frame (SPS/PPS) */
private var _lastAVCCFrame:PES = null;
/* callback function upon read complete */
private var _callback:Function;
/** Transmux the M2TS file into an FLV file. **/
public function TS(data:ByteArray,callback:Function) {
// Extract the elementary streams.
_data = data;
_callback = callback;
_timer = new Timer(0,0);
_timer.addEventListener(TimerEvent.TIMER, _readData);
_timer.start();
};
/** append new TS data */
//public function appendData(newData:ByteArray):void {
// newData.readBytes(_data,_data.length);
// _timer.start();
//}
/** Read a small chunk of packets each time to avoid blocking **/
private function _readData(e:Event):void {
var i:uint = 0;
while(_data.bytesAvailable && i < COUNT) {
_readPacket();
i++;
}
if (!_data.bytesAvailable) {
_timer.stop();
_extractFrames();
}
}
/** setup the video and audio tag vectors from the read data **/
private function _extractFrames():void {
if (_videoPES.length == 0 && _audioPES.length == 0 ) {
throw new Error("No AAC audio and no AVC video stream found.");
}
// Extract the ADTS or MP3 audio frames (transform PES packets into audio tags)
if(_aacId > 0) {
_readADTS();
} else {
_readMPEG();
}
// Extract the NALU video frames (transform PES packets into video tags)
_readNALU();
_callback(audioTags,videoTags,_getADIF(),_getAVCC());
}
/** Get audio configuration data. **/
private function _getADIF():ByteArray {
if(_aacId > 0 && audioTags.length > 0) {
return AAC.getADIF(_audioPES[0].data,_audioPES[0].payload);
} else {
return new ByteArray();
}
};
/** Get video configuration data. **/
private function _getAVCC():ByteArray {
if(_firstKey == -1) {
return new ByteArray();
}
return AVC.getAVCC(_lastAVCCFrame.data,_lastAVCCFrame.payload);
};
/** Read ADTS frames from audio PES streams. **/
private function _readADTS():void {
var frames:Array;
var overflow:Number = 0;
var tag:Tag;
var stamp:Number;
for(var i:Number=0; i<_audioPES.length; i++) {
// Parse the PES headers.
_audioPES[i].parse();
// Correct for Segmenter's "optimize", which cuts frames in half.
if(overflow > 0) {
_audioPES[i-1].data.position = _audioPES[i-1].data.length;
_audioPES[i-1].data.writeBytes(_audioPES[i].data,_audioPES[i].payload,overflow);
_audioPES[i].payload += overflow;
}
// Store ADTS frames in array.
frames = AAC.getFrames(_audioPES[i].data,_audioPES[i].payload);
for(var j:Number=0; j< frames.length; j++) {
// Increment the timestamp of subsequent frames.
stamp = Math.round(_audioPES[i].pts + j * 1024 * 1000 / frames[j].rate);
tag = new Tag(Tag.AAC_RAW, stamp, stamp, false);
if(i == _audioPES.length-1 && j == frames.length - 1) {
if((_audioPES[i].data.length - frames[j].start)>0) {
tag.push(_audioPES[i].data, frames[j].start, _audioPES[i].data.length - frames[j].start);
}
} else {
tag.push(_audioPES[i].data, frames[j].start, frames[j].length);
}
audioTags.push(tag);
}
// Correct for Segmenter's "optimize", which cuts frames in half.
overflow = frames[frames.length-1].start +
frames[frames.length-1].length - _audioPES[i].data.length;
}
};
/** Read MPEG data from audio PES streams. **/
private function _readMPEG():void {
var tag:Tag;
for(var i:Number=0; i<_audioPES.length; i++) {
_audioPES[i].parse();
tag = new Tag(Tag.MP3_RAW, _audioPES[i].pts,_audioPES[i].dts, false);
tag.push(_audioPES[i].data, _audioPES[i].payload, _audioPES[i].data.length-_audioPES[i].payload);
audioTags.push(tag);
}
};
/** Read NALU frames from video PES streams. **/
private function _readNALU():void {
var overflow:Number;
var units:Array;
var last:Number;
for(var i:Number=0; i<_videoPES.length; i++) {
// Parse the PES headers and NAL units.
try {
_videoPES[i].parse();
} catch (error:Error) {
Log.txt(error.message);
continue;
}
units = AVC.getNALU(_videoPES[i].data,_videoPES[i].payload);
// If there's no NAL unit, push all data in the previous tag.
if(!units.length) {
videoTags[videoTags.length-1].push(_videoPES[i].data, _videoPES[i].payload,
_videoPES[i].data.length - _videoPES[i].payload);
continue;
}
// If NAL units are offset, push preceding data into the previous tag.
overflow = units[0].start - units[0].header - _videoPES[i].payload;
if(overflow) {
videoTags[videoTags.length-1].push(_videoPES[i].data,_videoPES[i].payload,overflow);
}
videoTags.push(new Tag(Tag.AVC_NALU,_videoPES[i].pts,_videoPES[i].dts,false));
// Only push NAL units 1 to 5 into tag.
for(var j:Number = 0; j < units.length; j++) {
if (units[j].type < 6) {
videoTags[videoTags.length-1].push(_videoPES[i].data,units[j].start,units[j].length);
// Unit type 5 indicates a keyframe.
if(units[j].type == 5) {
videoTags[videoTags.length-1].keyframe = true;
}
} else if (units[j].type == 7 || units[j].type == 8) {
if(_firstKey == -1) {
_firstKey = i;
_lastAVCCFrame=_videoPES[i];
}
}
}
}
};
/** Read TS packet. **/
private function _readPacket():void {
// Each packet is 188 bytes.
var todo:uint = TS.PACKETSIZE;
// Sync byte.
if(_data.readByte() != TS.SYNCBYTE) {
throw new Error("Could not parse TS file: sync byte not found @ offset/len " + _data.position + "/"+ _data.length);
}
todo--;
// Payload unit start indicator.
var stt:uint = (_data.readUnsignedByte() & 64) >> 6;
_data.position--;
// Packet ID (last 13 bits of UI16).
var pid:uint = _data.readUnsignedShort() & 8191;
// Check for adaptation field.
todo -=2;
var atf:uint = (_data.readByte() & 48) >> 4;
todo --;
// Read adaptation field if available.
if(atf > 1) {
// Length of adaptation field.
var len:uint = _data.readUnsignedByte();
todo--;
// Random access indicator (keyframe).
//var rai:uint = data.readUnsignedByte() & 64;
_data.position += len;
todo -= len;
// Return if there's only adaptation field.
if(atf == 2 || len == 183) {
_data.position += todo;
return;
}
}
var pes:ByteArray = new ByteArray();
// Parse the PES, split by Packet ID.
switch (pid) {
case _patId:
todo -= _readPAT();
break;
case _pmtId:
todo -= _readPMT();
break;
case _aacId:
case _mp3Id:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_audioPES.push(new PES(pes,true));
} else if (_audioPES.length) {
_audioPES[_audioPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS audio packet with id "+pid);
}
break;
case _avcId:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_videoPES.push(new PES(pes,false));
} else if (_videoPES.length) {
_videoPES[_videoPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS video packet with id "+pid + " bad TS segmentation ?");
}
break;
case _sdtId:
break;
default:
_AVpacketsBeforePMT++;
break;
}
// Jump to the next packet.
_data.position += todo;
};
/** Read the Program Association Table. **/
private function _readPAT():Number {
// Check the section length for a single PMT.
_data.position += 3;
if(_data.readUnsignedByte() > 13) {
throw new Error("Multiple PMT entries are not supported.");
}
// Grab the PMT ID.
_data.position += 7;
_pmtId = _data.readUnsignedShort() & 8191;
return 13;
};
/** Read the Program Map Table. **/
private function _readPMT():Number {
// Check the section length for a single PMT.
_data.position += 3;
var len:uint = _data.readByte();
var read:uint = 13;
_data.position += 8;
var pil:Number = _data.readByte();
_data.position += pil;
read += pil;
// Loop through the streams in the PMT.
while(read < len) {
var typ:uint = _data.readByte();
var sid:uint = _data.readUnsignedShort() & 8191;
if(typ == 0x0F) {
_aacId = sid;
} else if (typ == 0x1B) {
_avcId = sid;
} else if (typ == 0x03 || typ == 0x04) {
_mp3Id = sid;
}
// descriptor loop length
_data.position++;
var sel:uint = _data.readByte() & 0x3F;
_data.position += sel;
read += sel + 5;
}
if(_pmtParsed == false) {
_pmtParsed = true;
// if PMT was not parsed before, and some unknown packets have been skipped in between, rewind to beginning of the stream
// it helps with fragment not segmented properly (in theory there should be no A/V packets before PAT/PMT)
if (_AVpacketsBeforePMT > 1) {
Log.txt("late PMT found, rewinding at beginning of TS");
return (-_data.position);
}
}
return len;
};
}
}
|
package org.mangui.HLS.muxing {
import org.mangui.HLS.muxing.*;
import org.mangui.HLS.utils.Log;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.ByteArray;
import flash.utils.Timer;
/** Representation of an MPEG transport stream. **/
public class TS extends EventDispatcher {
/** TS Sync byte. **/
private static const SYNCBYTE:uint = 0x47;
/** TS Packet size in byte. **/
private static const PACKETSIZE:uint = 188;
/** loop counter to avoid blocking **/
private static const COUNT:uint = 5000;
/** Packet ID of the AAC audio stream. **/
private var _aacId:Number = -1;
/** List with audio frames. **/
private var audioTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AAC. **/
private var _audioPES:Vector.<PES> = new Vector.<PES>();
/** has PMT been parsed ? **/
private var _pmtParsed:Boolean= false;
/** any TS packets before PMT ? **/
private var _packetsBeforePMT:Boolean = false;
/** Packet ID of the video stream. **/
private var _avcId:Number = -1;
/** PES packet that contains the first keyframe. **/
private var _firstKey:Number = -1;
/** Packet ID of the MP3 audio stream. **/
private var _mp3Id:Number = -1;
/** Packet ID of the PAT (is always 0). **/
private var _patId:Number = 0;
/** Packet ID of the Program Map Table. **/
private var _pmtId:Number = -1;
/** List with video frames. **/
/** Packet ID of the SDT (is always 17). **/
private var _sdtId:Number = 17;
private var videoTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AVC. **/
private var _videoPES:Vector.<PES> = new Vector.<PES>();
/** Timer for reading packets **/
private var _timer:Timer;
/** Byte data to be read **/
private var _data:ByteArray;
/* last PES packet containing AVCC Frame (SPS/PPS) */
private var _lastAVCCFrame:PES = null;
/* callback function upon read complete */
private var _callback:Function;
public static function probe(data:ByteArray):Boolean {
var pos:Number = data.position;
var len:Number = Math.min(data.bytesAvailable,188);
for(var i:Number = 0; i < len ; i++) {
if(data.readByte() == SYNCBYTE) {
data.position = pos+i;
return true;
}
}
data.position = pos;
return false;
}
/** Transmux the M2TS file into an FLV file. **/
public function TS(data:ByteArray,callback:Function) {
// Extract the elementary streams.
_data = data;
_callback = callback;
_timer = new Timer(0,0);
_timer.addEventListener(TimerEvent.TIMER, _readData);
_timer.start();
};
/** append new TS data */
//public function appendData(newData:ByteArray):void {
// newData.readBytes(_data,_data.length);
// _timer.start();
//}
/** Read a small chunk of packets each time to avoid blocking **/
private function _readData(e:Event):void {
var i:uint = 0;
while(_data.bytesAvailable && i < COUNT) {
_readPacket();
i++;
}
if (!_data.bytesAvailable) {
_timer.stop();
_extractFrames();
}
}
/** setup the video and audio tag vectors from the read data **/
private function _extractFrames():void {
if (_videoPES.length == 0 && _audioPES.length == 0 ) {
throw new Error("No AAC audio and no AVC video stream found.");
}
// Extract the ADTS or MP3 audio frames (transform PES packets into audio tags)
if(_aacId > 0) {
_readADTS();
} else {
_readMPEG();
}
// Extract the NALU video frames (transform PES packets into video tags)
_readNALU();
_callback(audioTags,videoTags,_getADIF(),_getAVCC());
}
/** Get audio configuration data. **/
private function _getADIF():ByteArray {
if(_aacId > 0 && audioTags.length > 0) {
return AAC.getADIF(_audioPES[0].data,_audioPES[0].payload);
} else {
return new ByteArray();
}
};
/** Get video configuration data. **/
private function _getAVCC():ByteArray {
if(_firstKey == -1) {
return new ByteArray();
}
return AVC.getAVCC(_lastAVCCFrame.data,_lastAVCCFrame.payload);
};
/** Read ADTS frames from audio PES streams. **/
private function _readADTS():void {
var frames:Array;
var overflow:Number = 0;
var tag:Tag;
var stamp:Number;
for(var i:Number=0; i<_audioPES.length; i++) {
// Parse the PES headers.
_audioPES[i].parse();
// Correct for Segmenter's "optimize", which cuts frames in half.
if(overflow > 0) {
_audioPES[i-1].data.position = _audioPES[i-1].data.length;
_audioPES[i-1].data.writeBytes(_audioPES[i].data,_audioPES[i].payload,overflow);
_audioPES[i].payload += overflow;
}
// Store ADTS frames in array.
frames = AAC.getFrames(_audioPES[i].data,_audioPES[i].payload);
for(var j:Number=0; j< frames.length; j++) {
// Increment the timestamp of subsequent frames.
stamp = Math.round(_audioPES[i].pts + j * 1024 * 1000 / frames[j].rate);
tag = new Tag(Tag.AAC_RAW, stamp, stamp, false);
if(i == _audioPES.length-1 && j == frames.length - 1) {
if((_audioPES[i].data.length - frames[j].start)>0) {
tag.push(_audioPES[i].data, frames[j].start, _audioPES[i].data.length - frames[j].start);
}
} else {
tag.push(_audioPES[i].data, frames[j].start, frames[j].length);
}
audioTags.push(tag);
}
// Correct for Segmenter's "optimize", which cuts frames in half.
overflow = frames[frames.length-1].start +
frames[frames.length-1].length - _audioPES[i].data.length;
}
};
/** Read MPEG data from audio PES streams. **/
private function _readMPEG():void {
var tag:Tag;
for(var i:Number=0; i<_audioPES.length; i++) {
_audioPES[i].parse();
tag = new Tag(Tag.MP3_RAW, _audioPES[i].pts,_audioPES[i].dts, false);
tag.push(_audioPES[i].data, _audioPES[i].payload, _audioPES[i].data.length-_audioPES[i].payload);
audioTags.push(tag);
}
};
/** Read NALU frames from video PES streams. **/
private function _readNALU():void {
var overflow:Number;
var units:Array;
var last:Number;
for(var i:Number=0; i<_videoPES.length; i++) {
// Parse the PES headers and NAL units.
try {
_videoPES[i].parse();
} catch (error:Error) {
Log.txt(error.message);
continue;
}
units = AVC.getNALU(_videoPES[i].data,_videoPES[i].payload);
// If there's no NAL unit, push all data in the previous tag.
if(!units.length) {
videoTags[videoTags.length-1].push(_videoPES[i].data, _videoPES[i].payload,
_videoPES[i].data.length - _videoPES[i].payload);
continue;
}
// If NAL units are offset, push preceding data into the previous tag.
overflow = units[0].start - units[0].header - _videoPES[i].payload;
if(overflow) {
videoTags[videoTags.length-1].push(_videoPES[i].data,_videoPES[i].payload,overflow);
}
videoTags.push(new Tag(Tag.AVC_NALU,_videoPES[i].pts,_videoPES[i].dts,false));
// Only push NAL units 1 to 5 into tag.
for(var j:Number = 0; j < units.length; j++) {
if (units[j].type < 6) {
videoTags[videoTags.length-1].push(_videoPES[i].data,units[j].start,units[j].length);
// Unit type 5 indicates a keyframe.
if(units[j].type == 5) {
videoTags[videoTags.length-1].keyframe = true;
}
} else if (units[j].type == 7 || units[j].type == 8) {
if(_firstKey == -1) {
_firstKey = i;
_lastAVCCFrame=_videoPES[i];
}
}
}
}
};
/** Read TS packet. **/
private function _readPacket():void {
// Each packet is 188 bytes.
var todo:uint = TS.PACKETSIZE;
// Sync byte.
if(_data.readByte() != TS.SYNCBYTE) {
var pos:Number = _data.position;
if(probe(_data) == true) {
Log.txt("lost sync in TS, between offsets:" + pos + "/" + _data.position);
_data.position++;
} else {
throw new Error("Could not parse TS file: sync byte not found @ offset/len " + _data.position + "/"+ _data.length);
}
}
todo--;
// Payload unit start indicator.
var stt:uint = (_data.readUnsignedByte() & 64) >> 6;
_data.position--;
// Packet ID (last 13 bits of UI16).
var pid:uint = _data.readUnsignedShort() & 8191;
// Check for adaptation field.
todo -=2;
var atf:uint = (_data.readByte() & 48) >> 4;
todo --;
// Read adaptation field if available.
if(atf > 1) {
// Length of adaptation field.
var len:uint = _data.readUnsignedByte();
todo--;
// Random access indicator (keyframe).
//var rai:uint = data.readUnsignedByte() & 64;
_data.position += len;
todo -= len;
// Return if there's only adaptation field.
if(atf == 2 || len == 183) {
_data.position += todo;
return;
}
}
var pes:ByteArray = new ByteArray();
// Parse the PES, split by Packet ID.
switch (pid) {
case _patId:
todo -= _readPAT();
break;
case _pmtId:
todo -= _readPMT();
if(_pmtParsed == false) {
_pmtParsed = true;
// if PMT was not parsed before, and some unknown packets have been skipped in between,
// rewind to beginning of the stream, it helps recovering bad segmented content
// in theory there should be no A/V packets before PAT/PMT)
if (_packetsBeforePMT) {
Log.txt("late PMT found, rewinding at beginning of TS");
_data.position = 0;
return;
}
}
break;
case _aacId:
case _mp3Id:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_audioPES.push(new PES(pes,true));
} else if (_audioPES.length) {
_audioPES[_audioPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS audio packet with id "+pid);
}
break;
case _avcId:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_videoPES.push(new PES(pes,false));
} else if (_videoPES.length) {
_videoPES[_videoPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS video packet with id "+pid + " bad TS segmentation ?");
}
break;
case _sdtId:
break;
default:
_packetsBeforePMT=true;
break;
}
// Jump to the next packet.
_data.position += todo;
};
/** Read the Program Association Table. **/
private function _readPAT():Number {
// Check the section length for a single PMT.
_data.position += 3;
if(_data.readUnsignedByte() > 13) {
throw new Error("Multiple PMT entries are not supported.");
}
// Grab the PMT ID.
_data.position += 7;
_pmtId = _data.readUnsignedShort() & 8191;
return 13;
};
/** Read the Program Map Table. **/
private function _readPMT():Number {
// Check the section length for a single PMT.
_data.position += 3;
var len:uint = _data.readByte();
var read:uint = 13;
_data.position += 8;
var pil:Number = _data.readByte();
_data.position += pil;
read += pil;
// Loop through the streams in the PMT.
while(read < len) {
var typ:uint = _data.readByte();
var sid:uint = _data.readUnsignedShort() & 8191;
if(typ == 0x0F) {
_aacId = sid;
} else if (typ == 0x1B) {
_avcId = sid;
} else if (typ == 0x03 || typ == 0x04) {
_mp3Id = sid;
}
// descriptor loop length
_data.position++;
var sel:uint = _data.readByte() & 0x3F;
_data.position += sel;
read += sel + 5;
}
return len;
};
}
}
|
add robustness to TS parsing when sync byte not found, look for it and resynchronize if possible
|
add robustness to TS parsing
when sync byte not found, look for it and resynchronize if possible
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
12904aaef23fa5f5df06b110648a9fcb47203796
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/CloseButtonView.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/CloseButtonView.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.html.beads
{
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.SimpleButton;
import org.apache.flex.core.BeadViewBase;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.html.Button;
import org.apache.flex.html.TitleBar;
/**
* The CloseButtonView class is the view for
* the down arrow button in a ScrollBar and other controls.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class CloseButtonView extends BeadViewBase implements IBeadView
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function CloseButtonView()
{
upView = new Shape();
downView = new Shape();
overView = new Shape();
drawView(upView.graphics, 0xCCCCCC);
drawView(downView.graphics, 0x666666);
drawView(overView.graphics, 0x999999);
}
private function drawView(g:Graphics, bgColor:uint):void
{
g.beginFill(bgColor);
g.drawRect(0, 0, 11, 11);
g.endFill();
}
private var shape:Shape;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
shape = new Shape();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, 11, 11);
shape.graphics.endFill();
SimpleButton(value).upState = upView;
SimpleButton(value).downState = downView;
SimpleButton(value).overState = overView;
SimpleButton(value).hitTestState = shape;
}
private var upView:Shape;
private var downView:Shape;
private var overView:Shape;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.html.beads
{
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.SimpleButton;
import org.apache.flex.core.BeadViewBase;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.html.Button;
import org.apache.flex.html.TitleBar;
/**
* The CloseButtonView class is the view for
* the down arrow button in a ScrollBar and other controls.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class CloseButtonView extends BeadViewBase implements IBeadView
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function CloseButtonView()
{
upView = new Shape();
downView = new Shape();
overView = new Shape();
drawView(upView.graphics, 0xCCCCCC);
drawView(downView.graphics, 0x666666);
drawView(overView.graphics, 0x999999);
}
private function drawView(g:Graphics, bgColor:uint):void
{
g.beginFill(bgColor);
g.drawRect(0, 0, 11, 11);
g.endFill();
g.lineStyle(2);
g.moveTo(3,3);
g.lineTo(8,8);
g.moveTo(3,8);
g.lineTo(8,3);
}
private var shape:Shape;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
shape = new Shape();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, 11, 11);
shape.graphics.endFill();
SimpleButton(value).upState = upView;
SimpleButton(value).downState = downView;
SimpleButton(value).overState = overView;
SimpleButton(value).hitTestState = shape;
}
private var upView:Shape;
private var downView:Shape;
private var overView:Shape;
}
}
|
add x to close button
|
add x to close button
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
fa9a0e5558a4450669cb14c5fd40cc69bcebc4d7
|
src/as/com/threerings/crowd/data/OccupantInfo.as
|
src/as/com/threerings/crowd/data/OccupantInfo.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.crowd.data {
import flash.system.ApplicationDomain;
import com.threerings.util.ClassUtil;
import com.threerings.util.Cloneable;
import com.threerings.util.Integer;
import com.threerings.util.Name;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.SimpleStreamableObject;
import com.threerings.presents.dobj.DSet_Entry;
import com.threerings.crowd.data.BodyObject;
/**
* The occupant info object contains all of the information about an
* occupant of a place that should be shared with other occupants of the
* place. These objects are stored in the place object itself and are
* updated when bodies enter and exit a place.
*
* <p> A system that builds upon the Crowd framework can extend this class to
* include extra information about their occupants. They will need to provide a
* derived {@link BodyObject} that creates and configures their occupant info
* in {@link BodyObject#createOccupantInfo}.
*
* <p> Note also that this class implements {@link Cloneable} which means
* that if derived classes add non-primitive attributes, they are
* responsible for adding the code to clone those attributes when a clone
* is requested.
*/
public class OccupantInfo extends SimpleStreamableObject
implements DSet_Entry, Cloneable
{
/** Constant value for {@link #status}. */
public static const ACTIVE :int = 0;
/** Constant value for {@link #status}. */
public static const IDLE :int = 1;
/** Constant value for {@link #status}. */
public static const DISCONNECTED :int = 2;
/** Maps status codes to human readable strings. */
public static const X_STATUS :Array = [ "active", "idle", "discon" ];
/** The body object id of this occupant (and our entry key). */
public var bodyOid :int;
/** The username of this occupant. */
public var username :Name;
/** The status of this occupant. */
public var status :int = ACTIVE;
/**
* Constructs an occupant info record, optionally obtaining data from the
* supplied BodyObject.
*/
public function OccupantInfo (body :BodyObject = null)
{
if (body != null) {
bodyOid = body.getOid();
username = body.getVisibleName();
status = body.status;
}
}
/** Access to the body object id as an int. */
public function getBodyOid () :int
{
return bodyOid;
}
/**
* Generates a cloned copy of this instance.
*/
public function clone () :Object
{
var that :OccupantInfo =
ClassUtil.newInstance(this, ApplicationDomain.currentDomain) as OccupantInfo;
that.bodyOid = this.bodyOid;
that.username = this.username;
that.status = this.status;
return that;
}
// documentation inherited from interface DSet_Entry
public function getKey () :Object
{
return bodyOid;
}
// from interface Streamable
override public function readObject (ins :ObjectInputStream) :void
{
super.readObject(ins);
bodyOid = (ins.readField(Integer) as Integer).value;
username = (ins.readObject() as Name);
status = ins.readByte();
}
// from interface Streamable
override public function writeObject (out :ObjectOutputStream) :void
{
super.writeObject(out);
out.writeObject(new Integer(bodyOid));
out.writeObject(username);
out.writeByte(status);
}
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.crowd.data {
import flash.system.ApplicationDomain;
import com.threerings.util.ClassUtil;
import com.threerings.util.Cloneable;
import com.threerings.util.Integer;
import com.threerings.util.Name;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.SimpleStreamableObject;
import com.threerings.presents.dobj.DSet_Entry;
import com.threerings.crowd.data.BodyObject;
/**
* The occupant info object contains all of the information about an
* occupant of a place that should be shared with other occupants of the
* place. These objects are stored in the place object itself and are
* updated when bodies enter and exit a place.
*
* <p> A system that builds upon the Crowd framework can extend this class to
* include extra information about their occupants. They will need to provide a
* derived {@link BodyObject} that creates and configures their occupant info
* in {@link BodyObject#createOccupantInfo}.
*
* <p> Note also that this class implements {@link Cloneable} which means
* that if derived classes add non-primitive attributes, they are
* responsible for adding the code to clone those attributes when a clone
* is requested.
*/
public class OccupantInfo extends SimpleStreamableObject
implements DSet_Entry, Cloneable
{
/** Constant value for {@link #status}. */
public static const ACTIVE :int = 0;
/** Constant value for {@link #status}. */
public static const IDLE :int = 1;
/** Constant value for {@link #status}. */
public static const DISCONNECTED :int = 2;
/** Maps status codes to human readable strings. */
public static const X_STATUS :Array = [ "active", "idle", "discon" ];
/** The body object id of this occupant (and our entry key). */
public var bodyOid :int;
/** The username of this occupant. */
public var username :Name;
/** The status of this occupant. */
public var status :int = ACTIVE;
/**
* Constructs an occupant info record, optionally obtaining data from the
* supplied BodyObject.
*/
public function OccupantInfo (body :BodyObject = null)
{
if (body != null) {
bodyOid = body.getOid();
username = body.getVisibleName();
status = body.status;
}
}
/** Access to the body object id as an int. */
public function getBodyOid () :int
{
return bodyOid;
}
/**
* Generates a cloned copy of this instance.
*/
public function clone () :Object
{
var that :OccupantInfo =
ClassUtil.newInstance(this) as OccupantInfo;
that.bodyOid = this.bodyOid;
that.username = this.username;
that.status = this.status;
return that;
}
// documentation inherited from interface DSet_Entry
public function getKey () :Object
{
return bodyOid;
}
// from interface Streamable
override public function readObject (ins :ObjectInputStream) :void
{
super.readObject(ins);
bodyOid = (ins.readField(Integer) as Integer).value;
username = (ins.readObject() as Name);
status = ins.readByte();
}
// from interface Streamable
override public function writeObject (out :ObjectOutputStream) :void
{
super.writeObject(out);
out.writeObject(new Integer(bodyOid));
out.writeObject(username);
out.writeByte(status);
}
}
}
|
Revert this, I'll work it another way.
|
Revert this, I'll work it another way.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5229 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
4ead6680813b946a03c7c2aae33da64e33f8eab0
|
src/aerys/minko/scene/controller/TransformController.as
|
src/aerys/minko/scene/controller/TransformController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private static const INIT_NONE : uint = 0;
private static const INIT_LOCAL_TO_WORLD : uint = 1;
private static const INIT_WORLD_TO_LOCAL : uint = 2;
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _initialized : Vector.<uint>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _worldToLocalTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>;
private var _parentId : Vector.<int>;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
updateLocalToWorld();
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var rootTransform : Matrix4x4 = _transforms[nodeId];
var root : ISceneNode = _idToNode[childId];
if (rootTransform._hasChanged || _initialized[nodeId] == INIT_NONE)
{
rootLocalToWorld.copyFrom(rootTransform);
if (nodeId != 0)
rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]);
rootTransform._hasChanged = false;
_initialized[nodeId] = INIT_LOCAL_TO_WORLD;
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
}
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
var isDirty : Boolean = localToWorld._hasChanged;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged
|| !_initialized[childId];
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
_initialized[childId] = INIT_LOCAL_TO_WORLD;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function updateAncestorsAndSelfLocalToWorld(nodeId : int) : void
{
var dirtyRoot : int = -1;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged ||
!_initialized[nodeId])
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_initialized = null;
_localToWorldTransforms = null;
_worldToLocalTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_initialized = new <uint>[];
_localToWorldTransforms = new <Matrix4x4>[];
_worldToLocalTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
_initialized[nodeId] = INIT_NONE;
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_worldToLocalTransforms.length = _localToWorldTransforms.length;
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
return _localToWorldTransforms[nodeId];
}
public function getWorldToLocalTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId];
if (!worldToLocalTransform)
{
_worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4();
if (!forceUpdate)
{
worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert();
_initialized[nodeId] |= INIT_WORLD_TO_LOCAL;
}
}
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
if (!(_initialized[nodeId] & INIT_WORLD_TO_LOCAL))
{
_initialized[nodeId] |= INIT_WORLD_TO_LOCAL;
worldToLocalTransform
.copyFrom(_localToWorldTransforms[nodeId])
.invert();
}
return worldToLocalTransform;
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private static const INIT_NONE : uint = 0;
private static const INIT_LOCAL_TO_WORLD : uint = 1;
private static const INIT_WORLD_TO_LOCAL : uint = 2;
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _initialized : Vector.<uint>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _worldToLocalTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>;
private var _parentId : Vector.<int>;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
updateLocalToWorld();
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var rootTransform : Matrix4x4 = _transforms[nodeId];
var root : ISceneNode = _idToNode[childId];
if (rootTransform._hasChanged || _initialized[nodeId] == INIT_NONE)
{
rootLocalToWorld.copyFrom(rootTransform);
if (nodeId != 0)
rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]);
rootTransform._hasChanged = false;
_initialized[nodeId] = INIT_LOCAL_TO_WORLD;
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
}
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
var isDirty : Boolean = localToWorld._hasChanged;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged
|| !_initialized[childId];
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
_initialized[childId] = INIT_LOCAL_TO_WORLD;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function updateAncestorsAndSelfLocalToWorld(nodeId : int) : void
{
var dirtyRoot : int = -1;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged ||
!_initialized[nodeId])
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_initialized = null;
_localToWorldTransforms = null;
_worldToLocalTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
var oldNodeToId : Dictionary = _nodeToId;
var oldInitialized : Vector.<uint> = _initialized;
var oldLocalToWorldTransforms : Vector.<Matrix4x4> = _localToWorldTransforms;
var oldWorldToLocalTransform : Vector.<Matrix4x4> = _worldToLocalTransforms;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_initialized = new <uint>[];
_localToWorldTransforms = new <Matrix4x4>[];
_worldToLocalTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
if (oldNodeToId && node in oldNodeToId)
{
var oldNodeId : uint = oldNodeToId[node];
_localToWorldTransforms[nodeId] = oldLocalToWorldTransforms[oldNodeId];
_worldToLocalTransforms[nodeId] = oldWorldToLocalTransform[oldNodeId];
_initialized[nodeId] = oldInitialized[oldNodeId];
}
else
{
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
_worldToLocalTransforms[nodeId] = null;
_initialized[nodeId] = INIT_NONE;
}
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_worldToLocalTransforms.length = _localToWorldTransforms.length;
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
return _localToWorldTransforms[nodeId];
}
public function getWorldToLocalTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId];
if (!worldToLocalTransform)
{
_worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4();
if (!forceUpdate)
{
worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert();
_initialized[nodeId] |= INIT_WORLD_TO_LOCAL;
}
}
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
if (!(_initialized[nodeId] & INIT_WORLD_TO_LOCAL))
{
_initialized[nodeId] |= INIT_WORLD_TO_LOCAL;
worldToLocalTransform
.copyFrom(_localToWorldTransforms[nodeId])
.invert();
}
return worldToLocalTransform;
}
}
}
|
update TransformController.updateTransformsList() to use already init. matrices/flags for nodes that where already part of the target (sub)scene tree
|
update TransformController.updateTransformsList() to use already init. matrices/flags for nodes that where already part of the target (sub)scene tree
|
ActionScript
|
mit
|
aerys/minko-as3
|
8774963d90c02e17470ecf507e8dee0c7ef5152d
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.net.Socket;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
private const RTMFP_URL:String = "rtmfp://tor-facilitator.bamsoftware.com";
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "tor-facilitator.bamsoftware.com",
port: 9002
};
/* Local Tor client to use in case of RTMFP connection. */
private const DEFAULT_LOCAL_TOR_CLIENT_ADDR:Object = {
host: "127.0.0.1",
port: 9002
};
private const MAX_NUM_PROXY_PAIRS:uint = 10;
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 1000;
// Bytes per second. Set to undefined to disable limit.
public const RATE_LIMIT:Number = undefined;
// Seconds.
private const RATE_LIMIT_HISTORY:Number = 5.0;
/* TextField for debug output. */
private var output_text:TextField;
/* UI shown when debug is off. */
private var badge:Badge;
/* Number of proxy pairs currently connected (up to
MAX_NUM_PROXY_PAIRS). */
private var num_proxy_pairs:int = 0;
private var fac_addr:Object;
private var local_addr:Object;
public var rate_limit:RateLimit;
public function puts(s:String):void
{
if (output_text) {
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
}
public function swfcat()
{
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
badge = new Badge();
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
if (this.loaderInfo.parameters["debug"] || this.loaderInfo.parameters["client"]) {
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
addChild(output_text);
} else {
addChild(badge);
}
puts("Parameters loaded.");
fac_addr = get_param_addr("facilitator", DEFAULT_FACILITATOR_ADDR);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
local_addr = get_param_addr("local", DEFAULT_LOCAL_TOR_CLIENT_ADDR);
if (!local_addr) {
puts("Error: Local spec must be in the form \"host:port\".");
return;
}
if (this.loaderInfo.parameters["client"])
client_main();
else
proxy_main();
}
/* Get an address structure from the given movie parameter, or the given
default. Returns null on error. */
private function get_param_addr(param:String, default_addr:Object):Object
{
var spec:String, addr:Object;
spec = this.loaderInfo.parameters[param];
if (spec)
return parse_addr_spec(spec);
else
return default_addr;
}
/* The main logic begins here, after start-up issues are taken care of. */
private function proxy_main():void
{
var fac_url:String;
var loader:URLLoader;
if (num_proxy_pairs >= MAX_NUM_PROXY_PAIRS) {
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
return;
}
loader = new URLLoader();
/* Get the x-www-form-urlencoded values. */
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, fac_complete);
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(new URLRequest(fac_url));
}
private function fac_complete(e:Event):void
{
var loader:URLLoader;
var client_spec:String;
var relay_spec:String;
var proxy_pair:Object;
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
loader = e.target as URLLoader;
client_spec = loader.data.client;
if (client_spec == "") {
puts("No clients.");
return;
} else if (!client_spec) {
puts("Error: missing \"client\" in response.");
return;
}
relay_spec = loader.data.relay;
if (!relay_spec) {
puts("Error: missing \"relay\" in response.");
return;
}
puts("Facilitator: got client:\"" + client_spec + "\" "
+ "relay:\"" + relay_spec + "\".");
try {
proxy_pair = make_proxy_pair(client_spec, relay_spec);
} catch (e:ArgumentError) {
puts("Error: " + e);
return;
}
proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void {
proxy_pair.log("Complete.");
num_proxy_pairs--;
badge.proxy_end();
});
proxy_pair.connect();
num_proxy_pairs++;
badge.proxy_begin();
}
private function client_main():void
{
var rs:RTMFPSocket;
rs = new RTMFPSocket(RTMFP_URL);
rs.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Got RTMFP id " + rs.id);
register(rs);
});
rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, client_accept);
rs.listen();
}
private function client_accept(e:Event):void {
var rs:RTMFPSocket;
var s_t:Socket;
var proxy_pair:ProxyPair;
rs = e.target as RTMFPSocket;
s_t = new Socket();
puts("Got RTMFP connection from " + rs.peer_id);
proxy_pair = new ProxyPair(this, rs, function ():void {
/* Do nothing; already connected. */
}, s_t, function ():void {
s_t.connect(local_addr.host, local_addr.port);
});
proxy_pair.connect();
}
private function register(rs:RTMFPSocket):void {
var fac_url:String;
var loader:URLLoader;
var request:URLRequest;
var variables:URLVariables;
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Facilitator: registered.");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
rs.close();
});
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
rs.close();
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
request = new URLRequest(fac_url);
request.method = URLRequestMethod.POST;
request.data = new URLVariables;
request.data["client"] = rs.id;
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(request);
}
private function make_proxy_pair(client_spec:String, relay_spec:String):ProxyPair
{
var proxy_pair:ProxyPair;
var addr_c:Object;
var addr_r:Object;
var s_c:*;
var s_r:Socket;
addr_r = swfcat.parse_addr_spec(relay_spec);
if (!addr_r)
throw new ArgumentError("Relay spec must be in the form \"host:port\".");
addr_c = swfcat.parse_addr_spec(client_spec);
if (addr_c) {
s_c = new Socket();
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(addr_c.host, addr_c.port);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + addr_c.host + ":" + addr_c.port + ","
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
if (client_spec.match(/^[0-9A-Fa-f]{64}$/)) {
s_c = new RTMFPSocket(RTMFP_URL);
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(client_spec);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + client_spec.substr(0, 4) + "...,"
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
throw new ArgumentError("Can't parse client spec \"" + client_spec + "\".");
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.text.TextFormat;
import flash.text.TextField;
import flash.utils.getTimer;
class Badge extends flash.display.Sprite
{
/* Number of proxy pairs currently connected. */
private var num_proxy_pairs:int = 0;
/* Number of proxy pairs ever connected. */
private var total_proxy_pairs:int = 0;
[Embed(source="badge.png")]
private var BadgeImage:Class;
private var tot_client_count_tf:TextField;
private var tot_client_count_fmt:TextFormat;
private var cur_client_count_tf:TextField;
private var cur_client_count_fmt:TextFormat;
public function Badge()
{
/* Setup client counter for badge. */
tot_client_count_fmt = new TextFormat();
tot_client_count_fmt.color = 0xFFFFFF;
tot_client_count_fmt.align = "center";
tot_client_count_fmt.font = "courier-new";
tot_client_count_fmt.bold = true;
tot_client_count_fmt.size = 10;
tot_client_count_tf = new TextField();
tot_client_count_tf.width = 20;
tot_client_count_tf.height = 17;
tot_client_count_tf.background = false;
tot_client_count_tf.defaultTextFormat = tot_client_count_fmt;
tot_client_count_tf.x=47;
tot_client_count_tf.y=0;
cur_client_count_fmt = new TextFormat();
cur_client_count_fmt.color = 0xFFFFFF;
cur_client_count_fmt.align = "center";
cur_client_count_fmt.font = "courier-new";
cur_client_count_fmt.bold = true;
cur_client_count_fmt.size = 10;
cur_client_count_tf = new TextField();
cur_client_count_tf.width = 20;
cur_client_count_tf.height = 17;
cur_client_count_tf.background = false;
cur_client_count_tf.defaultTextFormat = cur_client_count_fmt;
cur_client_count_tf.x=47;
cur_client_count_tf.y=6;
addChild(new BadgeImage());
addChild(tot_client_count_tf);
addChild(cur_client_count_tf);
/* Update the client counter on badge. */
update_client_count();
}
public function proxy_begin():void
{
num_proxy_pairs++;
total_proxy_pairs++;
update_client_count();
}
public function proxy_end():void
{
num_proxy_pairs--;
update_client_count();
}
private function update_client_count():void
{
/* Update total client count. */
if (String(total_proxy_pairs).length == 1)
tot_client_count_tf.text = "0" + String(total_proxy_pairs);
else
tot_client_count_tf.text = String(total_proxy_pairs);
/* Update current client count. */
cur_client_count_tf.text = "";
for(var i:Number = 0; i < num_proxy_pairs; i++)
cur_client_count_tf.appendText(".");
}
}
class RateLimit
{
public function RateLimit()
{
}
public function update(n:Number):Boolean
{
return true;
}
public function when():Number
{
return 0.0;
}
public function is_limited():Boolean
{
return false;
}
}
class RateUnlimit extends RateLimit
{
public function RateUnlimit()
{
}
public override function update(n:Number):Boolean
{
return true;
}
public override function when():Number
{
return 0.0;
}
public override function is_limited():Boolean
{
return false;
}
}
class BucketRateLimit extends RateLimit
{
private var amount:Number;
private var capacity:Number;
private var time:Number;
private var last_update:uint;
public function BucketRateLimit(capacity:Number, time:Number)
{
this.amount = 0.0;
/* capacity / time is the rate we are aiming for. */
this.capacity = capacity;
this.time = time;
this.last_update = getTimer();
}
private function age():void
{
var now:uint;
var delta:Number;
now = getTimer();
delta = (now - last_update) / 1000.0;
last_update = now;
amount -= delta * capacity / time;
if (amount < 0.0)
amount = 0.0;
}
public override function update(n:Number):Boolean
{
age();
amount += n;
return amount <= capacity;
}
public override function when():Number
{
age();
return (amount - capacity) / (capacity / time);
}
public override function is_limited():Boolean
{
age();
return amount > capacity;
}
}
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.net.Socket;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
private const RTMFP_URL:String = "rtmfp://tor-facilitator.bamsoftware.com";
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "tor-facilitator.bamsoftware.com",
port: 9002
};
/* Local Tor client to use in case of RTMFP connection. */
private const DEFAULT_LOCAL_TOR_CLIENT_ADDR:Object = {
host: "127.0.0.1",
port: 9002
};
private const MAX_NUM_PROXY_PAIRS:uint = 10;
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 1000;
// Bytes per second. Set to undefined to disable limit.
public static const RATE_LIMIT:Number = undefined;
// Seconds.
private static const RATE_LIMIT_HISTORY:Number = 5.0;
/* TextField for debug output. */
private var output_text:TextField;
/* UI shown when debug is off. */
private var badge:Badge;
/* Number of proxy pairs currently connected (up to
MAX_NUM_PROXY_PAIRS). */
private var num_proxy_pairs:int = 0;
private var fac_addr:Object;
private var local_addr:Object;
public var rate_limit:RateLimit;
public function puts(s:String):void
{
if (output_text) {
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
}
public function swfcat()
{
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
badge = new Badge();
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
if (this.loaderInfo.parameters["debug"] || this.loaderInfo.parameters["client"]) {
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
addChild(output_text);
} else {
addChild(badge);
}
puts("Parameters loaded.");
fac_addr = get_param_addr("facilitator", DEFAULT_FACILITATOR_ADDR);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
local_addr = get_param_addr("local", DEFAULT_LOCAL_TOR_CLIENT_ADDR);
if (!local_addr) {
puts("Error: Local spec must be in the form \"host:port\".");
return;
}
if (this.loaderInfo.parameters["client"])
client_main();
else
proxy_main();
}
/* Get an address structure from the given movie parameter, or the given
default. Returns null on error. */
private function get_param_addr(param:String, default_addr:Object):Object
{
var spec:String;
spec = this.loaderInfo.parameters[param];
if (spec)
return parse_addr_spec(spec);
else
return default_addr;
}
/* The main logic begins here, after start-up issues are taken care of. */
private function proxy_main():void
{
var fac_url:String;
var loader:URLLoader;
if (num_proxy_pairs >= MAX_NUM_PROXY_PAIRS) {
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
return;
}
loader = new URLLoader();
/* Get the x-www-form-urlencoded values. */
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, fac_complete);
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(new URLRequest(fac_url));
}
private function fac_complete(e:Event):void
{
var loader:URLLoader;
var client_spec:String;
var relay_spec:String;
var proxy_pair:Object;
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
loader = e.target as URLLoader;
client_spec = loader.data.client;
if (client_spec == "") {
puts("No clients.");
return;
} else if (!client_spec) {
puts("Error: missing \"client\" in response.");
return;
}
relay_spec = loader.data.relay;
if (!relay_spec) {
puts("Error: missing \"relay\" in response.");
return;
}
puts("Facilitator: got client:\"" + client_spec + "\" "
+ "relay:\"" + relay_spec + "\".");
try {
proxy_pair = make_proxy_pair(client_spec, relay_spec);
} catch (e:ArgumentError) {
puts("Error: " + e);
return;
}
proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void {
proxy_pair.log("Complete.");
num_proxy_pairs--;
badge.proxy_end();
});
proxy_pair.connect();
num_proxy_pairs++;
badge.proxy_begin();
}
private function client_main():void
{
var rs:RTMFPSocket;
rs = new RTMFPSocket(RTMFP_URL);
rs.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Got RTMFP id " + rs.id);
register(rs);
});
rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, client_accept);
rs.listen();
}
private function client_accept(e:Event):void {
var rs:RTMFPSocket;
var s_t:Socket;
var proxy_pair:ProxyPair;
rs = e.target as RTMFPSocket;
s_t = new Socket();
puts("Got RTMFP connection from " + rs.peer_id);
proxy_pair = new ProxyPair(this, rs, function ():void {
/* Do nothing; already connected. */
}, s_t, function ():void {
s_t.connect(local_addr.host, local_addr.port);
});
proxy_pair.connect();
}
private function register(rs:RTMFPSocket):void {
var fac_url:String;
var loader:URLLoader;
var request:URLRequest;
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Facilitator: registered.");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
rs.close();
});
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
rs.close();
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
request = new URLRequest(fac_url);
request.method = URLRequestMethod.POST;
request.data = new URLVariables();
request.data["client"] = rs.id;
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(request);
}
private function make_proxy_pair(client_spec:String, relay_spec:String):ProxyPair
{
var proxy_pair:ProxyPair;
var addr_c:Object;
var addr_r:Object;
var s_c:*;
var s_r:Socket;
addr_r = swfcat.parse_addr_spec(relay_spec);
if (!addr_r)
throw new ArgumentError("Relay spec must be in the form \"host:port\".");
addr_c = swfcat.parse_addr_spec(client_spec);
if (addr_c) {
s_c = new Socket();
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(addr_c.host, addr_c.port);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + addr_c.host + ":" + addr_c.port + ","
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
if (client_spec.match(/^[0-9A-Fa-f]{64}$/)) {
s_c = new RTMFPSocket(RTMFP_URL);
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(client_spec);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + client_spec.substr(0, 4) + "...,"
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
throw new ArgumentError("Can't parse client spec \"" + client_spec + "\".");
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.text.TextFormat;
import flash.text.TextField;
import flash.utils.getTimer;
class Badge extends flash.display.Sprite
{
/* Number of proxy pairs currently connected. */
private var num_proxy_pairs:int = 0;
/* Number of proxy pairs ever connected. */
private var total_proxy_pairs:int = 0;
[Embed(source="badge.png")]
private var BadgeImage:Class;
private var tot_client_count_tf:TextField;
private var tot_client_count_fmt:TextFormat;
private var cur_client_count_tf:TextField;
private var cur_client_count_fmt:TextFormat;
public function Badge()
{
/* Setup client counter for badge. */
tot_client_count_fmt = new TextFormat();
tot_client_count_fmt.color = 0xFFFFFF;
tot_client_count_fmt.align = "center";
tot_client_count_fmt.font = "courier-new";
tot_client_count_fmt.bold = true;
tot_client_count_fmt.size = 10;
tot_client_count_tf = new TextField();
tot_client_count_tf.width = 20;
tot_client_count_tf.height = 17;
tot_client_count_tf.background = false;
tot_client_count_tf.defaultTextFormat = tot_client_count_fmt;
tot_client_count_tf.x=47;
tot_client_count_tf.y=0;
cur_client_count_fmt = new TextFormat();
cur_client_count_fmt.color = 0xFFFFFF;
cur_client_count_fmt.align = "center";
cur_client_count_fmt.font = "courier-new";
cur_client_count_fmt.bold = true;
cur_client_count_fmt.size = 10;
cur_client_count_tf = new TextField();
cur_client_count_tf.width = 20;
cur_client_count_tf.height = 17;
cur_client_count_tf.background = false;
cur_client_count_tf.defaultTextFormat = cur_client_count_fmt;
cur_client_count_tf.x=47;
cur_client_count_tf.y=6;
addChild(new BadgeImage());
addChild(tot_client_count_tf);
addChild(cur_client_count_tf);
/* Update the client counter on badge. */
update_client_count();
}
public function proxy_begin():void
{
num_proxy_pairs++;
total_proxy_pairs++;
update_client_count();
}
public function proxy_end():void
{
num_proxy_pairs--;
update_client_count();
}
private function update_client_count():void
{
/* Update total client count. */
if (String(total_proxy_pairs).length == 1)
tot_client_count_tf.text = "0" + String(total_proxy_pairs);
else
tot_client_count_tf.text = String(total_proxy_pairs);
/* Update current client count. */
cur_client_count_tf.text = "";
for(var i:Number = 0; i < num_proxy_pairs; i++)
cur_client_count_tf.appendText(".");
}
}
class RateLimit
{
public function RateLimit()
{
}
public function update(n:Number):Boolean
{
return true;
}
public function when():Number
{
return 0.0;
}
public function is_limited():Boolean
{
return false;
}
}
class RateUnlimit extends RateLimit
{
public function RateUnlimit()
{
}
public override function update(n:Number):Boolean
{
return true;
}
public override function when():Number
{
return 0.0;
}
public override function is_limited():Boolean
{
return false;
}
}
class BucketRateLimit extends RateLimit
{
private var amount:Number;
private var capacity:Number;
private var time:Number;
private var last_update:uint;
public function BucketRateLimit(capacity:Number, time:Number)
{
this.amount = 0.0;
/* capacity / time is the rate we are aiming for. */
this.capacity = capacity;
this.time = time;
this.last_update = getTimer();
}
private function age():void
{
var now:uint;
var delta:Number;
now = getTimer();
delta = (now - last_update) / 1000.0;
last_update = now;
amount -= delta * capacity / time;
if (amount < 0.0)
amount = 0.0;
}
public override function update(n:Number):Boolean
{
age();
amount += n;
return amount <= capacity;
}
public override function when():Number
{
age();
return (amount - capacity) / (capacity / time);
}
public override function is_limited():Boolean
{
age();
return amount > capacity;
}
}
|
Make some changes suggested by flex-pmd.
|
Make some changes suggested by flex-pmd.
|
ActionScript
|
mit
|
infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy
|
e52dcf8b3b824f4acb3c19b1e0382b7eba7532ca
|
src/org/mangui/hls/loader/LevelLoader.as
|
src/org/mangui/hls/loader/LevelLoader.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.loader {
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.clearTimeout;
import flash.utils.getTimer;
import flash.utils.setTimeout;
import org.mangui.hls.constant.HLSLoaderTypes;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.constant.HLSTypes;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSLoadMetrics;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
import org.mangui.hls.model.Fragment;
import org.mangui.hls.model.Level;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.playlist.DataUri;
import org.mangui.hls.playlist.Manifest;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class LevelLoader {
/** Reference to the hls framework controller. **/
private var _hls : HLS;
/** levels vector. **/
private var _levels : Vector.<Level>;
/** Object that fetches the manifest. **/
private var _urlloader : URLLoader;
/** Link to the M3U8 file. **/
private var _url : String;
/** are all playlists filled ? **/
private var _canStart : Boolean;
/** Timeout ID for reloading live playlists. **/
private var _timeoutID : uint;
/** Streaming type (live, ondemand). **/
private var _type : String;
/** last reload manifest time **/
private var _reloadPlaylistTimer : uint;
/** current load level **/
private var _loadLevel : int;
/** reference to manifest being loaded **/
private var _manifestLoading : Manifest;
/** is this loader closed **/
private var _closed : Boolean = false;
/* playlist retry timeout */
private var _retryTimeout : Number;
private var _retryCount : int;
/* alt audio tracks */
private var _altAudioTracks : Vector.<AltAudioTrack>;
/* manifest load metrics */
private var _metrics : HLSLoadMetrics;
/** Setup the loader. **/
public function LevelLoader(hls : HLS) {
_hls = hls;
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
_levels = new Vector.<Level>();
};
public function dispose() : void {
_close();
if(_urlloader) {
_urlloader.removeEventListener(Event.COMPLETE, _loadCompleteHandler);
_urlloader.removeEventListener(ProgressEvent.PROGRESS, _loadProgressHandler);
_urlloader.removeEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
_urlloader = null;
}
_hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
}
/** Loading failed; return errors. **/
private function _errorHandler(event : ErrorEvent) : void {
var txt : String;
var code : int;
if (event is SecurityErrorEvent) {
code = HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR;
txt = "Cannot load M3U8: crossdomain access denied:" + event.text;
} else if (event is IOErrorEvent && _levels.length && (HLSSettings.manifestLoadMaxRetry == -1 || _retryCount < HLSSettings.manifestLoadMaxRetry)) {
CONFIG::LOGGING {
Log.warn("I/O Error while trying to load Playlist, retry in " + _retryTimeout + " ms");
}
_timeoutID = setTimeout(_loadActiveLevelPlaylist, _retryTimeout);
/* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */
_retryTimeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retryTimeout);
_retryCount++;
return;
} else {
code = HLSError.MANIFEST_LOADING_IO_ERROR;
txt = "Cannot load M3U8: " + event.text;
}
var hlsError : HLSError = new HLSError(code, _url, txt);
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
};
/** Return the current manifest. **/
public function get levels() : Vector.<Level> {
return _levels;
};
/** Return the stream type. **/
public function get type() : String {
return _type;
};
public function get altAudioTracks() : Vector.<AltAudioTrack> {
return _altAudioTracks;
}
/** Load the manifest file. **/
public function load(url : String) : void {
if(!_urlloader) {
//_urlloader = new URLLoader();
var urlLoaderClass : Class = _hls.URLloader as Class;
_urlloader = (new urlLoaderClass()) as URLLoader;
_urlloader.addEventListener(Event.COMPLETE, _loadCompleteHandler);
_urlloader.addEventListener(ProgressEvent.PROGRESS, _loadProgressHandler);
_urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
}
_close();
_closed = false;
_url = url;
_levels = new Vector.<Level>();
_canStart = false;
_reloadPlaylistTimer = getTimer();
_retryTimeout = 1000;
_retryCount = 0;
_altAudioTracks = null;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADING, url));
_metrics = new HLSLoadMetrics(HLSLoaderTypes.MANIFEST);
_metrics.loading_request_time = getTimer();
if (DataUri.isDataUri(url)) {
CONFIG::LOGGING {
Log.debug("Identified main manifest <" + url + "> as a data URI.");
}
_metrics.loading_begin_time = getTimer();
var data : String = new DataUri(url).extractData();
_metrics.loading_end_time = getTimer();
_parseManifest(data || "");
} else {
_urlloader.load(new URLRequest(url));
}
};
/** loading progress handler, use to determine loading latency **/
private function _loadProgressHandler(event : Event) : void {
if(_metrics.loading_begin_time == 0) {
_metrics.loading_begin_time = getTimer();
}
};
/** Manifest loaded; check and parse it **/
private function _loadCompleteHandler(event : Event) : void {
_metrics.loading_end_time = getTimer();
// successful loading, reset retry counter
_retryTimeout = 1000;
_retryCount = 0;
_parseManifest(String(_urlloader.data));
};
/** parse a playlist **/
private function _parseLevelPlaylist(string : String, url : String, level : int, metrics : HLSLoadMetrics) : void {
if (string != null && string.length != 0) {
// successful loading, reset retry counter
_retryTimeout = 1000;
_retryCount = 0;
CONFIG::LOGGING {
Log.debug("level " + level + " playlist:\n" + string);
}
var frags : Vector.<Fragment> = Manifest.getFragments(string, url, level);
// set fragment and update sequence number range
_levels[level].updateFragments(frags);
_levels[level].targetduration = Manifest.getTargetDuration(string);
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYLIST_DURATION_UPDATED, _levels[level].duration));
}
// Check whether the stream is live or not finished yet
if (Manifest.hasEndlist(string)) {
_type = HLSTypes.VOD;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_ENDLIST, level));
} else {
_type = HLSTypes.LIVE;
/* in order to determine playlist reload timer,
check playback position against playlist duration.
if we are near the edge of a live playlist, reload playlist quickly
to discover quicker new fragments and avoid buffer starvation.
*/
var _reloadInterval : Number = 1000*Math.min((_levels[level].duration - _hls.position)/2,_levels[level].averageduration);
// avoid spamming the server if we are at the edge ... wait 500ms between 2 reload at least
var timeout : Number = Math.max(500, _reloadPlaylistTimer + _reloadInterval - getTimer());
CONFIG::LOGGING {
Log.debug("Level " + level + " Live Playlist parsing finished: reload in " + timeout.toFixed(0) + " ms");
}
_timeoutID = setTimeout(_loadActiveLevelPlaylist, timeout);
}
if (!_canStart) {
_canStart = (_levels[level].fragments.length > 0);
if (_canStart) {
CONFIG::LOGGING {
Log.debug("first level filled with at least 1 fragment, notify event");
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADED, _levels, _metrics));
}
}
metrics.id = _levels[level].start_seqnum;
metrics.id2 = _levels[level].end_seqnum;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADED, metrics));
_manifestLoading = null;
};
/** Parse First Level Playlist **/
private function _parseManifest(string : String) : void {
var hlsError : HLSError;
// Check for M3U8 playlist or manifest.
if (string.indexOf(Manifest.HEADER) == 0) {
// 1 level playlist, create unique level and parse playlist
if (string.indexOf(Manifest.FRAGMENT) > 0) {
var level : Level = new Level();
level.url = _url;
_levels.push(level);
_metrics.parsing_end_time = getTimer();
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels));
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, 0));
CONFIG::LOGGING {
Log.debug("1 Level Playlist, load it");
}
_loadLevel = 0;
_metrics.type = HLSLoaderTypes.LEVEL_MAIN;
_parseLevelPlaylist(string, _url, 0,_metrics);
} else if (string.indexOf(Manifest.LEVEL) > 0) {
CONFIG::LOGGING {
Log.debug("adaptive playlist:\n" + string);
}
// adaptative playlist, extract levels from playlist, get them and parse them
_levels = Manifest.extractLevels(string, _url);
var levelsLength : int = _levels.length;
if (levelsLength == 0) {
hlsError = new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, "No level found in Manifest");
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
}
_metrics.parsing_end_time = getTimer();
_loadLevel = -1;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels));
if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) {
CONFIG::LOGGING {
Log.debug("alternate audio level found");
}
// parse alternate audio tracks
_altAudioTracks = Manifest.extractAltAudioTracks(string, _url);
CONFIG::LOGGING {
if (_altAudioTracks.length > 0) {
Log.debug(_altAudioTracks.length + " alternate audio tracks found");
}
}
}
} else {
// manifest start with correct header, but it does not contain any fragment or level info ...
hlsError = new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, "empty Manifest");
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
}
} else {
hlsError = new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, "Manifest is not a valid M3U8 file");
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
}
};
/** load/reload active M3U8 playlist **/
private function _loadActiveLevelPlaylist() : void {
if (_closed) {
return;
}
_reloadPlaylistTimer = getTimer();
// load active M3U8 playlist only
_manifestLoading = new Manifest();
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, _loadLevel));
_manifestLoading.loadPlaylist(_hls,_levels[_loadLevel].url, _parseLevelPlaylist, _errorHandler, _loadLevel, _type, HLSSettings.flushLiveURLCache);
};
/** When level switch occurs, assess the need of (re)loading new level playlist **/
private function _levelSwitchHandler(event : HLSEvent) : void {
if (_loadLevel != event.level) {
_loadLevel = event.level;
CONFIG::LOGGING {
Log.debug("switch to level " + _loadLevel);
}
if (_type == HLSTypes.LIVE || _levels[_loadLevel].fragments.length == 0) {
_closed = false;
CONFIG::LOGGING {
Log.debug("(re)load Playlist");
}
if(_manifestLoading) {
_manifestLoading.close();
_manifestLoading = null;
}
clearTimeout(_timeoutID);
_timeoutID = setTimeout(_loadActiveLevelPlaylist, 0);
}
}
};
private function _close() : void {
CONFIG::LOGGING {
Log.debug("cancel any manifest load in progress");
}
_closed = true;
clearTimeout(_timeoutID);
try {
_urlloader.close();
if (_manifestLoading) {
_manifestLoading.close();
}
} catch(e : Error) {
}
}
/** When the framework idles out, stop reloading manifest **/
private function _stateHandler(event : HLSEvent) : void {
if (event.state == HLSPlayStates.IDLE) {
_close();
}
};
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.loader {
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.clearTimeout;
import flash.utils.getTimer;
import flash.utils.setTimeout;
import org.mangui.hls.constant.HLSLoaderTypes;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.constant.HLSTypes;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSLoadMetrics;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
import org.mangui.hls.model.Fragment;
import org.mangui.hls.model.Level;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.playlist.DataUri;
import org.mangui.hls.playlist.Manifest;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class LevelLoader {
/** Reference to the hls framework controller. **/
private var _hls : HLS;
/** levels vector. **/
private var _levels : Vector.<Level>;
/** Object that fetches the manifest. **/
private var _urlloader : URLLoader;
/** Link to the M3U8 file. **/
private var _url : String;
/** are all playlists filled ? **/
private var _canStart : Boolean;
/** Timeout ID for reloading live playlists. **/
private var _timeoutID : uint;
/** Streaming type (live, ondemand). **/
private var _type : String;
/** last reload manifest time **/
private var _reloadPlaylistTimer : uint;
/** current load level **/
private var _loadLevel : int;
/** reference to manifest being loaded **/
private var _manifestLoading : Manifest;
/** is this loader closed **/
private var _closed : Boolean = false;
/* playlist retry timeout */
private var _retryTimeout : Number;
private var _retryCount : int;
/* alt audio tracks */
private var _altAudioTracks : Vector.<AltAudioTrack>;
/* manifest load metrics */
private var _metrics : HLSLoadMetrics;
/** Setup the loader. **/
public function LevelLoader(hls : HLS) {
_hls = hls;
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
_levels = new Vector.<Level>();
};
public function dispose() : void {
_close();
if(_urlloader) {
_urlloader.removeEventListener(Event.COMPLETE, _loadCompleteHandler);
_urlloader.removeEventListener(ProgressEvent.PROGRESS, _loadProgressHandler);
_urlloader.removeEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
_urlloader = null;
}
_hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
}
/** Loading failed; return errors. **/
private function _errorHandler(event : ErrorEvent) : void {
var txt : String;
var code : int;
if (event is SecurityErrorEvent) {
code = HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR;
txt = "Cannot load M3U8: crossdomain access denied:" + event.text;
} else if (event is IOErrorEvent && _levels.length && (HLSSettings.manifestLoadMaxRetry == -1 || _retryCount < HLSSettings.manifestLoadMaxRetry)) {
CONFIG::LOGGING {
Log.warn("I/O Error while trying to load Playlist, retry in " + _retryTimeout + " ms");
}
_timeoutID = setTimeout(_loadActiveLevelPlaylist, _retryTimeout);
/* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */
_retryTimeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retryTimeout);
_retryCount++;
return;
} else {
code = HLSError.MANIFEST_LOADING_IO_ERROR;
txt = "Cannot load M3U8: " + event.text;
}
var hlsError : HLSError = new HLSError(code, _url, txt);
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
};
/** Return the current manifest. **/
public function get levels() : Vector.<Level> {
return _levels;
};
/** Return the stream type. **/
public function get type() : String {
return _type;
};
public function get altAudioTracks() : Vector.<AltAudioTrack> {
return _altAudioTracks;
}
/** Load the manifest file. **/
public function load(url : String) : void {
if(!_urlloader) {
//_urlloader = new URLLoader();
var urlLoaderClass : Class = _hls.URLloader as Class;
_urlloader = (new urlLoaderClass()) as URLLoader;
_urlloader.addEventListener(Event.COMPLETE, _loadCompleteHandler);
_urlloader.addEventListener(ProgressEvent.PROGRESS, _loadProgressHandler);
_urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
}
_close();
_closed = false;
_url = url;
_levels = new Vector.<Level>();
_canStart = false;
_reloadPlaylistTimer = getTimer();
_retryTimeout = 1000;
_retryCount = 0;
_altAudioTracks = null;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADING, url));
_metrics = new HLSLoadMetrics(HLSLoaderTypes.MANIFEST);
_metrics.loading_request_time = getTimer();
if (DataUri.isDataUri(url)) {
CONFIG::LOGGING {
Log.debug("Identified main manifest <" + url + "> as a data URI.");
}
_metrics.loading_begin_time = getTimer();
var data : String = new DataUri(url).extractData();
_metrics.loading_end_time = getTimer();
_parseManifest(data || "");
} else {
_urlloader.load(new URLRequest(url));
}
};
/** loading progress handler, use to determine loading latency **/
private function _loadProgressHandler(event : Event) : void {
if(_metrics.loading_begin_time == 0) {
_metrics.loading_begin_time = getTimer();
}
};
/** Manifest loaded; check and parse it **/
private function _loadCompleteHandler(event : Event) : void {
_metrics.loading_end_time = getTimer();
// successful loading, reset retry counter
_retryTimeout = 1000;
_retryCount = 0;
_parseManifest(String(_urlloader.data));
};
/** parse a playlist **/
private function _parseLevelPlaylist(string : String, url : String, level : int, metrics : HLSLoadMetrics) : void {
if (string != null && string.length != 0) {
// successful loading, reset retry counter
_retryTimeout = 1000;
_retryCount = 0;
CONFIG::LOGGING {
Log.debug("level " + level + " playlist:\n" + string);
}
var frags : Vector.<Fragment> = Manifest.getFragments(string, url, level);
// set fragment and update sequence number range
_levels[level].updateFragments(frags);
_levels[level].targetduration = Manifest.getTargetDuration(string);
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYLIST_DURATION_UPDATED, _levels[level].duration));
}
// Check whether the stream is live or not finished yet
if (Manifest.hasEndlist(string)) {
_type = HLSTypes.VOD;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_ENDLIST, level));
} else {
_type = HLSTypes.LIVE;
/* in order to determine playlist reload timer,
check playback position against playlist duration.
if we are near the edge of a live playlist, reload playlist quickly
to discover quicker new fragments and avoid buffer starvation.
*/
var _reloadInterval : Number = 1000*Math.min((_levels[level].duration - _hls.position)/2,_levels[level].averageduration);
// avoid spamming the server if we are at the edge ... wait 500ms between 2 reload at least
var timeout : Number = Math.max(500, _reloadPlaylistTimer + _reloadInterval - getTimer());
CONFIG::LOGGING {
Log.debug("Level " + level + " Live Playlist parsing finished: reload in " + timeout.toFixed(0) + " ms");
}
_timeoutID = setTimeout(_loadActiveLevelPlaylist, timeout);
}
if (!_canStart) {
_canStart = (_levels[level].fragments.length > 0);
if (_canStart) {
CONFIG::LOGGING {
Log.debug("first level filled with at least 1 fragment, notify event");
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADED, _levels, _metrics));
}
}
metrics.id = _levels[level].start_seqnum;
metrics.id2 = _levels[level].end_seqnum;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADED, metrics));
_manifestLoading = null;
};
/** Parse First Level Playlist **/
private function _parseManifest(string : String) : void {
var errorTxt : String = null;
// Check for M3U8 playlist or manifest.
if (string.indexOf(Manifest.HEADER) == 0) {
// 1 level playlist, create unique level and parse playlist
if (string.indexOf(Manifest.FRAGMENT) > 0) {
var level : Level = new Level();
level.url = _url;
_levels.push(level);
_metrics.parsing_end_time = getTimer();
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels));
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, 0));
CONFIG::LOGGING {
Log.debug("1 Level Playlist, load it");
}
_loadLevel = 0;
_metrics.type = HLSLoaderTypes.LEVEL_MAIN;
_parseLevelPlaylist(string, _url, 0,_metrics);
} else if (string.indexOf(Manifest.LEVEL) > 0) {
CONFIG::LOGGING {
Log.debug("adaptive playlist:\n" + string);
}
// adaptative playlist, extract levels from playlist, get them and parse them
_levels = Manifest.extractLevels(string, _url);
if (_levels.length) {
_metrics.parsing_end_time = getTimer();
_loadLevel = -1;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels));
if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) {
CONFIG::LOGGING {
Log.debug("alternate audio level found");
}
// parse alternate audio tracks
_altAudioTracks = Manifest.extractAltAudioTracks(string, _url);
CONFIG::LOGGING {
if (_altAudioTracks.length > 0) {
Log.debug(_altAudioTracks.length + " alternate audio tracks found");
}
}
}
} else {
errorTxt = "No level found in Manifest";
}
} else {
// manifest start with correct header, but it does not contain any fragment or level info ...
errorTxt = "empty Manifest";
}
} else {
errorTxt = "Manifest is not a valid M3U8 file";
}
if(errorTxt) {
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, errorTxt)));
}
};
/** load/reload active M3U8 playlist **/
private function _loadActiveLevelPlaylist() : void {
if (_closed) {
return;
}
_reloadPlaylistTimer = getTimer();
// load active M3U8 playlist only
_manifestLoading = new Manifest();
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, _loadLevel));
_manifestLoading.loadPlaylist(_hls,_levels[_loadLevel].url, _parseLevelPlaylist, _errorHandler, _loadLevel, _type, HLSSettings.flushLiveURLCache);
};
/** When level switch occurs, assess the need of (re)loading new level playlist **/
private function _levelSwitchHandler(event : HLSEvent) : void {
if (_loadLevel != event.level) {
_loadLevel = event.level;
CONFIG::LOGGING {
Log.debug("switch to level " + _loadLevel);
}
if (_type == HLSTypes.LIVE || _levels[_loadLevel].fragments.length == 0) {
_closed = false;
CONFIG::LOGGING {
Log.debug("(re)load Playlist");
}
if(_manifestLoading) {
_manifestLoading.close();
_manifestLoading = null;
}
clearTimeout(_timeoutID);
_timeoutID = setTimeout(_loadActiveLevelPlaylist, 0);
}
}
};
private function _close() : void {
CONFIG::LOGGING {
Log.debug("cancel any manifest load in progress");
}
_closed = true;
clearTimeout(_timeoutID);
try {
_urlloader.close();
if (_manifestLoading) {
_manifestLoading.close();
}
} catch(e : Error) {
}
}
/** When the framework idles out, stop reloading manifest **/
private function _stateHandler(event : HLSEvent) : void {
if (event.state == HLSPlayStates.IDLE) {
_close();
}
};
}
}
|
optimize manifest parsing error handling
|
optimize manifest parsing error handling
|
ActionScript
|
mpl-2.0
|
vidible/vdb-flashls,jlacivita/flashls,hola/flashls,NicolasSiver/flashls,jlacivita/flashls,Boxie5/flashls,vidible/vdb-flashls,loungelogic/flashls,loungelogic/flashls,aevange/flashls,aevange/flashls,hola/flashls,fixedmachine/flashls,mangui/flashls,neilrackett/flashls,neilrackett/flashls,thdtjsdn/flashls,Boxie5/flashls,JulianPena/flashls,Peer5/flashls,aevange/flashls,aevange/flashls,Peer5/flashls,tedconf/flashls,JulianPena/flashls,Peer5/flashls,Corey600/flashls,fixedmachine/flashls,clappr/flashls,clappr/flashls,codex-corp/flashls,NicolasSiver/flashls,Peer5/flashls,tedconf/flashls,mangui/flashls,thdtjsdn/flashls,Corey600/flashls,dighan/flashls,dighan/flashls,codex-corp/flashls
|
1ed3e20ab6ab546984df4d7eeb71ea56cf25bd3a
|
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/layouts/FlexibleFirstChildHorizontalLayout.as
|
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/layouts/FlexibleFirstChildHorizontalLayout.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.IViewport;
import org.apache.flex.core.IViewportModel;
import org.apache.flex.html.supportClasses.Viewport;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The FlexibleFirstChildHorizontalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* horizontally in one row, separating them according to
* CSS layout rules for margin and padding styles. But it
* will size the first child to take up as much or little
* room as possible.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class FlexibleFirstChildHorizontalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function FlexibleFirstChildHorizontalLayout()
{
}
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
host = value as ILayoutChild;
}
private var _viewportModel:IViewportModel;
/**
* The data that describes the viewport used by this layout.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get viewportModel():IViewportModel
{
return _viewportModel;
}
public function set viewportModel(value:IViewportModel):void
{
_viewportModel = value;
}
private var _maxWidth:Number;
/**
* @copy org.apache.flex.core.IBead#maxWidth
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxWidth():Number
{
return _maxWidth;
}
/**
* @private
*/
public function set maxWidth(value:Number):void
{
_maxWidth = value;
}
private var _maxHeight:Number;
/**
* @copy org.apache.flex.core.IBead#maxHeight
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxHeight():Number
{
return _maxHeight;
}
/**
* @private
*/
public function set maxHeight(value:Number):void
{
_maxHeight = value;
}
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParent = layoutParent.contentView;
var hostSizedToContent:Boolean = host.isHeightSizedToContent();
// this layout will use and modify the IViewportMode
var viewport:IViewport = host.getBeadByType(IViewport) as IViewport;
if (viewport) viewportModel = viewport.model;
var n:int = contentView.numElements;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
maxHeight = 0;
var verticalMargins:Array = [];
var xx:Number = layoutParent.resizableView.width;
if (isNaN(xx) || xx <= 0)
return true;
var padding:Object = determinePadding();
// some browsers don't like it when you go all the way to the right edge.
xx -= padding.paddingLeft + padding.paddingRight + 1;
for (var i:int = n - 1; i >= 0; i--)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
margin = ValuesManager.valuesImpl.getValue(child, "margin");
if (margin is Array)
{
if (margin.length == 1)
marginLeft = marginTop = marginRight = marginBottom = margin[0];
else if (margin.length <= 3)
{
marginLeft = marginRight = margin[1];
marginTop = marginBottom = margin[0];
}
else if (margin.length == 4)
{
marginLeft = margin[3];
marginBottom = margin[2];
marginRight = margin[1];
marginTop = margin[0];
}
}
else if (margin == null)
{
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
}
else
{
marginLeft = marginTop = marginBottom = marginRight = margin;
}
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var lastmr:Number;
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
if (marginLeft == "auto")
ml = 0;
else
{
ml = Number(marginLeft);
if (isNaN(ml))
ml = 0;
}
if (marginRight == "auto")
mr = 0;
else
{
mr = Number(marginRight);
if (isNaN(mr))
mr = 0;
}
child.y = mt;
maxHeight = Math.max(maxHeight, mt + child.height + mb);
if (i == 0)
{
child.x = ml;
child.width = xx - mr;
}
else
child.x = xx - child.width - mr;
xx -= child.width + mr + ml;
lastmr = mr;
var valign:Object = ValuesManager.valuesImpl.getValue(child, "vertical-align");
verticalMargins.push({ marginTop: mt, marginBottom: mb, valign: valign });
}
for (i = 0; i < n; i++)
{
var obj:Object = verticalMargins[0]
child = contentView.getElementAt(i) as IUIBase;
if (obj.valign == "middle")
child.y = (maxHeight - child.height) / 2;
else if (valign == "bottom")
child.y = maxHeight - child.height - obj.marginBottom;
else
child.y = obj.marginTop;
}
if (hostSizedToContent)
ILayoutChild(contentView).setHeight(maxHeight, true);
// Only return true if the contentView needs to be larger; that new
// size is stored in the model.
var sizeChanged:Boolean = false;
if (viewportModel != null) {
if (viewportModel.contentHeight < maxHeight) {
viewportModel.contentHeight = maxHeight;
sizeChanged = true;
}
if (viewportModel.contentWidth < xx) {
viewportModel.contentWidth = xx;
sizeChanged = true;
}
} else {
sizeChanged = true;
}
return sizeChanged;
}
// TODO (aharui): utility class or base class
/**
* Determines the top and left padding values, if any, as set by
* padding style values. This includes "padding" for all padding values
* as well as "padding-left" and "padding-top".
*
* Returns an object with paddingLeft and paddingTop properties.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected function determinePadding():Object
{
var paddingLeft:Object;
var paddingTop:Object;
var paddingRight:Object;
var padding:Object = ValuesManager.valuesImpl.getValue(host, "padding");
if (typeof(padding) == "Array")
{
if (padding.length == 1)
paddingLeft = paddingTop = paddingRight = padding[0];
else if (padding.length <= 3)
{
paddingLeft = padding[1];
paddingTop = padding[0];
paddingRight = padding[1];
}
else if (padding.length == 4)
{
paddingLeft = padding[3];
paddingTop = padding[0];
paddingRight = padding[1];
}
}
else if (padding == null)
{
paddingLeft = ValuesManager.valuesImpl.getValue(host, "padding-left");
paddingTop = ValuesManager.valuesImpl.getValue(host, "padding-top");
paddingRight = ValuesManager.valuesImpl.getValue(host, "padding-right");
}
else
{
paddingLeft = paddingTop = paddingRight = padding;
}
var pl:Number = Number(paddingLeft);
var pt:Number = Number(paddingTop);
var pr:Number = Number(paddingRight);
if (isNaN(pl))
pl = 0;
if (isNaN(pt))
pt = 0;
if (isNaN(pr))
pr = 0;
return {paddingLeft:pl, paddingTop:pt, paddingRight:pr};
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.IViewport;
import org.apache.flex.core.IViewportModel;
import org.apache.flex.core.UIMetrics;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.html.supportClasses.Viewport;
import org.apache.flex.utils.BeadMetrics;
/**
* The FlexibleFirstChildHorizontalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* horizontally in one row, separating them according to
* CSS layout rules for margin and padding styles. But it
* will size the first child to take up as much or little
* room as possible.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class FlexibleFirstChildHorizontalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function FlexibleFirstChildHorizontalLayout()
{
}
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
host = value as ILayoutChild;
}
private var _viewportModel:IViewportModel;
/**
* The data that describes the viewport used by this layout.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get viewportModel():IViewportModel
{
return _viewportModel;
}
public function set viewportModel(value:IViewportModel):void
{
_viewportModel = value;
}
private var _maxWidth:Number;
/**
* @copy org.apache.flex.core.IBead#maxWidth
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxWidth():Number
{
return _maxWidth;
}
/**
* @private
*/
public function set maxWidth(value:Number):void
{
_maxWidth = value;
}
private var _maxHeight:Number;
/**
* @copy org.apache.flex.core.IBead#maxHeight
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxHeight():Number
{
return _maxHeight;
}
/**
* @private
*/
public function set maxHeight(value:Number):void
{
_maxHeight = value;
}
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParent = layoutParent.contentView;
var hostSizedToContent:Boolean = host.isHeightSizedToContent();
// this layout will use and modify the IViewportMode
var viewport:IViewport = host.getBeadByType(IViewport) as IViewport;
if (viewport) viewportModel = viewport.model;
var n:int = contentView.numElements;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
maxHeight = 0;
var verticalMargins:Array = [];
var xx:Number = layoutParent.resizableView.width;
if (isNaN(xx) || xx <= 0)
return true;
var uiMetrics:UIMetrics = BeadMetrics.getMetrics(layoutParent.resizableView);
xx -= uiMetrics.left + uiMetrics.right + 1; // some browsers won't layout to the edge
for (var i:int = n - 1; i >= 0; i--)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
margin = ValuesManager.valuesImpl.getValue(child, "margin");
if (margin is Array)
{
if (margin.length == 1)
marginLeft = marginTop = marginRight = marginBottom = margin[0];
else if (margin.length <= 3)
{
marginLeft = marginRight = margin[1];
marginTop = marginBottom = margin[0];
}
else if (margin.length == 4)
{
marginLeft = margin[3];
marginBottom = margin[2];
marginRight = margin[1];
marginTop = margin[0];
}
}
else if (margin == null)
{
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
}
else
{
marginLeft = marginTop = marginBottom = marginRight = margin;
}
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var lastmr:Number;
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
if (marginLeft == "auto")
ml = 0;
else
{
ml = Number(marginLeft);
if (isNaN(ml))
ml = 0;
}
if (marginRight == "auto")
mr = 0;
else
{
mr = Number(marginRight);
if (isNaN(mr))
mr = 0;
}
child.y = mt;
maxHeight = Math.max(maxHeight, mt + child.height + mb);
if (i == 0)
{
child.x = ml;
child.width = xx - mr;
}
else
child.x = xx - child.width - mr;
xx -= child.width + mr + ml;
lastmr = mr;
var valign:Object = ValuesManager.valuesImpl.getValue(child, "vertical-align");
verticalMargins.push({ marginTop: mt, marginBottom: mb, valign: valign });
}
for (i = 0; i < n; i++)
{
var obj:Object = verticalMargins[0]
child = contentView.getElementAt(i) as IUIBase;
if (obj.valign == "middle")
child.y = (maxHeight - child.height) / 2;
else if (valign == "bottom")
child.y = maxHeight - child.height - obj.marginBottom;
else
child.y = obj.marginTop;
}
if (hostSizedToContent)
ILayoutChild(contentView).setHeight(maxHeight, true);
// Only return true if the contentView needs to be larger; that new
// size is stored in the model.
var sizeChanged:Boolean = false;
if (viewportModel != null) {
if (viewportModel.contentHeight < maxHeight) {
viewportModel.contentHeight = maxHeight;
sizeChanged = true;
}
if (viewportModel.contentWidth < xx) {
viewportModel.contentWidth = xx;
sizeChanged = true;
}
} else {
sizeChanged = true;
}
return sizeChanged;
}
}
}
|
upgrade to use BeadMetrics
|
upgrade to use BeadMetrics
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
1dafbc3a45ec596f721c5e3c22d6cf7ec7f9ffbb
|
src/battlecode/client/viewer/render/DrawState.as
|
src/battlecode/client/viewer/render/DrawState.as
|
package battlecode.client.viewer.render {
import battlecode.common.MapLocation;
import battlecode.common.RobotType;
import battlecode.common.Team;
import battlecode.serial.RoundDelta;
import battlecode.serial.RoundStats;
import battlecode.world.GameMap;
import battlecode.world.signals.*;
public class DrawState extends DefaultSignalHandler {
// state
private var mines:Array; // Team[][]
private var neutralEncampments:Object;
private var encampments:Object;
private var groundRobots:Object;
// stats
private var aPoints:Number;
private var bPoints:Number;
private var aGatheredPoints:Number;
private var bGatheredPoints:Number;
private var roundNum:uint;
// immutables
private var map:GameMap;
private var origin:MapLocation;
public function DrawState(map:GameMap) {
neutralEncampments = new Object();
encampments = new Object();
groundRobots = new Object();
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = null;
}
}
aPoints = 0;
bPoints = 0;
aGatheredPoints = 0;
bGatheredPoints = 0;
roundNum = 1;
this.map = map;
this.origin = map.getOrigin();
}
///////////////////////////////////////////////////////
///////////////// PROPERTY GETTERS ////////////////////
///////////////////////////////////////////////////////
public function getMines():Array {
return mines;
}
public function getNeutralEncampments():Object {
return neutralEncampments;
}
public function getEncampments():Object {
return encampments
}
public function getGroundRobots():Object {
return groundRobots;
}
public function getPoints(team:String):uint {
return (team == Team.A) ? aPoints : bPoints;
}
///////////////////////////////////////////////////////
/////////////////// CORE FUNCTIONS ////////////////////
///////////////////////////////////////////////////////
private function copyStateFrom(state:DrawState):void {
var a:*;
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = state.mines[i][j];
}
}
neutralEncampments = new Object();
for (a in state.neutralEncampments) {
neutralEncampments[a] = state.neutralEncampments[a].clone();
}
encampments = new Object();
for (a in state.encampments) {
encampments[a] = state.encampments[a].clone();
}
groundRobots = new Object();
for (a in state.groundRobots) {
groundRobots[a] = state.groundRobots[a].clone();
}
roundNum = state.roundNum;
}
public function clone():DrawState {
var state:DrawState = new DrawState(map);
state.copyStateFrom(this);
return state;
}
public function applyDelta(delta:RoundDelta):void {
updateRound();
for each (var signal:Signal in delta.getSignals()) {
applySignal(signal);
}
processEndOfRound();
}
public function applySignal(signal:Signal):void {
if (signal != null) signal.accept(this);
}
public function applyStats(stats:RoundStats):void {
aPoints = stats.getPoints(Team.A);
bPoints = stats.getPoints(Team.B);
aGatheredPoints = stats.getGatheredPoints(Team.A);
bGatheredPoints = stats.getGatheredPoints(Team.B);
}
public function updateRound():void {
var a:*, i:uint, j:uint;
var o:DrawRobot;
for (a in groundRobots) {
o = groundRobots[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete groundRobots[a];
}
}
for (a in encampments) {
o = encampments[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete encampments[a];
}
}
}
private function processEndOfRound():void {
roundNum++;
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getRobot(id:uint):DrawRobot {
if (groundRobots[id]) return groundRobots[id] as DrawRobot;
if (encampments[id]) return encampments[id] as DrawRobot;
return null;
}
private function removeRobot(id:uint):void {
if (groundRobots[id]) delete groundRobots[id];
if (encampments[id]) delete encampments[id];
}
private function translateCoordinates(loc:MapLocation):MapLocation {
return new MapLocation(loc.getX() - origin.getX(), loc.getY() - origin.getY());
}
///////////////////////////////////////////////////////
/////////////////// SIGNAL HANDLERS ///////////////////
///////////////////////////////////////////////////////
override public function visitAttackSignal(s:AttackSignal):* {
getRobot(s.getRobotID()).attack(s.getTargetLoc());
}
override public function visitBroadcastSignal(s:BroadcastSignal):* {
getRobot(s.getRobotID()).broadcast();
}
override public function visitCaptureSignal(s:CaptureSignal):* {
var o:DrawRobot = neutralEncampments[s.getLocation()];
if (o) {
if (o.parent) {
o.parent.removeChild(o);
}
delete neutralEncampments[s.getLocation()];
}
}
override public function visitDeathSignal(s:DeathSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
robot.destroyUnit();
}
override public function visitEnergonChangeSignal(s:EnergonChangeSignal):* {
}
override public function visitFluxChangeSignal(s:FluxChangeSignal):* {
}
override public function visitIndicatorStringSignal(s:IndicatorStringSignal):* {
getRobot(s.getRobotID()).setIndicatorString(s.getIndicatorString(), s.getIndex());
}
override public function visitMineSignal(s:MineSignal):* {
var loc:MapLocation = translateCoordinates(s.getLocation());
if (s.isBirth()) {
mines[loc.getX()][loc.getY()] = s.getTeam();
} else {
mines[loc.getX()][loc.getY()] = null;
}
}
override public function visitMovementSignal(s:MovementSignal):* {
getRobot(s.getRobotID()).moveToLocation(s.getTargetLoc());
}
override public function visitNodeBirthSignal(s:NodeBirthSignal):* {
var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
encampment.setLocation(s.getLocation());
neutralEncampments[s.getLocation()] = encampment;
}
override public function visitSpawnSignal(s:SpawnSignal):* {
var robot:DrawRobot = new DrawRobot(s.getRobotID(), s.getRobotType(), s.getTeam());
robot.setLocation(s.getLocation());
groundRobots[s.getRobotID()] = robot;
}
}
}
|
package battlecode.client.viewer.render {
import battlecode.common.MapLocation;
import battlecode.common.RobotType;
import battlecode.common.Team;
import battlecode.serial.RoundDelta;
import battlecode.serial.RoundStats;
import battlecode.world.GameMap;
import battlecode.world.signals.*;
public class DrawState extends DefaultSignalHandler {
// state
private var mines:Array; // Team[][]
private var neutralEncampments:Object;
private var encampments:Object;
private var groundRobots:Object;
// stats
private var aPoints:Number;
private var bPoints:Number;
private var aGatheredPoints:Number;
private var bGatheredPoints:Number;
private var roundNum:uint;
// immutables
private var map:GameMap;
private var origin:MapLocation;
public function DrawState(map:GameMap) {
neutralEncampments = new Object();
encampments = new Object();
groundRobots = new Object();
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = null;
}
}
aPoints = 0;
bPoints = 0;
aGatheredPoints = 0;
bGatheredPoints = 0;
roundNum = 1;
this.map = map;
this.origin = map.getOrigin();
}
///////////////////////////////////////////////////////
///////////////// PROPERTY GETTERS ////////////////////
///////////////////////////////////////////////////////
public function getMines():Array {
return mines;
}
public function getNeutralEncampments():Object {
return neutralEncampments;
}
public function getEncampments():Object {
return encampments
}
public function getGroundRobots():Object {
return groundRobots;
}
public function getPoints(team:String):uint {
return (team == Team.A) ? aPoints : bPoints;
}
///////////////////////////////////////////////////////
/////////////////// CORE FUNCTIONS ////////////////////
///////////////////////////////////////////////////////
private function copyStateFrom(state:DrawState):void {
var a:*;
mines = new Array();
for (var i:int = 0; i < map.getWidth(); i++) {
mines[i] = new Array();
for (var j:int = 0; j < map.getHeight(); j++) {
mines[i][j] = state.mines[i][j];
}
}
neutralEncampments = new Object();
for (a in state.neutralEncampments) {
neutralEncampments[a] = state.neutralEncampments[a].clone();
}
encampments = new Object();
for (a in state.encampments) {
encampments[a] = state.encampments[a].clone();
}
groundRobots = new Object();
for (a in state.groundRobots) {
groundRobots[a] = state.groundRobots[a].clone();
}
roundNum = state.roundNum;
}
public function clone():DrawState {
var state:DrawState = new DrawState(map);
state.copyStateFrom(this);
return state;
}
public function applyDelta(delta:RoundDelta):void {
updateRound();
for each (var signal:Signal in delta.getSignals()) {
applySignal(signal);
}
processEndOfRound();
}
public function applySignal(signal:Signal):void {
if (signal != null) signal.accept(this);
}
public function applyStats(stats:RoundStats):void {
aPoints = stats.getPoints(Team.A);
bPoints = stats.getPoints(Team.B);
aGatheredPoints = stats.getGatheredPoints(Team.A);
bGatheredPoints = stats.getGatheredPoints(Team.B);
}
public function updateRound():void {
var a:*, i:uint, j:uint;
var o:DrawRobot;
for (a in groundRobots) {
o = groundRobots[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete groundRobots[a];
}
}
for (a in encampments) {
o = encampments[a] as DrawRobot;
o.updateRound();
if (!o.isAlive()) {
if (o.parent) {
o.parent.removeChild(o);
}
delete encampments[a];
}
}
}
private function processEndOfRound():void {
roundNum++;
}
///////////////////////////////////////////////////////
////////////// PRIVATE HELPER FUNCTIONS ///////////////
///////////////////////////////////////////////////////
private function getRobot(id:uint):DrawRobot {
if (groundRobots[id]) return groundRobots[id] as DrawRobot;
if (encampments[id]) return encampments[id] as DrawRobot;
return null;
}
private function removeRobot(id:uint):void {
if (groundRobots[id]) delete groundRobots[id];
if (encampments[id]) delete encampments[id];
}
private function translateCoordinates(loc:MapLocation):MapLocation {
return new MapLocation(loc.getX() - origin.getX(), loc.getY() - origin.getY());
}
///////////////////////////////////////////////////////
/////////////////// SIGNAL HANDLERS ///////////////////
///////////////////////////////////////////////////////
override public function visitBroadcastSignal(s:BroadcastSignal):* {
getRobot(s.getRobotID()).broadcast();
}
override public function visitCaptureSignal(s:CaptureSignal):* {
var o:DrawRobot = neutralEncampments[s.getLocation()];
if (o) {
if (o.parent) {
o.parent.removeChild(o);
}
delete neutralEncampments[s.getLocation()];
}
}
override public function visitDeathSignal(s:DeathSignal):* {
var robot:DrawRobot = getRobot(s.getRobotID());
robot.destroyUnit();
}
override public function visitEnergonChangeSignal(s:EnergonChangeSignal):* {
// TODO
}
override public function visitFluxChangeSignal(s:FluxChangeSignal):* {
// TODO
}
override public function visitIndicatorStringSignal(s:IndicatorStringSignal):* {
getRobot(s.getRobotID()).setIndicatorString(s.getIndicatorString(), s.getIndex());
}
override public function visitMineSignal(s:MineSignal):* {
var loc:MapLocation = translateCoordinates(s.getLocation());
if (s.isBirth()) {
mines[loc.getX()][loc.getY()] = s.getTeam();
} else {
mines[loc.getX()][loc.getY()] = null;
}
}
override public function visitMovementSignal(s:MovementSignal):* {
getRobot(s.getRobotID()).moveToLocation(s.getTargetLoc());
}
override public function visitNodeBirthSignal(s:NodeBirthSignal):* {
var encampment:DrawRobot = new DrawRobot(0, RobotType.ENCAMPMENT, Team.NEUTRAL);
encampment.setLocation(s.getLocation());
neutralEncampments[s.getLocation()] = encampment;
}
override public function visitSpawnSignal(s:SpawnSignal):* {
var robot:DrawRobot = new DrawRobot(s.getRobotID(), s.getRobotType(), s.getTeam());
robot.setLocation(s.getLocation());
groundRobots[s.getRobotID()] = robot;
}
}
}
|
remove attack animation
|
remove attack animation
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
e574b889ebc1be9e07e8e1d775d2824e4f26e4b0
|
krew-framework/krewfw/builtin_actor/display/KrewMovieClip.as
|
krew-framework/krewfw/builtin_actor/display/KrewMovieClip.as
|
package krewfw.builtin_actor.display {
import starling.display.Image;
import krewfw.core.KrewActor;
//------------------------------------------------------------
public class KrewMovieClip extends KrewActor {
protected var _movieImage:Image;
private var _movieInfoList:Array = null;
private var _frameCount:int = 0;
private var _framePlayTime:Number = 0;
//------------------------------------------------------------
public function KrewMovieClip() {}
/**
* Set up frame animation info.
* Please call after init().
*
* @param infoList List of [imageName, durationSec]. Example:
* [
* ['frame_1', 0.1],
* ['frame_2', 0.1],
* ['frame_3', 0.1],
* ...
* ]
*/
public function setupMovieClip(infoList:Array, width:Number, height:Number,
x:Number=0, y:Number=0):void
{
_movieInfoList = infoList;
var imageName:String = _movieInfoList[0][0];
_movieImage = getImage(imageName);
addImage(_movieImage, width, height, x, y);
_frameCount = 0;
}
public function setRandomFrame():void {
if (!_movieInfoList) { return; }
if (_movieInfoList.length == 0) { return; }
_frameCount = krew.randInt(_movieInfoList.length);
}
public override function update(passedTime:Number):void {
super.update(passedTime);
_updateMovieFrame(passedTime);
}
private function _updateMovieFrame(passedTime:Number):void {
if (!_movieInfoList) { return; }
if (_movieInfoList.length == 0) { return; }
var nextDuration:Number = _movieInfoList[_frameCount][1];
_framePlayTime += passedTime;
if (_framePlayTime > nextDuration) {
_framePlayTime -= nextDuration;
++_frameCount;
if (_frameCount >= _movieInfoList.length) { _frameCount = 0; }
var imageName:String = _movieInfoList[_frameCount][0];
changeImage(_movieImage, imageName);
}
}
}
}
|
package krewfw.builtin_actor.display {
import starling.display.Image;
import krewfw.core.KrewActor;
//------------------------------------------------------------
public class KrewMovieClip extends KrewActor {
protected var _movieImage:Image;
private var _movieInfoList:Array = null;
private var _frameCount:int = 0;
private var _framePlayTime:Number = 0;
//------------------------------------------------------------
public function KrewMovieClip() {}
/**
* Set up frame animation info.
* Please call after init().
*
* @param infoList List of [imageName, durationSec]. Example:
* <pre>
* [
* ['frame_1', 0.1],
* ['frame_2', 0.1],
* ['frame_3', 0.1],
* ...
* ]
* </pre>
*/
public function setUpMovieClip(infoList:Array, width:Number, height:Number,
x:Number=0, y:Number=0):void
{
_movieInfoList = infoList;
var imageName:String = _movieInfoList[0][0];
_movieImage = getImage(imageName);
addImage(_movieImage, width, height, x, y);
_frameCount = 0;
}
public function changeClip(newInfoList:Array):void {
_movieInfoList = newInfoList;
_frameCount = 0;
_framePlayTime = 0;
var imageName:String = _movieInfoList[_frameCount][0];
changeImage(_movieImage, imageName);
}
public function setRandomFrame():void {
if (!_movieInfoList) { return; }
if (_movieInfoList.length == 0) { return; }
_frameCount = krew.randInt(_movieInfoList.length);
}
public override function update(passedTime:Number):void {
super.update(passedTime);
_updateMovieFrame(passedTime);
}
private function _updateMovieFrame(passedTime:Number):void {
if (!_movieInfoList) { return; }
if (_movieInfoList.length <= 1) { return; }
var nextDuration:Number = _movieInfoList[_frameCount][1];
_framePlayTime += passedTime;
if (_framePlayTime > nextDuration) {
_framePlayTime -= nextDuration;
++_frameCount;
if (_frameCount >= _movieInfoList.length) { _frameCount = 0; }
var imageName:String = _movieInfoList[_frameCount][0];
changeImage(_movieImage, imageName);
}
}
}
}
|
Update KrewMovieClip
|
Update KrewMovieClip
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
c275fe92625da7471dd3b2613fda9a2d7f17536e
|
dolly-framework/src/test/actionscript/dolly/CopierTest.as
|
dolly-framework/src/test/actionscript/dolly/CopierTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.ClassLevelCopyable;
import dolly.data.ClassLevelCopyableCloneable;
import dolly.data.PropertyLevelCopyable;
import dolly.data.PropertyLevelCopyableCloneable;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class CopierTest {
private var classLevelCopyable:ClassLevelCopyable;
private var classLevelCopyableType:Type;
private var classLevelCopyableCloneable:ClassLevelCopyableCloneable;
private var classLevelCopyableCloneableType:Type;
private var propertyLevelCopyable:PropertyLevelCopyable;
private var propertyLevelCopyableType:Type;
private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable;
private var propertyLevelCopyableCloneableType:Type;
[Before]
public function before():void {
classLevelCopyable = new ClassLevelCopyable();
classLevelCopyable.property1 = "value 1";
classLevelCopyable.property2 = "value 2";
classLevelCopyable.property3 = "value 3";
classLevelCopyable.writableField = "value 4";
classLevelCopyableType = Type.forInstance(classLevelCopyable);
classLevelCopyableCloneable = new ClassLevelCopyableCloneable();
classLevelCopyableCloneable.property1 = "value 1";
classLevelCopyableCloneable.property2 = "value 2";
classLevelCopyableCloneable.property3 = "value 3";
classLevelCopyableCloneable.writableField = "value 4";
classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable);
propertyLevelCopyable = new PropertyLevelCopyable();
propertyLevelCopyable.property1 = "value 1";
propertyLevelCopyable.property2 = "value 2";
propertyLevelCopyable.property3 = "value 3";
propertyLevelCopyable.writableField = "value 4";
propertyLevelCopyableType = Type.forInstance(propertyLevelCopyable);
propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable();
propertyLevelCopyableCloneable.property1 = "value 1";
propertyLevelCopyableCloneable.property2 = "value 2";
propertyLevelCopyableCloneable.property3 = "value 3";
propertyLevelCopyableCloneable.writableField = "value 4";
propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable);
}
[After]
public function after():void {
classLevelCopyable = null;
classLevelCopyableType = null;
classLevelCopyableCloneable = null;
classLevelCopyableCloneableType = null;
propertyLevelCopyable = null;
propertyLevelCopyableType = null;
propertyLevelCopyableCloneable = null;
propertyLevelCopyableCloneableType = null;
}
[Test]
public function testGetCopyableFieldsForTypeClassLevelCopyable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableType);
assertNotNull(copyableFields);
assertEquals(4, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
assertNotNull(copyableFields[3]);
}
[Test]
public function testGetCopyableFieldsForTypeClassLevelCopyableCloneable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableCloneableType);
assertNotNull(copyableFields);
assertEquals(4, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
assertNotNull(copyableFields[3]);
}
[Test]
public function testGetCopyableFieldsForTypePropertyLevelCopyable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(propertyLevelCopyableType);
assertNotNull(copyableFields);
assertEquals(3, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
}
[Test]
public function testGetCopyableFieldsForTypePropertyLevelCopyableCloneable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(propertyLevelCopyableCloneableType);
assertNotNull(copyableFields);
assertEquals(3, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
}
[Test]
public function testCopyWithClassLevelMetadata():void {
const copy1:ClassLevelCopyable = Copier.copy(classLevelCopyable);
assertNotNull(copy1);
assertNotNull(copy1.property1);
assertEquals(copy1.property1, classLevelCopyable.property1);
assertNotNull(copy1.property2);
assertEquals(copy1.property2, classLevelCopyable.property2);
assertNotNull(copy1.property3);
assertEquals(copy1.property3, classLevelCopyable.property3);
assertNotNull(copy1.writableField);
assertEquals(copy1.writableField, classLevelCopyable.writableField);
const copy2:ClassLevelCopyableCloneable = Copier.copy(classLevelCopyableCloneable);
assertNotNull(copy2);
assertNotNull(copy2.property1);
assertEquals(copy2.property1, classLevelCopyable.property1);
assertNotNull(copy2.property2);
assertEquals(copy2.property2, classLevelCopyable.property2);
assertNotNull(copy2.property3);
assertEquals(copy2.property3, classLevelCopyable.property3);
assertNotNull(copy2.writableField);
assertEquals(copy2.writableField, classLevelCopyable.writableField);
}
[Test]
public function testCopyWithPropertyLevelMetadata():void {
const copy1:PropertyLevelCopyable = Copier.copy(propertyLevelCopyable);
assertNotNull(copy1);
assertNull(copy1.property1);
assertNotNull(copy1.property2);
assertEquals(copy1.property2, classLevelCopyable.property2);
assertNotNull(copy1.property3);
assertEquals(copy1.property3, classLevelCopyable.property3);
assertNotNull(copy1.writableField);
assertEquals(copy1.writableField, classLevelCopyable.writableField);
const copy2:PropertyLevelCopyableCloneable = Copier.copy(propertyLevelCopyableCloneable);
assertNotNull(copy2);
assertNull(copy2.property1);
assertNotNull(copy2.property2);
assertEquals(copy2.property2, classLevelCopyable.property2);
assertNotNull(copy2.property3);
assertEquals(copy2.property3, classLevelCopyable.property3);
assertNotNull(copy2.writableField);
assertEquals(copy2.writableField, classLevelCopyable.writableField);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.ClassLevelCopyable;
import dolly.data.ClassLevelCopyableCloneable;
import dolly.data.PropertyLevelCopyable;
import dolly.data.PropertyLevelCopyableCloneable;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class CopierTest {
private var classLevelCopyable:ClassLevelCopyable;
private var classLevelCopyableType:Type;
private var classLevelCopyableCloneable:ClassLevelCopyableCloneable;
private var classLevelCopyableCloneableType:Type;
private var propertyLevelCopyable:PropertyLevelCopyable;
private var propertyLevelCopyableType:Type;
private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable;
private var propertyLevelCopyableCloneableType:Type;
[Before]
public function before():void {
classLevelCopyable = new ClassLevelCopyable();
classLevelCopyable.property1 = "value 1";
classLevelCopyable.property2 = "value 2";
classLevelCopyable.property3 = "value 3";
classLevelCopyable.writableField = "value 4";
classLevelCopyableType = Type.forInstance(classLevelCopyable);
classLevelCopyableCloneable = new ClassLevelCopyableCloneable();
classLevelCopyableCloneable.property1 = "value 1";
classLevelCopyableCloneable.property2 = "value 2";
classLevelCopyableCloneable.property3 = "value 3";
classLevelCopyableCloneable.writableField = "value 4";
classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable);
propertyLevelCopyable = new PropertyLevelCopyable();
propertyLevelCopyable.property1 = "value 1";
propertyLevelCopyable.property2 = "value 2";
propertyLevelCopyable.property3 = "value 3";
propertyLevelCopyable.writableField = "value 4";
propertyLevelCopyableType = Type.forInstance(propertyLevelCopyable);
propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable();
propertyLevelCopyableCloneable.property1 = "value 1";
propertyLevelCopyableCloneable.property2 = "value 2";
propertyLevelCopyableCloneable.property3 = "value 3";
propertyLevelCopyableCloneable.writableField = "value 4";
propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable);
}
[After]
public function after():void {
classLevelCopyable = null;
classLevelCopyableType = null;
classLevelCopyableCloneable = null;
classLevelCopyableCloneableType = null;
propertyLevelCopyable = null;
propertyLevelCopyableType = null;
propertyLevelCopyableCloneable = null;
propertyLevelCopyableCloneableType = null;
}
[Test]
public function testGetCopyableFieldsForTypeClassLevelCopyable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableType);
assertNotNull(copyableFields);
assertEquals(4, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
assertNotNull(copyableFields[3]);
}
[Test]
public function testGetCopyableFieldsForTypeClassLevelCopyableCloneable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(classLevelCopyableCloneableType);
assertNotNull(copyableFields);
assertEquals(4, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
assertNotNull(copyableFields[3]);
}
[Test]
public function testGetCopyableFieldsForTypePropertyLevelCopyable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(propertyLevelCopyableType);
assertNotNull(copyableFields);
assertEquals(3, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
}
[Test]
public function testGetCopyableFieldsForTypePropertyLevelCopyableCloneable():void {
const copyableFields:Vector.<Field> = Copier.getCopyableFieldsForType(propertyLevelCopyableCloneableType);
assertNotNull(copyableFields);
assertEquals(3, copyableFields.length);
assertNotNull(copyableFields[0]);
assertNotNull(copyableFields[1]);
assertNotNull(copyableFields[2]);
}
[Test]
public function testCopyClassLevelCopyable():void {
const copy:ClassLevelCopyable = Copier.copy(classLevelCopyable);
assertNotNull(copy);
assertNotNull(copy.property1);
assertEquals(copy.property1, classLevelCopyable.property1);
assertNotNull(copy.property2);
assertEquals(copy.property2, classLevelCopyable.property2);
assertNotNull(copy.property3);
assertEquals(copy.property3, classLevelCopyable.property3);
assertNotNull(copy.writableField);
assertEquals(copy.writableField, classLevelCopyable.writableField);
}
[Test]
public function testCopyClassLevelCopyableCloneable():void {
const copy:ClassLevelCopyableCloneable = Copier.copy(classLevelCopyableCloneable);
assertNotNull(copy);
assertNotNull(copy.property1);
assertEquals(copy.property1, classLevelCopyable.property1);
assertNotNull(copy.property2);
assertEquals(copy.property2, classLevelCopyable.property2);
assertNotNull(copy.property3);
assertEquals(copy.property3, classLevelCopyable.property3);
assertNotNull(copy.writableField);
assertEquals(copy.writableField, classLevelCopyable.writableField);
}
[Test]
public function testCopyWithPropertyLevelMetadata():void {
const copy1:PropertyLevelCopyable = Copier.copy(propertyLevelCopyable);
assertNotNull(copy1);
assertNull(copy1.property1);
assertNotNull(copy1.property2);
assertEquals(copy1.property2, classLevelCopyable.property2);
assertNotNull(copy1.property3);
assertEquals(copy1.property3, classLevelCopyable.property3);
assertNotNull(copy1.writableField);
assertEquals(copy1.writableField, classLevelCopyable.writableField);
const copy2:PropertyLevelCopyableCloneable = Copier.copy(propertyLevelCopyableCloneable);
assertNotNull(copy2);
assertNull(copy2.property1);
assertNotNull(copy2.property2);
assertEquals(copy2.property2, classLevelCopyable.property2);
assertNotNull(copy2.property3);
assertEquals(copy2.property3, classLevelCopyable.property3);
assertNotNull(copy2.writableField);
assertEquals(copy2.writableField, classLevelCopyable.writableField);
}
}
}
|
Split method "testCopyWithClassLevelMetadata" to a few.
|
Split method "testCopyWithClassLevelMetadata" to a few.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
66a5aab858c1a12e145f69d267b5cc4cbddf6e4b
|
src/model/AnimationDataProxy.as
|
src/model/AnimationDataProxy.as
|
package model
{
import dragonBones.objects.AnimationData;
import dragonBones.objects.ArmatureData;
import dragonBones.objects.MovementBoneData;
import dragonBones.objects.MovementData;
import dragonBones.objects.XMLDataParser;
import dragonBones.utils.ConstValues;
import dragonBones.utils.dragonBones_internal;
import flash.events.Event;
import message.MessageDispatcher;
import mx.collections.XMLListCollection;
use namespace dragonBones_internal;
/**
* Manage selected animation data
*/
public class AnimationDataProxy
{
public var movementsMC:XMLListCollection;
private var _xml:XML;
private var _movementsXMLList:XMLList;
private var _movementXML:XML;
private var _movementBonesXMLList:XMLList;
private var _movementBoneXML:XML;
public function get animationName():String
{
return _xml?_xml.attribute(ConstValues.A_NAME):"";
}
public function get movementName():String
{
return _movementXML?_movementXML.attribute(ConstValues.A_NAME):"";
}
public function get boneName():String
{
return _movementBoneXML?_movementBoneXML.attribute(ConstValues.A_NAME):"";
}
public function get durationTo():Number
{
if(!_movementXML)
{
return -1;
}
return int(_movementXML.attribute(ConstValues.A_DURATION_TO)) / ImportDataProxy.getInstance().skeletonData.frameRate;
}
public function set durationTo(value:Number):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_DURATION_TO] = Math.round(value * ImportDataProxy.getInstance().skeletonData.frameRate);
updateMovement();
}
}
public function get durationTween():Number
{
if(_movementXML?int(_movementXML.attribute(ConstValues.A_DURATION)) == 1:true)
{
return -1;
}
return int(_movementXML.attribute(ConstValues.A_DURATION_TWEEN)) / ImportDataProxy.getInstance().skeletonData.frameRate;
}
public function set durationTween(value:Number):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_DURATION_TWEEN] = Math.round(value * ImportDataProxy.getInstance().skeletonData.frameRate);
updateMovement();
}
}
public function get loop():Boolean
{
return _movementXML?Boolean(int(_movementXML.attribute(ConstValues.A_LOOP)) == 1):false;
}
public function set loop(value:Boolean):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_LOOP] = value?1:0;
updateMovement();
}
}
public function get tweenEasing():Number
{
return _movementXML?Number(_movementXML.attribute(ConstValues.A_TWEEN_EASING)):-1.1;
}
public function set tweenEasing(value:Number):void
{
if(_movementXML)
{
if(value<-1)
{
_movementXML.@[ConstValues.A_TWEEN_EASING] = NaN;
}
else
{
_movementXML.@[ConstValues.A_TWEEN_EASING] = value;
}
updateMovement();
}
}
public function get boneScale():Number
{
if(!_movementBoneXML || int(_movementXML.attribute(ConstValues.A_DURATION)) < 2)
{
return NaN;
}
return Number(_movementBoneXML.attribute(ConstValues.A_MOVEMENT_SCALE)) * 100;
}
public function set boneScale(value:Number):void
{
if(_movementBoneXML)
{
_movementBoneXML.@[ConstValues.A_MOVEMENT_SCALE] = value * 0.01;
updateMovementBone();
}
}
public function get boneDelay():Number
{
if(!_movementBoneXML || int(_movementXML.attribute(ConstValues.A_DURATION)) < 2)
{
return NaN;
}
return Number(_movementBoneXML.attribute(ConstValues.A_MOVEMENT_DELAY))* 100;
}
public function set boneDelay(value:Number):void
{
if(_movementBoneXML)
{
_movementBoneXML.@[ConstValues.A_MOVEMENT_DELAY] = value * 0.01;
updateMovementBone();
}
}
public function AnimationDataProxy()
{
movementsMC = new XMLListCollection();
}
internal function setData(xml:XML):void
{
_xml = xml;
if(_xml)
{
_movementsXMLList = _xml.elements(ConstValues.MOVEMENT);
}
else
{
_movementsXMLList = null;
}
movementsMC.source = _movementsXMLList;
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_ANIMATION_DATA, animationName);
changeMovement();
}
public function changeMovement(movementName:String = null, isChangedByArmature:Boolean = false):void
{
_movementXML = ImportDataProxy.getElementByName(_movementsXMLList, movementName, true);
if(_movementXML)
{
_movementBonesXMLList = _movementXML.elements(ConstValues.BONE);
}
else
{
_movementBonesXMLList = null;
}
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_MOVEMENT_DATA, this.movementName, isChangedByArmature);
changeMovementBone(ImportDataProxy.getInstance().armatureDataProxy.boneName);
}
public function changeMovementBone(boneName:String = null):void
{
var movementBoneXML:XML = ImportDataProxy.getElementByName(_movementBonesXMLList, boneName, true);
if(movementBoneXML == _movementBoneXML)
{
return;
}
_movementBoneXML = movementBoneXML;
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_MOVEMENT_BONE_DATA , this.boneName);
}
internal function updateBoneParent(boneName:String):void
{
if(_xml)
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var armatureData:ArmatureData = ImportDataProxy.getInstance().skeletonData.getArmatureData(animationName);
XMLDataParser.parseAnimationData(_xml, animationData, armatureData);
}
}
private function updateMovement():void
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var movementData:MovementData = animationData.getMovementData(movementName);
movementData.durationTo = durationTo;
movementData.durationTween = durationTween;
movementData.loop = loop;
movementData.tweenEasing = tweenEasing;
if(!ImportDataProxy.getInstance().isExportedSource)
{
JSFLProxy.getInstance().changeMovement(animationName, movementName, _movementXML);
}
MessageDispatcher.dispatchEvent(MessageDispatcher.UPDATE_MOVEMENT_DATA, movementName);
}
private function updateMovementBone():void
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var movementData:MovementData = animationData.getMovementData(movementName);
var movementBoneData:MovementBoneData = movementData.getMovementBoneData(boneName);
movementBoneData.scale = boneScale * 0.01;
movementBoneData.delay = boneDelay * 0.01;
if(movementBoneData.delay > 0)
{
movementBoneData.delay -= 1;
}
if(!ImportDataProxy.getInstance().isExportedSource)
{
var movementXMLCopy:XML = _movementXML.copy();
delete movementXMLCopy.elements(ConstValues.BONE).*;
delete movementXMLCopy[ConstValues.FRAME];
JSFLProxy.getInstance().changeMovement(animationName, movementName, movementXMLCopy);
}
MessageDispatcher.dispatchEvent(MessageDispatcher.UPDATE_MOVEMENT_BONE_DATA, movementName);
}
}
}
|
package model
{
import dragonBones.objects.AnimationData;
import dragonBones.objects.ArmatureData;
import dragonBones.objects.MovementBoneData;
import dragonBones.objects.MovementData;
import dragonBones.objects.XMLDataParser;
import dragonBones.utils.ConstValues;
import dragonBones.utils.dragonBones_internal;
import flash.events.Event;
import message.MessageDispatcher;
import mx.collections.XMLListCollection;
use namespace dragonBones_internal;
/**
* Manage selected animation data
*/
public class AnimationDataProxy
{
public var movementsMC:XMLListCollection;
private var _xml:XML;
private var _movementsXMLList:XMLList;
private var _movementXML:XML;
private var _movementBonesXMLList:XMLList;
private var _movementBoneXML:XML;
public function get animationName():String
{
return _xml?_xml.attribute(ConstValues.A_NAME):"";
}
public function get movementName():String
{
return _movementXML?_movementXML.attribute(ConstValues.A_NAME):"";
}
public function get boneName():String
{
return _movementBoneXML?_movementBoneXML.attribute(ConstValues.A_NAME):"";
}
public function get durationTo():Number
{
if(!_movementXML)
{
return -1;
}
return int(_movementXML.attribute(ConstValues.A_DURATION_TO)) / ImportDataProxy.getInstance().skeletonData.frameRate;
}
public function set durationTo(value:Number):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_DURATION_TO] = Math.round(value * ImportDataProxy.getInstance().skeletonData.frameRate);
updateMovement();
}
}
public function get durationTween():Number
{
if(_movementXML?int(_movementXML.attribute(ConstValues.A_DURATION)) == 1:true)
{
return -1;
}
return int(_movementXML.attribute(ConstValues.A_DURATION_TWEEN)) / ImportDataProxy.getInstance().skeletonData.frameRate;
}
public function set durationTween(value:Number):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_DURATION_TWEEN] = Math.round(value * ImportDataProxy.getInstance().skeletonData.frameRate);
updateMovement();
}
}
public function get loop():Boolean
{
return _movementXML?Boolean(int(_movementXML.attribute(ConstValues.A_LOOP)) == 1):false;
}
public function set loop(value:Boolean):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_LOOP] = value?1:0;
updateMovement();
}
}
public function get tweenEasing():Number
{
return _movementXML?Number(_movementXML.attribute(ConstValues.A_TWEEN_EASING)):-1.1;
}
public function set tweenEasing(value:Number):void
{
if(_movementXML)
{
if(value<-1)
{
_movementXML.@[ConstValues.A_TWEEN_EASING] = NaN;
}
else
{
_movementXML.@[ConstValues.A_TWEEN_EASING] = value;
}
updateMovement();
}
}
public function get boneScale():Number
{
if(!_movementBoneXML || int(_movementXML.attribute(ConstValues.A_DURATION)) < 2)
{
return NaN;
}
return Number(_movementBoneXML.attribute(ConstValues.A_MOVEMENT_SCALE)) * 100;
}
public function set boneScale(value:Number):void
{
if(_movementBoneXML)
{
_movementBoneXML.@[ConstValues.A_MOVEMENT_SCALE] = value * 0.01;
updateMovementBone();
}
}
public function get boneDelay():Number
{
if(!_movementBoneXML || int(_movementXML.attribute(ConstValues.A_DURATION)) < 2)
{
return NaN;
}
return Number(_movementBoneXML.attribute(ConstValues.A_MOVEMENT_DELAY))* 100;
}
public function set boneDelay(value:Number):void
{
if(_movementBoneXML)
{
_movementBoneXML.@[ConstValues.A_MOVEMENT_DELAY] = value * 0.01;
updateMovementBone();
}
}
public function AnimationDataProxy()
{
movementsMC = new XMLListCollection();
}
internal function setData(xml:XML):void
{
_xml = xml;
if(_xml)
{
_movementsXMLList = _xml.elements(ConstValues.MOVEMENT);
}
else
{
_movementsXMLList = null;
}
movementsMC.source = _movementsXMLList;
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_ANIMATION_DATA, animationName);
changeMovement();
}
public function changeMovement(movementName:String = null, isChangedByArmature:Boolean = false):void
{
_movementXML = ImportDataProxy.getElementByName(_movementsXMLList, movementName, true);
if(_movementXML)
{
_movementBonesXMLList = _movementXML.elements(ConstValues.BONE);
}
else
{
_movementBonesXMLList = null;
}
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_MOVEMENT_DATA, this.movementName, isChangedByArmature);
changeMovementBone(ImportDataProxy.getInstance().armatureDataProxy.boneName);
}
public function changeMovementBone(boneName:String = null):void
{
var movementBoneXML:XML = ImportDataProxy.getElementByName(_movementBonesXMLList, boneName, true);
if(movementBoneXML == _movementBoneXML)
{
return;
}
_movementBoneXML = movementBoneXML;
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_MOVEMENT_BONE_DATA , this.boneName);
}
internal function updateBoneParent(boneName:String):void
{
if(_xml)
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var armatureData:ArmatureData = ImportDataProxy.getInstance().skeletonData.getArmatureData(animationName);
XMLDataParser.parseAnimationData(_xml, animationData, armatureData);
}
}
private function updateMovement():void
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var movementData:MovementData = animationData.getMovementData(movementName);
movementData.durationTo = durationTo;
movementData.durationTween = durationTween;
movementData.loop = loop;
movementData.tweenEasing = tweenEasing;
if(!ImportDataProxy.getInstance().isExportedSource)
{
JSFLProxy.getInstance().changeMovement(animationName, movementName, _movementXML);
}
MessageDispatcher.dispatchEvent(MessageDispatcher.UPDATE_MOVEMENT_DATA, movementName);
}
private function updateMovementBone():void
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var movementData:MovementData = animationData.getMovementData(movementName);
var movementBoneData:MovementBoneData = movementData.getMovementBoneData(boneName);
movementBoneData.setValues(
boneScale * 0.01,
boneDelay * 0.01
)
if(!ImportDataProxy.getInstance().isExportedSource)
{
var movementXMLCopy:XML = _movementXML.copy();
delete movementXMLCopy.elements(ConstValues.BONE).*;
delete movementXMLCopy[ConstValues.FRAME];
JSFLProxy.getInstance().changeMovement(animationName, movementName, movementXMLCopy);
}
MessageDispatcher.dispatchEvent(MessageDispatcher.UPDATE_MOVEMENT_BONE_DATA, movementName);
}
}
}
|
fix bug
|
fix bug
|
ActionScript
|
mit
|
DragonBones/DesignPanel
|
e437bdeebc18d0ce11af93cb2e777a63d7dda79a
|
source/fairygui/Events.as
|
source/fairygui/Events.as
|
package fairygui {
import laya.display.Sprite;
import laya.events.Event;
public class Events {
public static const STATE_CHANGED: String = "fui_state_changed";
public static const XY_CHANGED: String = "fui_xy_changed";
public static const SIZE_CHANGED: String = "fui_size_changed";
public static const SIZE_DELAY_CHANGE: String = "fui_size_delay_change";
public static const CLICK_ITEM:String = "fui_click_item";
public static const SCROLL:String = "fui_scroll";
public static const SCROLL_END:String = "fui_scroll_end";
public static const DROP:String = "fui_drop";
public static const FOCUS_CHANGED:String = "fui_focus_changed";
public static const DRAG_START:String = "fui_drag_start";
public static const DRAG_MOVE:String = "fui_drag_move";
public static const DRAG_END:String = "fui_drag_end";
public static const PULL_DOWN_RELEASE:String = "fui_pull_down_release";
public static const PULL_UP_RELEASE:String = "fui_pull_up_release";
public static const GEAR_STOP:String = "fui_gear_stop";
public static var $event:Event = new Event();
public static function createEvent(type:String, target:Sprite, source:Event=null):Event {
Events.$event.setTo(type, target, source?source.target:target);
if(source)
Events.$event.touchId = source.touchId;
Events.$event._stoped = false;
return Events.$event;
}
public static function dispatch(type:String, target:Sprite, source:Event=null):void {
target.event(type, Events.createEvent(type, target, source));
}
}
}
|
package fairygui {
import laya.display.Sprite;
import laya.events.Event;
public class Events {
public static const STATE_CHANGED: String = "fui_state_changed";
public static const XY_CHANGED: String = "fui_xy_changed";
public static const SIZE_CHANGED: String = "fui_size_changed";
public static const SIZE_DELAY_CHANGE: String = "fui_size_delay_change";
public static const CLICK_ITEM:String = "fui_click_item";
public static const SCROLL:String = "fui_scroll";
public static const SCROLL_END:String = "fui_scroll_end";
public static const DROP:String = "fui_drop";
public static const FOCUS_CHANGED:String = "fui_focus_changed";
public static const DRAG_START:String = "fui_drag_start";
public static const DRAG_MOVE:String = "fui_drag_move";
public static const DRAG_END:String = "fui_drag_end";
public static const PULL_DOWN_RELEASE:String = "fui_pull_down_release";
public static const PULL_UP_RELEASE:String = "fui_pull_up_release";
public static const GEAR_STOP:String = "fui_gear_stop";
public static var $event:Event = new Event();
public static function createEvent(type:String, target:Sprite, source:Event=null):Event {
Events.$event.setTo(type, target, source?source.target:target);
if(source)
{
Events.$event.touchId = source.touchId;
Events.$event.nativeEvent=source.nativeEvent;
}
else
{
Events.$event.nativeEvent=null;
}
Events.$event._stoped = false;
return Events.$event;
}
public static function dispatch(type:String, target:Sprite, source:Event=null):void {
target.event(type, Events.createEvent(type, target, source));
}
}
}
|
Update Events.as
|
Update Events.as
修复list点击的item的ctrlKey等属性传递丢失。。
|
ActionScript
|
mit
|
fairygui/FairyGUI-layabox,fairygui/FairyGUI-layabox
|
85316458e8dc4e4b0ceb5c6000e0707c64ae1fd9
|
src/aerys/minko/type/animation/timeline/ScalarTimeline.as
|
src/aerys/minko/type/animation/timeline/ScalarTimeline.as
|
package aerys.minko.type.animation.timeline
{
import aerys.minko.ns.minko_animation;
import aerys.minko.scene.node.ISceneNode;
public class ScalarTimeline extends AbstractTimeline
{
use namespace minko_animation;
minko_animation var _timeTable : Vector.<uint>
minko_animation var _values : Vector.<Number>;
minko_animation var _interpolate : Boolean;
public function ScalarTimeline(propertyPath : String,
timeTable : Vector.<uint>,
values : Vector.<Number>,
interpolate : Boolean = true)
{
super(propertyPath, timeTable[int(timeTable.length - 1)]);
_timeTable = timeTable;
_values = values;
_interpolate = interpolate;
}
override public function updateAt(t : int, target : Object):void
{
super.updateAt(t, target);
var time : int = t < 0 ? duration + t : t;
var timeId : uint = getIndexForTime(time);
if (_interpolate)
{
var timeCount : uint = _timeTable.length;
// change value.
var previousTime : Number = _timeTable[int(timeId - 1)];
var nextTime : Number = _timeTable[timeId % timeCount];
var interpolationRatio : Number = (time - previousTime) / (nextTime - previousTime);
if (t < 0.)
interpolationRatio = 1. - interpolationRatio;
currentTarget[propertyName] = (1 - interpolationRatio) * _values[timeId - 1] +
interpolationRatio * _values[timeId % timeCount];
}
else
{
currentTarget[propertyName] = _values[timeId];
}
}
private function getIndexForTime(t : uint) : uint
{
// use a dichotomy to find the current frame in the time table.
var timeCount : uint = _timeTable.length;
var bottomTimeId : uint = 0;
var upperTimeId : uint = timeCount;
var timeId : uint;
while (upperTimeId - bottomTimeId > 1)
{
timeId = (bottomTimeId + upperTimeId) >> 1;
if (_timeTable[timeId] > t)
upperTimeId = timeId;
else
bottomTimeId = timeId;
}
return upperTimeId;
}
override public function clone() : ITimeline
{
return new ScalarTimeline(
propertyPath,
_timeTable.slice(),
_values.slice(),
_interpolate
);
}
}
}
|
package aerys.minko.type.animation.timeline
{
import aerys.minko.ns.minko_animation;
import aerys.minko.scene.node.ISceneNode;
public class ScalarTimeline extends AbstractTimeline
{
use namespace minko_animation;
minko_animation var _timeTable : Vector.<uint>
minko_animation var _values : Vector.<Number>;
minko_animation var _interpolate : Boolean;
public function ScalarTimeline(propertyPath : String,
timeTable : Vector.<uint>,
values : Vector.<Number>,
interpolate : Boolean = true)
{
super(propertyPath, timeTable[int(timeTable.length - 1)]);
_timeTable = timeTable;
_values = values;
_interpolate = interpolate;
}
override public function updateAt(t : int, target : Object):void
{
super.updateAt(t, target);
var time : int = t < 0 ? duration + t : t;
var timeId : uint = getIndexForTime(time);
if (_interpolate)
{
var timeCount : uint = _timeTable.length;
// change value.
var previousTime : Number = _timeTable[uint(timeId - 1)];
var nextTime : Number = _timeTable[uint(timeId % timeCount)];
var interpolationRatio : Number = (time - previousTime) / (nextTime - previousTime);
if (t < 0.)
interpolationRatio = 1. - interpolationRatio;
currentTarget[propertyName] = (1 - interpolationRatio) * _values[timeId - 1] +
interpolationRatio * _values[timeId % timeCount];
}
else
{
currentTarget[propertyName] = _values[timeId];
}
}
private function getIndexForTime(t : uint) : uint
{
// use a dichotomy to find the current frame in the time table.
var timeCount : uint = _timeTable.length;
var bottomTimeId : uint = 0;
var upperTimeId : uint = timeCount;
var timeId : uint;
while (upperTimeId - bottomTimeId > 1)
{
timeId = (bottomTimeId + upperTimeId) >> 1;
if (_timeTable[timeId] > t)
upperTimeId = timeId;
else
bottomTimeId = timeId;
}
return upperTimeId;
}
override public function clone() : ITimeline
{
return new ScalarTimeline(
propertyPath,
_timeTable.slice(),
_values.slice(),
_interpolate
);
}
}
}
|
fix missing cast to uint when accessing array cells
|
fix missing cast to uint when accessing array cells
|
ActionScript
|
mit
|
aerys/minko-as3
|
f5097cec88a7c36515d770ca9922897984e02225
|
src/aerys/minko/scene/controller/camera/ArcBallController.as
|
src/aerys/minko/scene/controller/camera/ArcBallController.as
|
package aerys.minko.scene.controller.camera
{
import flash.display.BitmapData;
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.geom.Point;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.EnterFrameController;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
public class ArcBallController extends EnterFrameController
{
private static const TMP_MATRIX : Matrix4x4 = new Matrix4x4();
private static const EPSILON : Number = 0.001;
protected var _mousePosition : Point = new Point();
private var _enabled : Boolean = true;
private var _previousTime : uint = 0;
private var _distance : Number = 1.;
private var _yaw : Number = 0;
private var _pitch : Number = 0;
private var _newDistance : Number = 1.;
private var _newYaw : Number = 0;
private var _newPitch : Number = 0;
private var _update : Boolean = true;
private var _position : Vector4 = new Vector4(0, 0, 0, 1);
private var _lookAt : Vector4 = new Vector4(0, 0, 0, 1);
private var _up : Vector4 = new Vector4(0, 1, 0, 1);
private var _minDistance : Number = 1.;
private var _maxDistance : Number = 1000;
private var _distanceStep : Number = 1;
private var _yawStep : Number = 0.01;
private var _pitchStep : Number = 0.01;
private var _inertia : Number = 1.0;
private var _interpolationSpeed : Number = 1;
private var _speed : Number = 1;
public function get speed() : Number
{
return _speed;
}
public function set speed(value : Number) : void
{
_speed = value;
_update = true;
}
public function get inertia() : Number
{
return _inertia;
}
public function set inertia(value : Number) : void
{
_inertia = value;
}
public function get interpolationSpeed() : Number
{
return _interpolationSpeed;
}
public function set interpolationSpeed(value : Number) : void
{
_interpolationSpeed = value;
}
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
}
protected function set update(value : Boolean) : void
{
_update = value;
}
/**
* Distance between look at point and target
*/
public function get distance() : Number
{
return _newDistance;
}
public function set distance(value : Number) : void
{
_newDistance = value;
_update = true;
}
/**
* Horizontal rotation angle (in radians)
*/
public function get yaw() : Number
{
return _newYaw;
}
public function set yaw(value : Number) : void
{
_newYaw = value;
_update = true;
}
/**
* Vertical rotation angle (in radians)
*/
public function get pitch() : Number
{
return _newPitch;
}
public function set pitch(value : Number) : void
{
_newPitch = value;
_update = true;
}
/**
* Position the targets will look at
*/
public function get lookAt() : Vector4
{
return _lookAt;
}
/**
* Up vector the targets will rotate around
*/
public function get up() : Vector4
{
return _up;
}
/**
* Minimum distance constrain between look at point and target.
*/
public function get minDistance() : Number
{
return _minDistance;
}
public function set minDistance(value : Number) : void
{
_minDistance = value;
_update = true;
}
/**
* Maximum distance constrain between look at point and target.
*/
public function get maxDistance() : Number
{
return _maxDistance;
}
public function set maxDistance(value : Number) : void
{
_maxDistance = value;
_update = true;
}
/**
* Distance step applied to the camera when the mouse wheel is used in meters/wheel rotation unit
*/
public function get distanceStep() : Number
{
return _distanceStep;
}
public function set distanceStep(value : Number) : void
{
_distanceStep = value;
}
/**
* Horizontal angular step applied to the camera when the mouse is moved in radian/pixel
*/
public function get yawStep() : Number
{
return _yawStep;
}
public function set yawStep(value : Number) : void
{
_yawStep = value;
}
/**
* Vertical angular step applied to the camera when the mouse is moved in radian/pixel
*/
public function get pitchStep() : Number
{
return _pitchStep;
}
public function set pitchStep(value : Number) : void
{
_pitchStep = value;
}
public function ArcBallController()
{
super();
_newPitch = Math.PI * .5;
_lookAt.changed.add(updateNextFrameHandler);
_up.changed.add(updateNextFrameHandler);
}
public function bindDefaultControls(dispatcher : IEventDispatcher) : ArcBallController
{
dispatcher.addEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler);
dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
return this;
}
public function unbindDefaultControls(dispatcher : IEventDispatcher) : ArcBallController
{
dispatcher.removeEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler);
dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
return this;
}
override protected function targetAddedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
super.targetAddedHandler(ctrl, target);
_update = true;
updateTargets();
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
updateTargets((time - _previousTime) * .001);
_previousTime = time;
}
private function clampValues() : void
{
if (_newDistance < _minDistance)
_newDistance = _minDistance;
if (_newDistance > _maxDistance)
_newDistance = _maxDistance;
if (_newPitch <= EPSILON)
_newPitch = EPSILON;
if (_newPitch > Math.PI - EPSILON)
_newPitch = Math.PI - EPSILON;
}
private function updateTargets(time : Number = 1) : void
{
var enableInertia : Boolean = (_inertia != 1. && _interpolationSpeed != 1.);
if (enableInertia || (_update && _enabled))
{
clampValues();
if (enableInertia)
{
var dt : Number = time * _interpolationSpeed;
var factor : Number = _inertia;
_distance = (((_distance * factor) + (_newDistance * dt)) / (factor + dt));
_pitch = (((_pitch * factor) + (_newPitch * dt)) / (factor + dt));
_yaw = (((_yaw * factor) + (_newYaw * dt)) / (factor + dt));
}
else
{
_yaw = _newYaw;
_pitch = _newPitch;
_distance = _newDistance;
}
_position.set(
_speed * (_lookAt.x + _distance * Math.cos(_yaw) * Math.sin(_pitch)),
_speed * (_lookAt.y + _distance * Math.cos(_pitch)),
_speed * (_lookAt.z + _distance * Math.sin(_yaw) * Math.sin(_pitch))
);
TMP_MATRIX.lookAt(_lookAt, _position, _up);
var numTargets : uint = this.numTargets;
for (var targetId : uint = 0; targetId < numTargets; ++targetId)
getTarget(targetId).transform.copyFrom(TMP_MATRIX);
_update = false;
}
}
protected function mouseWheelHandler(e : MouseEvent) : void
{
_newDistance -= e.delta * _distanceStep;
_update = true;
}
protected function mouseMoveHandler(e : MouseEvent) : void
{
// compute position
if (e.buttonDown && _enabled)
{
_newYaw += (_mousePosition.x - e.stageX) * _yawStep;
_newPitch += (_mousePosition.y - e.stageY) * _pitchStep;
_update = true;
}
_mousePosition.setTo(e.stageX, e.stageY);
}
private function updateNextFrameHandler(vector : Vector4) : void
{
_update = true;
}
}
}
|
package aerys.minko.scene.controller.camera
{
import flash.display.BitmapData;
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.geom.Point;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.EnterFrameController;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
public class ArcBallController extends EnterFrameController
{
private static const TMP_MATRIX : Matrix4x4 = new Matrix4x4();
private static const EPSILON : Number = 0.001;
protected var _mousePosition : Point = new Point();
private var _enabled : Boolean = true;
private var _previousTime : uint = 0;
private var _distance : Number = 1.;
private var _yaw : Number = 0;
private var _pitch : Number = 0;
private var _newDistance : Number = 1.;
private var _newYaw : Number = 0;
private var _newPitch : Number = 0;
private var _update : Boolean = true;
private var _position : Vector4 = new Vector4(0, 0, 0, 1);
private var _lookAt : Vector4 = new Vector4(0, 0, 0, 1);
private var _up : Vector4 = new Vector4(0, 1, 0, 1);
private var _minDistance : Number = 1.;
private var _maxDistance : Number = 1000;
private var _distanceStep : Number = 1;
private var _yawStep : Number = 0.01;
private var _pitchStep : Number = 0.01;
private var _inertia : Number = 1.0;
private var _interpolationSpeed : Number = 1;
private var _speed : Number = 1;
public function get speed() : Number
{
return _speed;
}
public function set speed(value : Number) : void
{
_speed = value;
_update = true;
}
public function get inertia() : Number
{
return _inertia;
}
public function set inertia(value : Number) : void
{
_inertia = value;
}
public function get interpolationSpeed() : Number
{
return _interpolationSpeed;
}
public function set interpolationSpeed(value : Number) : void
{
_interpolationSpeed = value;
}
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
}
protected function set update(value : Boolean) : void
{
_update = value;
}
/**
* Distance between look at point and target
*/
public function get distance() : Number
{
return _newDistance;
}
public function set distance(value : Number) : void
{
_newDistance = value;
_update = true;
}
/**
* Horizontal rotation angle (in radians)
*/
public function get yaw() : Number
{
return _newYaw;
}
public function set yaw(value : Number) : void
{
_newYaw = value;
_update = true;
}
/**
* Vertical rotation angle (in radians)
*/
public function get pitch() : Number
{
return _newPitch;
}
public function set pitch(value : Number) : void
{
_newPitch = value;
_update = true;
}
/**
* Position the targets will look at
*/
public function get lookAt() : Vector4
{
return _lookAt;
}
/**
* Up vector the targets will rotate around
*/
public function get up() : Vector4
{
return _up;
}
/**
* Minimum distance constrain between look at point and target.
*/
public function get minDistance() : Number
{
return _minDistance;
}
public function set minDistance(value : Number) : void
{
_minDistance = value;
_update = true;
}
/**
* Maximum distance constrain between look at point and target.
*/
public function get maxDistance() : Number
{
return _maxDistance;
}
public function set maxDistance(value : Number) : void
{
_maxDistance = value;
_update = true;
}
/**
* Distance step applied to the camera when the mouse wheel is used in meters/wheel rotation unit
*/
public function get distanceStep() : Number
{
return _distanceStep;
}
public function set distanceStep(value : Number) : void
{
_distanceStep = value;
}
/**
* Horizontal angular step applied to the camera when the mouse is moved in radian/pixel
*/
public function get yawStep() : Number
{
return _yawStep;
}
public function set yawStep(value : Number) : void
{
_yawStep = value;
}
/**
* Vertical angular step applied to the camera when the mouse is moved in radian/pixel
*/
public function get pitchStep() : Number
{
return _pitchStep;
}
public function set pitchStep(value : Number) : void
{
_pitchStep = value;
}
public function ArcBallController()
{
super();
_newPitch = Math.PI * .5;
_lookAt.changed.add(updateNextFrameHandler);
_up.changed.add(updateNextFrameHandler);
}
public function bindDefaultControls(dispatcher : IEventDispatcher) : ArcBallController
{
dispatcher.addEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler);
dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
return this;
}
public function unbindDefaultControls(dispatcher : IEventDispatcher) : ArcBallController
{
dispatcher.removeEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler);
dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
return this;
}
override protected function targetAddedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
super.targetAddedHandler(ctrl, target);
_update = true;
updateTargets();
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
updateTargets((time - _previousTime) * .001);
_previousTime = time;
}
private function clampValues() : void
{
if (_newDistance < _minDistance)
_newDistance = _minDistance;
if (_newDistance > _maxDistance)
_newDistance = _maxDistance;
if (_newPitch <= EPSILON)
_newPitch = EPSILON;
if (_newPitch > Math.PI - EPSILON)
_newPitch = Math.PI - EPSILON;
}
private function inertiaConverged() : Boolean
{
var distanceDiff : Number = _newDistance - _distance;
var pitchDiff : Number = _newPitch - _pitch;
var yawDiff : Number = _newYaw - _yaw;
return distanceDiff > -EPSILON && distanceDiff < EPSILON &&
pitchDiff > -EPSILON && pitchDiff < EPSILON &&
yawDiff > -EPSILON && yawDiff < EPSILON;
}
private function updateTargets(time : Number = 1) : void
{
var enableInertia : Boolean = (_inertia != 1. && _interpolationSpeed != 1.);
if ((enableInertia && !inertiaConverged()) || (_update && _enabled))
{
clampValues();
if (enableInertia)
{
var dt : Number = time * _interpolationSpeed;
var factor : Number = _inertia;
_distance = (((_distance * factor) + (_newDistance * dt)) / (factor + dt));
_pitch = (((_pitch * factor) + (_newPitch * dt)) / (factor + dt));
_yaw = (((_yaw * factor) + (_newYaw * dt)) / (factor + dt));
}
else
{
_yaw = _newYaw;
_pitch = _newPitch;
_distance = _newDistance;
}
_position.set(
_speed * (_lookAt.x + _distance * Math.cos(_yaw) * Math.sin(_pitch)),
_speed * (_lookAt.y + _distance * Math.cos(_pitch)),
_speed * (_lookAt.z + _distance * Math.sin(_yaw) * Math.sin(_pitch))
);
TMP_MATRIX.lookAt(_lookAt, _position, _up);
var numTargets : uint = this.numTargets;
for (var targetId : uint = 0; targetId < numTargets; ++targetId)
getTarget(targetId).transform.copyFrom(TMP_MATRIX);
_update = false;
}
}
protected function mouseWheelHandler(e : MouseEvent) : void
{
_newDistance -= e.delta * _distanceStep;
_update = true;
}
protected function mouseMoveHandler(e : MouseEvent) : void
{
// compute position
if (e.buttonDown && _enabled)
{
_newYaw += (_mousePosition.x - e.stageX) * _yawStep;
_newPitch += (_mousePosition.y - e.stageY) * _pitchStep;
_update = true;
}
_mousePosition.setTo(e.stageX, e.stageY);
}
private function updateNextFrameHandler(vector : Vector4) : void
{
_update = true;
}
}
}
|
Stop updating the ArcBallController once inertia has converged.
|
Stop updating the ArcBallController once inertia has converged.
|
ActionScript
|
mit
|
aerys/minko-as3
|
61f752a105912e3bbeed24d9e1ff39e4a310fed1
|
src/as/com/threerings/presents/util/SafeSubscriber.as
|
src/as/com/threerings/presents/util/SafeSubscriber.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.util {
import com.threerings.util.Log;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.DObjectManager;
import com.threerings.presents.dobj.ObjectAccessError;
import com.threerings.presents.dobj.Subscriber;
/**
* A class that safely handles the asynchronous subscription to a distributed object when it is not
* know if the subscription will complete before the subscriber decides they no longer wish to be
* subscribed.
*/
public class SafeSubscriber implements Subscriber
{
/**
* Creates a safe subscriber for the specified distributed object which will interact with the
* supplied callback functions.
*
* @param onAvailable a function to be called when the object in question is available. Looks
* like: function (obj :DObject) :void
* @param onFailure a function to be called if the subscription request fails. Looks like:
* function (oid :int, error :ObjectAccessError) :void
*/
public function SafeSubscriber (oid :int, onAvailable :Function, onFailure :Function)
{
// make sure they're not fucking us around
if (oid <= 0) {
throw new ArgumentError("Invalid oid provided to safesub [oid=" + oid + "]");
}
if (subscriber == null) {
throw new ArgumentError("Null subscriber provided to safesub [oid=" + oid + "]");
}
_oid = oid;
_onAvailable = onAvailable;
_onFailure = onFailure;
}
/**
* Returns true if we are currently subscribed to our object (or in the process of obtaining a
* subscription).
*/
public function isActive () :Boolean
{
return _active;
}
/**
* Initiates the subscription process.
*/
public function subscribe (omgr :DObjectManager) :void
{
if (_active) {
log.warning("Active safesub asked to resubscribe " + this);
return;
}
// note that we are now again in the "wishing to be subscribed" state
_active = true;
// make sure we dont have an object reference (which should be logically impossible)
if (_object != null) {
log.warning("Incroyable! A safesub has an object and was non-active!? " + this);
// make do in the face of insanity
_onAvailable(_object);
return;
}
if (_pending) {
// we were previously asked to subscribe, then they asked to unsubscribe and now
// they've asked to subscribe again, all before the original subscription even
// completed; we need do nothing here except as the original subscription request will
// eventually come through and all will be well
return;
}
// we're not pending and we just became active, that means we need to request to subscribe
// to our object
_pending = true;
omgr.subscribeToObject(_oid, this);
}
/**
* Terminates the object subscription. If the initial subscription has not yet completed, the
* desire to terminate will be noted and the subscription will be terminated as soon as it
* completes.
*/
public function unsubscribe (omgr :DObjectManager) :void
{
if (!_active) {
// we may be non-active and have no object which could mean that subscription failed;
// in which case we don't want to complain about anything, just quietly ignore the
// unsubscribe request
if (_object == null && !_pending) {
return;
}
log.warning("Inactive safesub asked to unsubscribe " + this);
Log.dumpStack();
}
// note that we no longer desire to be subscribed
_active = false;
if (_pending) {
// make sure we don't have an object reference
if (_object != null) {
log.warning("Have an object and am pending!? " + this, new Error());
} else {
// nothing to do but wait for the subscription to complete at which point we'll
// pitch the object post-haste
return;
}
}
// make sure we have our object
if (_object == null) {
log.warning("Was active and not pending yet have no object!? " + this, new Error());
// nothing to do since we're apparently already unsubscribed
return;
}
// finally effect our unsubscription
_object = null;
omgr.unsubscribeFromObject(_oid, this);
}
// documentation inherited from interface
public function objectAvailable (object :DObject) :void
{
// make sure life is not too cruel
if (_object != null) {
log.warning("Our object came available but we've already got one!? " + this);
// go ahead and pitch the old one, God knows what's going on
_object = null;
}
if (!_pending) {
log.warning("Our object came available but we're not pending!? " + this);
// go with our badselves, it's the only way
}
// we're no longer pending
_pending = false;
// if we are no longer active, we don't want this damned thing
if (!_active) {
var omgr :DObjectManager = object.getManager();
// if the object's manager is null, that means the object is already destroyed and we
// need not trouble ourselves with unsubscription as it has already been pitched
if (omgr != null) {
omgr.unsubscribeFromObject(_oid, this);
}
return;
}
// otherwise the air is fresh and clean and we can do our job
_object = object;
_onAvailable(object);
}
// documentation inherited from interface
public function requestFailed (oid :int, cause :ObjectAccessError) :void
{
// do the right thing with our pending state
if (!_pending) {
log.warning("Criminy creole! Our subscribe failed but we're not pending!? " + this);
// go with our badselves, it's the only way
}
_pending = false;
// if we're active, let our subscriber know that the shit hit the fan
if (_active) {
// deactivate ourselves as we never got our object (and thus the real subscriber need
// not call unsubscribe())
_active = false;
_onFailure(oid, cause);
}
}
/**
* Returns a string representation of this instance.
*/
public function toString () :String
{
return "[oid=" + _oid + ", active=" + _active + ", pending=" + _pending + "]";
}
protected var _oid :int
protected var _onAvailable :Function;
protected var _onFailure :Function;
protected var _object :DObject;;
protected var _active :Boolean;
protected var _pending :Boolean;
private static const log :Log = Log.getLog(SafeSubscriber);
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.util {
import com.threerings.util.Log;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.DObjectManager;
import com.threerings.presents.dobj.ObjectAccessError;
import com.threerings.presents.dobj.Subscriber;
/**
* A class that safely handles the asynchronous subscription to a distributed object when it is not
* know if the subscription will complete before the subscriber decides they no longer wish to be
* subscribed.
*/
public class SafeSubscriber implements Subscriber
{
/**
* Creates a safe subscriber for the specified distributed object which will interact with the
* supplied callback functions.
*
* @param onAvailable a function to be called when the object in question is available. Looks
* like: function (obj :DObject) :void
* @param onFailure a function to be called if the subscription request fails. Looks like:
* function (oid :int, error :ObjectAccessError) :void
*/
public function SafeSubscriber (oid :int, onAvailable :Function, onFailure :Function)
{
// make sure they're not fucking us around
if (oid <= 0) {
throw new ArgumentError("Invalid oid provided to safesub [oid=" + oid + "]");
}
if (onAvailable == null) {
throw new ArgumentError("Null onAvailable provided to safesub [oid=" + oid + "]");
}
if (onFailure == null) {
throw new ArgumentError("Null onFailure provided to safesub [oid=" + oid + "]");
}
_oid = oid;
_onAvailable = onAvailable;
_onFailure = onFailure;
}
/**
* Returns true if we are currently subscribed to our object (or in the process of obtaining a
* subscription).
*/
public function isActive () :Boolean
{
return _active;
}
/**
* Initiates the subscription process.
*/
public function subscribe (omgr :DObjectManager) :void
{
if (_active) {
log.warning("Active safesub asked to resubscribe " + this);
return;
}
// note that we are now again in the "wishing to be subscribed" state
_active = true;
// make sure we dont have an object reference (which should be logically impossible)
if (_object != null) {
log.warning("Incroyable! A safesub has an object and was non-active!? " + this);
// make do in the face of insanity
_onAvailable(_object);
return;
}
if (_pending) {
// we were previously asked to subscribe, then they asked to unsubscribe and now
// they've asked to subscribe again, all before the original subscription even
// completed; we need do nothing here except as the original subscription request will
// eventually come through and all will be well
return;
}
// we're not pending and we just became active, that means we need to request to subscribe
// to our object
_pending = true;
omgr.subscribeToObject(_oid, this);
}
/**
* Terminates the object subscription. If the initial subscription has not yet completed, the
* desire to terminate will be noted and the subscription will be terminated as soon as it
* completes.
*/
public function unsubscribe (omgr :DObjectManager) :void
{
if (!_active) {
// we may be non-active and have no object which could mean that subscription failed;
// in which case we don't want to complain about anything, just quietly ignore the
// unsubscribe request
if (_object == null && !_pending) {
return;
}
log.warning("Inactive safesub asked to unsubscribe " + this);
Log.dumpStack();
}
// note that we no longer desire to be subscribed
_active = false;
if (_pending) {
// make sure we don't have an object reference
if (_object != null) {
log.warning("Have an object and am pending!? " + this, new Error());
} else {
// nothing to do but wait for the subscription to complete at which point we'll
// pitch the object post-haste
return;
}
}
// make sure we have our object
if (_object == null) {
log.warning("Was active and not pending yet have no object!? " + this, new Error());
// nothing to do since we're apparently already unsubscribed
return;
}
// finally effect our unsubscription
_object = null;
omgr.unsubscribeFromObject(_oid, this);
}
// documentation inherited from interface
public function objectAvailable (object :DObject) :void
{
// make sure life is not too cruel
if (_object != null) {
log.warning("Our object came available but we've already got one!? " + this);
// go ahead and pitch the old one, God knows what's going on
_object = null;
}
if (!_pending) {
log.warning("Our object came available but we're not pending!? " + this);
// go with our badselves, it's the only way
}
// we're no longer pending
_pending = false;
// if we are no longer active, we don't want this damned thing
if (!_active) {
var omgr :DObjectManager = object.getManager();
// if the object's manager is null, that means the object is already destroyed and we
// need not trouble ourselves with unsubscription as it has already been pitched
if (omgr != null) {
omgr.unsubscribeFromObject(_oid, this);
}
return;
}
// otherwise the air is fresh and clean and we can do our job
_object = object;
_onAvailable(object);
}
// documentation inherited from interface
public function requestFailed (oid :int, cause :ObjectAccessError) :void
{
// do the right thing with our pending state
if (!_pending) {
log.warning("Criminy creole! Our subscribe failed but we're not pending!? " + this);
// go with our badselves, it's the only way
}
_pending = false;
// if we're active, let our subscriber know that the shit hit the fan
if (_active) {
// deactivate ourselves as we never got our object (and thus the real subscriber need
// not call unsubscribe())
_active = false;
_onFailure(oid, cause);
}
}
/**
* Returns a string representation of this instance.
*/
public function toString () :String
{
return "[oid=" + _oid + ", active=" + _active + ", pending=" + _pending + "]";
}
protected var _oid :int
protected var _onAvailable :Function;
protected var _onFailure :Function;
protected var _object :DObject;;
protected var _active :Boolean;
protected var _pending :Boolean;
private static const log :Log = Log.getLog(SafeSubscriber);
}
}
|
Check the right things in our Preconditions.
|
Check the right things in our Preconditions.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5720 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
16e938ab5366f7c215309e319f9681c2271094c9
|
actionscript/src/com/freshplanet/ane/AirAACPlayer/AirAACPlayer.as
|
actionscript/src/com/freshplanet/ane/AirAACPlayer/AirAACPlayer.as
|
/*
* Copyright 2017 FreshPlanet
* Licensed 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 com.freshplanet.ane.AirAACPlayer
{
import com.freshplanet.ane.AirAACPlayer.enums.AirAACPlayerState;
import com.freshplanet.ane.AirAACPlayer.events.AirAACPlayerErrorEvent;
import com.freshplanet.ane.AirAACPlayer.events.AirAACPlayerEvent;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class AirAACPlayer extends EventDispatcher
{
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/**
* If <code>true</code>, logs will be displayed at the Actionscript level.
*/
public function get logEnabled() : Boolean {
return _logEnabled;
}
public function set logEnabled( value : Boolean ) : void {
_logEnabled = value;
}
/** AirAACPlayer is supported on iOS and Android devices. */
public static function get isSupported():Boolean {
return isAndroid || isIOS;
}
/**
* Create AirAACPlayer instance
* @param url file or remote sound URL
*/
public function AirAACPlayer(url:String) {
if (!isSupported) return;
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context) {
log("ERROR - Extension context is null. Please check if extension.xml is setup correctly.");
return;
}
_context.addEventListener(StatusEvent.STATUS, onStatus);
_url = url;
}
/**
* Load sound
*/
public function load():void {
if (!isSupported || state != AirAACPlayerState.INITIAL) return;
_state = AirAACPlayerState.LOADING;
_context.call("AirAACPlayer_load", _url);
}
/**
* Dispose AirAACPlayer
*/
public function dispose():void {
if (!isSupported || state == AirAACPlayerState.DISPOSED) return;
_state = AirAACPlayerState.DISPOSED;
_context.call("AirAACPlayer_dispose");
_context.dispose();
_context = null;
}
/**
* Current player url
*/
public function get url():String {
return _url;
}
/**
* Get AirAACPlayer state
*/
public function get state():AirAACPlayerState {
return _state;
}
/**
* Duration in milliseconds
*/
public function get duration():int {
if (!isSupported || state != AirAACPlayerState.READY) return -1;
return _context.call("AirAACPlayer_getDuration") as int;
}
/**
* Progress in milliseconds
*/
public function get progress():int {
if (!isSupported || state != AirAACPlayerState.READY) return -1;
return _context.call("AirAACPlayer_getProgress") as int;
}
/**
* Set the media volume.
* @param volume:Number float between 0.0 and 1.0
*/
public function set volume(volume:Number):void {
if (!isSupported || state != AirAACPlayerState.READY) return;
_context.call("AirAACPlayer_setVolume", volume);
}
/**
* Start playing the stream.
* If the playback has been paused before, it will continue from this point.
* @param startTime:int the start time in milliseconds
*/
public function play(startTime:int = 0):void {
if (!isSupported || state != AirAACPlayerState.READY) return;
startTime = Math.max(0, Math.min(duration, startTime));
_context.call("AirAACPlayer_play", startTime);
}
/** Pause the playback */
public function pause():void {
if (!isSupported || state != AirAACPlayerState.READY) return;
_context.call("AirAACPlayer_pause");
}
/** Stop the playback and move the play head to the beginning of the file */
public function stop():void {
if (!isSupported || state != AirAACPlayerState.READY) return;
_context.call("AirAACPlayer_stop");
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.ane.AirAACPlayer";
private var _logEnabled:Boolean = true;
private var _context:ExtensionContext;
private var _state:AirAACPlayerState = AirAACPlayerState.INITIAL;
private var _url:String;
private function log(message:String):void {
if (_logEnabled) trace("[AirAACPlayer] " + message);
}
private function onStatus(event:StatusEvent):void {
if (state == AirAACPlayerState.DISPOSED) return;
if (event.code == "log") {
log(event.level);
}
else if (event.code == AirAACPlayerEvent.AAC_PLAYER_DOWNLOAD) {
dispatchEvent(new AirAACPlayerEvent(event.code, int(event.level)));
}
else if (event.code == AirAACPlayerEvent.AAC_PLAYER_PREPARED) {
_state = AirAACPlayerState.READY;
dispatchEvent(new AirAACPlayerEvent(event.code));
}
else if (event.code == AirAACPlayerErrorEvent.AAC_PLAYER_ERROR) {
_state = AirAACPlayerState.ERROR;
dispatchEvent(new AirAACPlayerErrorEvent(event.code, event.level));
}
else if (event.code == AirAACPlayerEvent.AAC_PLAYER_PLAYBACK_FINISHED) {
dispatchEvent(new AirAACPlayerEvent(event.code));
}
}
private static function get isIOS():Boolean {
return Capabilities.manufacturer.indexOf("iOS") > -1;
}
private static function get isAndroid():Boolean {
return Capabilities.manufacturer.indexOf("Android") > -1;
}
}
}
|
/*
* Copyright 2017 FreshPlanet
* Licensed 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 com.freshplanet.ane.AirAACPlayer
{
import com.freshplanet.ane.AirAACPlayer.enums.AirAACPlayerState;
import com.freshplanet.ane.AirAACPlayer.events.AirAACPlayerErrorEvent;
import com.freshplanet.ane.AirAACPlayer.events.AirAACPlayerEvent;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class AirAACPlayer extends EventDispatcher
{
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/**
* If <code>true</code>, logs will be displayed at the Actionscript level.
*/
public function get logEnabled() : Boolean {
return _logEnabled;
}
public function set logEnabled( value : Boolean ) : void {
_logEnabled = value;
}
/** AirAACPlayer is supported on iOS and Android devices. */
public static function get isSupported():Boolean {
return isAndroid || isIOS;
}
/**
* Create AirAACPlayer instance
* @param url file or remote sound URL
*/
public function AirAACPlayer(url:String) {
if (!isSupported) return;
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context) {
log("ERROR - Extension context is null. Please check if extension.xml is setup correctly.");
return;
}
_context.addEventListener(StatusEvent.STATUS, onStatus);
_url = url;
}
/**
* Load sound
*/
public function load():void {
if (!isSupported || state != AirAACPlayerState.INITIAL) return;
_state = AirAACPlayerState.LOADING;
_context.call("AirAACPlayer_load", _url);
}
/**
* Dispose AirAACPlayer
*/
public function dispose():void {
if (!isSupported || state == AirAACPlayerState.DISPOSED) return;
_state = AirAACPlayerState.DISPOSED;
_context.call("AirAACPlayer_dispose");
_context.dispose();
_context = null;
}
/**
* Current player url
*/
public function get url():String {
return _url;
}
/**
* Get AirAACPlayer state
*/
public function get state():AirAACPlayerState {
return _state;
}
/**
* Duration in milliseconds
*/
public function get duration():int {
if (!isSupported || state != AirAACPlayerState.READY) return -1;
return _context.call("AirAACPlayer_getDuration") as int;
}
/**
* Progress in milliseconds
*/
public function get progress():int {
if (!isSupported || state != AirAACPlayerState.READY) return -1;
return _context.call("AirAACPlayer_getProgress") as int;
}
/**
* Set the media volume.
* @param volume:Number float between 0.0 and 1.0
*/
public function set volume(volume:Number):void {
if (!isSupported || state != AirAACPlayerState.READY) return;
_context.call("AirAACPlayer_setVolume", volume);
}
/**
* Start playing the stream.
* If the playback has been paused before, it will continue from this point.
* @param startTime:int the start time in milliseconds
*/
public function play(startTime:int = 0, mode:int = 0):void {
if (!isSupported || state != AirAACPlayerState.READY) return;
startTime = Math.max(0, Math.min(duration, startTime));
if (isIOS) {
_context.call("AirAACPlayer_play", startTime, mode ? mode : _playbackCategory);
} else {
_context.call("AirAACPlayer_play", startTime);
}
}
/** Pause the playback */
public function pause():void {
if (!isSupported || state != AirAACPlayerState.READY) return;
_context.call("AirAACPlayer_pause");
}
/** Stop the playback and move the play head to the beginning of the file */
public function stop():void {
if (!isSupported || state != AirAACPlayerState.READY) return;
_context.call("AirAACPlayer_stop");
}
public static const PLAYBACK_MODE_AMBIENT:int = 1
public static const PLAYBACK_MODE_SOLO_AMBIENT:int = 2;
public static const PLAYBACK_MODE_MEDIA:int = 3;
private static var _playbackCategory:int = 0;
public static function setPlaybackCategory(mode:int = 0):void
{
_playbackCategory = mode
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.ane.AirAACPlayer";
private var _logEnabled:Boolean = true;
private var _context:ExtensionContext;
private var _state:AirAACPlayerState = AirAACPlayerState.INITIAL;
private var _url:String;
private function log(message:String):void {
if (_logEnabled) trace("[AirAACPlayer] " + message);
}
private function onStatus(event:StatusEvent):void {
if (state == AirAACPlayerState.DISPOSED) return;
if (event.code == "log") {
log(event.level);
}
else if (event.code == AirAACPlayerEvent.AAC_PLAYER_DOWNLOAD) {
dispatchEvent(new AirAACPlayerEvent(event.code, int(event.level)));
}
else if (event.code == AirAACPlayerEvent.AAC_PLAYER_PREPARED) {
_state = AirAACPlayerState.READY;
dispatchEvent(new AirAACPlayerEvent(event.code));
}
else if (event.code == AirAACPlayerErrorEvent.AAC_PLAYER_ERROR) {
_state = AirAACPlayerState.ERROR;
dispatchEvent(new AirAACPlayerErrorEvent(event.code, event.level));
}
else if (event.code == AirAACPlayerEvent.AAC_PLAYER_PLAYBACK_FINISHED) {
dispatchEvent(new AirAACPlayerEvent(event.code));
}
}
private static function get isIOS():Boolean {
return Capabilities.manufacturer.indexOf("iOS") > -1;
}
private static function get isAndroid():Boolean {
return Capabilities.manufacturer.indexOf("Android") > -1;
}
}
}
|
support a 'global' playback category on ios (only updates when playing sounds)
|
support a 'global' playback category on ios (only updates when playing sounds)
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-AACPlayer,freshplanet/ANE-AACPlayer,freshplanet/ANE-AACPlayer
|
adac943c7b9c3daf5648aef17ae8ce165cada408
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.PushButton;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.animations.AnimationHelper;
import com.merlinds.miracle.display.MiracleDisplayObject;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle.utils.MafReader;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.FileFilter;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _startBtn:PushButton;
private var _texture:ByteArray;
private var _animation:ByteArray;
private var _fileName:String;
private var _list:List;
private var _instance:MiracleDisplayObject;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
_startBtn = new PushButton(this, this.stage.stageWidth >> 1, this.stage.stageHeight >> 1,
"Start", this.startBtnHandler );
}
function clear():void
{
if(_animation != null) _animation.clear();
if(_texture != null) _texture.clear();
_texture = null;
_animation = null;
_fileName = null;
}
private function startHandler():void {
trace("Miracle was started");
var maf:Asset = new Asset(_fileName + ".maf", _animation);
var mtf:Asset = new Asset(_fileName + ".mtf", _texture);
Miracle.createScene(new <Asset>[maf, mtf], this.createdHandler, 1);
}
private function createdHandler():void {
trace("Scene created");
this.getAnimationList();
}
private function getAnimationList():void {
var mafReader = new MafReader();
mafReader.execute(_animation, 1);
var animationsName:Array = [];
for each(var animation:AnimationHelper in mafReader.animations)
{
animationsName.push(animation.name);
}
trace("Was get animations", animationsName);
_list = new List(this, this.stage.stageWidth - 200, 0, animationsName);
_list.width = 200;
_list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
private function getAnimation():void {
var file:File = _model.lastFileDirection;
file.browseForOpen("Get animation file", [new FileFilter("Miracle animation format", "*.maf")] );
file.addEventListener(Event.SELECT, this.animationSelected);
file.addEventListener(Event.CANCEL, this.animationSelected);
}
private function readAnimation(file:File):void {
_animation = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
fileStream.readBytes(_animation);
fileStream.close();
}
private function getTexture(file:File):void {
_fileName = file.name.substr(0, -file.extension.length - 1);
file.browseForOpen("Get texture file", [new FileFilter("Miracle texture format", _fileName + ".mtf")] );
file.addEventListener(Event.SELECT, this.animationSelected);
file.addEventListener(Event.CANCEL, this.animationSelected);
}
private function readTexture(file:File):void {
_texture = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
fileStream.readBytes(_texture);
fileStream.close();
}
public function startBtnHandler(event:Event):void{
_startBtn.visible = false;
getAnimation();
}
private function animationSelected(event:Event):void {
if(event.type == Event.CANCEL)
{
this.clear();
_startBtn.visible = true;
}else
{
if(_animation == null)
{
this.readAnimation(event.target as File);
this.getTexture(event.target as File);
}else
{
this.readTexture(event.target as File);
trace("All loaded");
Miracle.start(this.stage, this.startHandler, true);
}
}
}
private function selectAnimationHandler(event:Event):void {
if(_instance != null)
{
Miracle.scene.removeInstance(_instance);
}
var selected:String = _list.selectedItem as String;
var dot:int = selected.lastIndexOf(".");
var animation:String = selected.substr(dot+1);
var mesh:String = selected.substr(0, dot);
_instance = Miracle.scene.createImage(mesh, animation);
_instance.x = this.stage.stageWidth >> 1;
_instance.y = this.stage.stageHeight >> 1;
_instance.visible = true;
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.PushButton;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.animations.AnimationHelper;
import com.merlinds.miracle.display.MiracleDisplayObject;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle.utils.MafReader;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.FileFilter;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _startBtn:PushButton;
private var _texture:ByteArray;
private var _animation:ByteArray;
private var _fileName:String;
private var _list:List;
private var _instance:MiracleDisplayObject;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
_startBtn = new PushButton(this, this.stage.stageWidth >> 1, this.stage.stageHeight >> 1,
"Start", this.startBtnHandler );
}
public function clear():void
{
if(_animation != null) _animation.clear();
if(_texture != null) _texture.clear();
_texture = null;
_animation = null;
_fileName = null;
}
private function startHandler():void {
trace("Miracle was started");
var maf:Asset = new Asset(_fileName + ".maf", _animation);
var mtf:Asset = new Asset(_fileName + ".mtf", _texture);
Miracle.createScene(new <Asset>[maf, mtf], this.createdHandler, 1);
}
private function createdHandler():void {
trace("Scene created");
this.getAnimationList();
}
private function getAnimationList():void {
var mafReader:MafReader = new MafReader();
mafReader.execute(_animation, 1);
var animationsName:Array = [];
for each(var animation:AnimationHelper in mafReader.animations)
{
animationsName.push(animation.name);
}
trace("Was get animations", animationsName);
_list = new List(this, this.stage.stageWidth - 200, 0, animationsName);
_list.width = 200;
_list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
private function getAnimation():void {
var file:File = _model.lastFileDirection;
file.browseForOpen("Get animation file", [new FileFilter("Miracle animation format", "*.maf")] );
file.addEventListener(Event.SELECT, this.animationSelected);
file.addEventListener(Event.CANCEL, this.animationSelected);
}
private function readAnimation(file:File):void {
_animation = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
fileStream.readBytes(_animation);
fileStream.close();
}
private function getTexture(file:File):void {
_fileName = file.name.substr(0, -file.extension.length - 1);
file.browseForOpen("Get texture file", [new FileFilter("Miracle texture format", _fileName + ".mtf")] );
file.addEventListener(Event.SELECT, this.animationSelected);
file.addEventListener(Event.CANCEL, this.animationSelected);
}
private function readTexture(file:File):void {
_texture = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
fileStream.readBytes(_texture);
fileStream.close();
}
public function startBtnHandler(event:Event):void{
_startBtn.visible = false;
getAnimation();
}
private function animationSelected(event:Event):void {
if(event.type == Event.CANCEL)
{
this.clear();
_startBtn.visible = true;
}else
{
if(_animation == null)
{
this.readAnimation(event.target as File);
this.getTexture(event.target as File);
}else
{
this.readTexture(event.target as File);
trace("All loaded");
Miracle.start(this.stage, this.startHandler, true);
}
}
}
private function selectAnimationHandler(event:Event):void {
if(_instance != null)
{
Miracle.scene.removeInstance(_instance);
}
var selected:String = _list.selectedItem as String;
var dot:int = selected.lastIndexOf(".");
var animation:String = selected.substr(dot+1);
var mesh:String = selected.substr(0, dot);
_instance = Miracle.scene.createImage(mesh, animation);
_instance.x = this.stage.stageWidth >> 1;
_instance.y = this.stage.stageHeight >> 1;
_instance.visible = true;
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
refactor with external config
|
refactor with external config
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
b68645dba7df847c3ecee302d8d3fd7606893662
|
test/request/HTTPClientTest.as
|
test/request/HTTPClientTest.as
|
package test.request {
import mx.rpc.events.ResultEvent;
import flails.request.HTTPClient;
import flails.request.JSONFilter;
import flails.resource.Record;
import flails.request.ResourcePathBuilder;
import flails.request.RequestConfig;
import net.digitalprimates.fluint.tests.TestCase;
public class HTTPClientTest extends TestCase {
private var r:HTTPClient;
private var rCheck:HTTPClient;
override protected function setUp():void {
var cleanup:HTTPClient = new HTTPClient(null, null, new RequestConfig())
cleanup.addEventListener("result", asyncHandler(pendUntilComplete, 1000))
cleanup.doGet("/posts/reset");
var rc:RequestConfig = new RequestConfig();
rc.baseUrl = "http://localhost:3000";
r = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter(), rc);
rCheck = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter(), rc);
}
public function testIndex():void {
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var a:Array = e.result as Array;
assertEquals(2, a.length);
assertEquals('testFindAll #1', a[0].subject);
assertEquals('testFindAll #1 body', a[0].body);
assertEquals('testFindAll #2', a[1].subject);
assertEquals('testFindAll #2 body', a[1].body);
}, 1000));
r.index();
}
public function testShow():void {
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = new Record;
p.setAttributes(e.result);
assertEquals('testFindAll #1', p.subject);
assertEquals('testFindAll #1 body', p.body);
}, 1500));
r.show(1);
}
public function testShowNotFound():void {
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = new Record;
p.setAttributes(e.result);
assertEquals('Record Not Found', p.message);
}, 1500));
r.show(2349324920);
}
public function testCreate():void {
r.addEventListener("result", asyncHandler(verifyCreateComplete, 1500));
r.create({post: {subject: "creating new post", body: "creating new post with body"}});
}
private function verifyCreateComplete(e:ResultEvent, data:Object):void {
rCheck.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = new Record;
p.setAttributes(e.result);
assertEquals('creating new post', p.subject);
assertEquals('creating new post with body', p.body);
}, 1500));
rCheck.show(e.result.id);
}
public function testUpdate():void {
r.addEventListener("result", asyncHandler(verifyUpdateComplete, 1500));
r.update({post: {subject: "testFindAll #2 updated", body: "testFindAll #2 body updated"}}, 2);
}
private function verifyUpdateComplete(e:ResultEvent, data:Object):void {
rCheck.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = new Record;
p.setAttributes(e.result);
assertEquals('testFindAll #2 updated', p.subject);
assertEquals('testFindAll #2 body updated', p.body);
}, 1500));
rCheck.show(2);
}
public function testDestroy():void {
r.addEventListener("result", asyncHandler(verifyDestroy, 1500));
r.destroy(2);
}
private function verifyDestroy(e:ResultEvent, data:Object):void {
var p:Record = new Record;
p.setAttributes(e.result);
assertEquals(2, p.id);
rCheck.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p2:Record = new Record;
p2.setAttributes(e.result);
assertEquals(null, p2.id);
}, 1500));
rCheck.show(p.id);
}
}
}
|
package test.request {
import mx.rpc.events.ResultEvent;
import flails.request.HTTPClient;
import flails.request.JSONFilter;
import flails.resource.Record;
import flails.request.ResourcePathBuilder;
import flails.request.RequestConfig;
import net.digitalprimates.fluint.tests.TestCase;
public class HTTPClientTest extends TestCase {
private var r:HTTPClient;
private var rCheck:HTTPClient;
override protected function setUp():void {
var cleanup:HTTPClient = new HTTPClient(null, null, new RequestConfig())
cleanup.addEventListener("result", asyncHandler(pendUntilComplete, 1000))
cleanup.doGet("/posts/reset");
var rc:RequestConfig = new RequestConfig();
rc.baseUrl = "http://localhost:3000";
r = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter(), rc);
rCheck = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter(), rc);
}
public function testIndex():void {
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var a:Array = e.result as Array;
assertEquals(2, a.length);
assertEquals('testFindAll #1', a[0].subject);
assertEquals('testFindAll #1 body', a[0].body);
assertEquals('testFindAll #2', a[1].subject);
assertEquals('testFindAll #2 body', a[1].body);
}, 1000));
r.index();
}
public function testShow():void {
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = new Record(e.result);
assertEquals('testFindAll #1', p.subject);
assertEquals('testFindAll #1 body', p.body);
}, 1500));
r.show(1);
}
public function testShowNotFound():void {
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = new Record(e.result);
assertEquals('Record Not Found', p.message);
}, 1500));
r.show(2349324920);
}
public function testCreate():void {
r.addEventListener("result", asyncHandler(verifyCreateComplete, 1500));
r.create({post: {subject: "creating new post", body: "creating new post with body"}});
}
private function verifyCreateComplete(e:ResultEvent, data:Object):void {
rCheck.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = new Record(e.result);
assertEquals('creating new post', p.subject);
assertEquals('creating new post with body', p.body);
}, 1500));
rCheck.show(e.result.id);
}
public function testUpdate():void {
r.addEventListener("result", asyncHandler(verifyUpdateComplete, 1500));
r.update(2, {post: {subject: "testFindAll #2 updated", body: "testFindAll #2 body updated"}});
}
private function verifyUpdateComplete(e:ResultEvent, data:Object):void {
rCheck.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = new Record(e.result);
assertEquals('testFindAll #2 updated', p.subject);
assertEquals('testFindAll #2 body updated', p.body);
}, 1500));
rCheck.show(2);
}
public function testDestroy():void {
r.addEventListener("result", asyncHandler(verifyDestroy, 1500));
r.destroy(2);
}
private function verifyDestroy(e:ResultEvent, data:Object):void {
var p:Record = new Record(e.result);
assertEquals(2, p.id);
rCheck.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p2:Record = new Record;
p2.setAttributes(e.result);
assertEquals(null, p2.id);
}, 1500));
rCheck.show(p.id);
}
}
}
|
Update test fixed
|
Update test fixed
|
ActionScript
|
mit
|
lancecarlson/flails,lancecarlson/flails
|
ca14a6a3e8a85425e71786cd0e27d7a76da6f03e
|
src/spitfire.as
|
src/spitfire.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
include "corsaair/server/spitfire/SimpleSocketServer.as";
include "corsaair/server/spitfire/SimpleSocketServer1.as";
import corsaair.server.spitfire.*;
// example1
/*
var server = new SimpleSocketServer();
*/
// example2
var server = new SimpleSocketServer1();
server.showAddressInfo1();
server.showAddressInfo2();
server.showAddressInfo3();
server.showAddressInfo3( "localhost" );
// pass trough cloudflare
server.showAddressInfo3( "www.corsaair.com" );
// direct to the server
server.showAddressInfo3( "www.as3lang.org" );
// more example
server.showAddressInfo3( "www.google.com" );
server.showAddressInfo3( "www.yahoo.com" );
server.showAddressInfo3( "www.cloudflare.com" );
server.main();
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
include "corsaair/server/spitfire/SimpleSocketServer.as";
include "corsaair/server/spitfire/SimpleSocketServerSelect.as";
include "corsaair/server/spitfire/SimpleSocketServerSelect2.as";
import corsaair.server.spitfire.*;
// example1
/*
var server = new SimpleSocketServer();
server.main();
*/
// example2
/*
var server = new SimpleSocketServerSelect();
server.showAddressInfo1();
server.showAddressInfo2();
server.showAddressInfo3();
server.showAddressInfo3( "localhost" );
// pass trough cloudflare
server.showAddressInfo3( "www.corsaair.com" );
// direct to the server
server.showAddressInfo3( "www.as3lang.org" );
// more example
server.showAddressInfo3( "www.google.com" );
server.showAddressInfo3( "www.yahoo.com" );
server.showAddressInfo3( "www.cloudflare.com" );
server.main();
*/
// example2
var server = new SimpleSocketServerSelect2();
server.main();
|
update main file
|
update main file
git-svn-id: 44dac414ef660a76a1e627c7b7c0e36d248d62e4@18 c2cce57b-6cbb-4450-ba62-5fdab5196ef5
|
ActionScript
|
mpl-2.0
|
Corsaair/spitfire
|
f25e51a40c90809f9e3f13f48b25efdf541ba486
|
src/CameraMan.as
|
src/CameraMan.as
|
package {
import flash.display.Sprite;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.geom.Point;
import flash.external.ExternalInterface;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.media.Camera;
import flash.media.Video;
import flash.utils.ByteArray;
import mx.graphics.codec.JPEGEncoder;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class CameraMan extends Sprite {
private var videoface:Video;
private var cam:Camera;
private var photo:Bitmap;
private var sendto:String;
private var movieSize:Point;
public function CameraMan() {
stage.addEventListener(Event.RESIZE, configureCamera);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
trace("START ME UP");
sendto = this.loaderInfo.parameters.sendto;
configureCamera(null);
if (ExternalInterface.available) {
ExternalInterface.addCallback("takePhoto", takePhoto);
ExternalInterface.addCallback("sendPhoto", sendPhoto);
ExternalInterface.addCallback("dropPhoto", dropPhoto);
}
}
public function awesome(event:Event) : void {
trace("~~ AWESOME " + event.target.muted);
}
public function createCamera(event:Event) : void {
cam = Camera.getCamera();
// TODO: handle a missing camera
// TODO: handle a "dead" camera (fps = 0?)
/* TODO: handle a muted camera? we'll only get an
* unmuted camera to start with if they've chosen to
* Remember Allow. If they haven't chosen Remember Deny,
* they'll automatically get a dialog from attachCamera()
* later.
*/
cam.addEventListener("status", awesome);
trace("got camera " + cam.name + ". muted: " + cam.muted
+ '. size: ' + cam.width + ',' + cam.height + '. fps: '
+ cam.currentFPS + '. max fps: ' + cam.fps + ' total cameras: ' + Camera.names.length);
cam.setMode(stage.stageWidth, stage.stageHeight, 15);
videoface = new Video(cam.width, cam.height);
videoface.attachCamera(cam);
this.addChild(videoface);
}
public function configureCamera(event:Event) : void {
trace("o hai configure camera!!");
if (stage.stageWidth == 0) {
trace("stage is zero-width, so skip");
return;
}
if (!cam)
return this.createCamera(event);
cam.setMode(stage.stageWidth, stage.stageHeight, 15);
trace("Camera size is " + cam.width + ", " + cam.height);
videoface.width = cam.width;
videoface.height = cam.height;
}
public function callback(eventname:String, ... args) : void {
eventname = "cameraman._" + eventname;
var callargs:Array = [eventname] + args;
if (ExternalInterface.available)
ExternalInterface.call.apply(callargs);
}
public function takePhoto() : void {
// freeze image
try {
var photobits:BitmapData = new BitmapData(videoface.videoWidth, videoface.videoHeight, false);
photobits.draw(videoface);
// Swap the video for the captured bitmap.
photo = new Bitmap(photobits);
this.addChild(photo);
this.removeChild(videoface);
} catch(err:Error) {
trace(err.name + " " + err.message);
}
this.callback('tookPhoto');
}
public function dropPhoto() : void {
// cancel the freezing
try {
this.removeChild(photo);
photo = null;
this.addChild(videoface);
}
catch (err:Error) {
trace(err.name + " " + err.message);
}
this.callback('droppedPhoto');
}
public function sendPhoto() : void {
try {
// produce image file
var peggy:JPEGEncoder = new JPEGEncoder(75.0);
var image:ByteArray = peggy.encode(photo.bitmapData);
// send image file to server
var req:URLRequest = new URLRequest();
req.url = this.sendto;
req.method = "POST";
req.contentType = peggy.contentType;
req.data = image;
var http:URLLoader = new URLLoader();
http.addEventListener("complete", sentPhoto);
http.addEventListener("ioError", sendingIOError);
http.addEventListener("securityError", sendingSecurityError);
http.addEventListener("httpStatus", sendingHttpStatus);
http.load(req);
} catch(err:Error) {
trace(err.name + " " + err.message);
}
}
public function sendingHttpStatus(event:HTTPStatusEvent) : void {
trace("HTTPStatus: " + event.status + " " + event.target);
}
public function sendingIOError(event:IOErrorEvent) : void {
trace("IOError: " + event.type + " " + event.text + " " + event.target + " " + event.target.bytesLoaded);
}
public function sendingSecurityError(event:SecurityErrorEvent) : void {
trace("SecurityError: " + event.text + " " + event.target);
}
public function sentPhoto(event:Event) : void {
var url:String = event.target.data;
this.callback('sentPhoto', url);
}
}
}
|
package {
import flash.display.Sprite;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.geom.Point;
import flash.external.ExternalInterface;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.media.Camera;
import flash.media.Video;
import flash.utils.ByteArray;
import mx.graphics.codec.JPEGEncoder;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class CameraMan extends Sprite {
private var videoface:Video;
private var cam:Camera;
private var photo:Bitmap;
private var cameraid:String;
private var sendto:String;
private var movieSize:Point;
public function CameraMan() {
stage.addEventListener(Event.RESIZE, configureCamera);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
trace("START ME UP");
sendto = this.loaderInfo.parameters.sendto;
cameraid = this.loaderInfo.parameters.cameraid;
configureCamera(null);
if (ExternalInterface.available) {
ExternalInterface.addCallback("takePhoto", takePhoto);
ExternalInterface.addCallback("sendPhoto", sendPhoto);
ExternalInterface.addCallback("dropPhoto", dropPhoto);
}
}
public function awesome(event:Event) : void {
trace("~~ AWESOME " + event.target.muted);
}
public function createCamera(event:Event) : void {
cam = Camera.getCamera();
// TODO: handle a missing camera
// TODO: handle a "dead" camera (fps = 0?)
/* TODO: handle a muted camera? we'll only get an
* unmuted camera to start with if they've chosen to
* Remember Allow. If they haven't chosen Remember Deny,
* they'll automatically get a dialog from attachCamera()
* later.
*/
cam.addEventListener("status", awesome);
trace("got camera " + cam.name + ". muted: " + cam.muted
+ '. size: ' + cam.width + ',' + cam.height + '. fps: '
+ cam.currentFPS + '. max fps: ' + cam.fps + ' total cameras: ' + Camera.names.length);
cam.setMode(stage.stageWidth, stage.stageHeight, 15);
videoface = new Video(cam.width, cam.height);
videoface.attachCamera(cam);
this.addChild(videoface);
}
public function configureCamera(event:Event) : void {
trace("o hai configure camera!!");
if (stage.stageWidth == 0) {
trace("stage is zero-width, so skip");
return;
}
if (!cam)
return this.createCamera(event);
cam.setMode(stage.stageWidth, stage.stageHeight, 15);
trace("Camera size is " + cam.width + ", " + cam.height);
videoface.width = cam.width;
videoface.height = cam.height;
}
public function callback(eventname:String, ... args) : void {
eventname = "cameraman.cameras['" + cameraid + "']._" + eventname;
trace("Calling back to " + eventname + " with: " + args);
args.unshift(eventname);
if (ExternalInterface.available)
ExternalInterface.call.apply(null, args);
}
public function takePhoto() : void {
// freeze image
try {
var photobits:BitmapData = new BitmapData(videoface.videoWidth, videoface.videoHeight, false);
photobits.draw(videoface);
// Swap the video for the captured bitmap.
photo = new Bitmap(photobits);
this.addChild(photo);
this.removeChild(videoface);
} catch(err:Error) {
trace(err.name + " " + err.message);
}
this.callback('tookPhoto');
}
public function dropPhoto() : void {
// cancel the freezing
try {
this.removeChild(photo);
photo = null;
this.addChild(videoface);
}
catch (err:Error) {
trace(err.name + " " + err.message);
}
this.callback('droppedPhoto');
}
public function sendPhoto() : void {
try {
// produce image file
var peggy:JPEGEncoder = new JPEGEncoder(75.0);
var image:ByteArray = peggy.encode(photo.bitmapData);
// send image file to server
var req:URLRequest = new URLRequest();
req.url = this.sendto;
req.method = "POST";
req.contentType = peggy.contentType;
req.data = image;
var http:URLLoader = new URLLoader();
http.addEventListener("complete", sentPhoto);
http.addEventListener("ioError", sendingIOError);
http.addEventListener("securityError", sendingSecurityError);
http.addEventListener("httpStatus", sendingHttpStatus);
http.load(req);
} catch(err:Error) {
trace(err.name + " " + err.message);
}
}
public function sendingHttpStatus(event:HTTPStatusEvent) : void {
trace("HTTPStatus: " + event.status + " " + event.target);
}
public function sendingIOError(event:IOErrorEvent) : void {
trace("IOError: " + event.type + " " + event.text + " " + event.target + " " + event.target.bytesLoaded);
this.callback('errorSending', 'IO error: ' + event.text);
}
public function sendingSecurityError(event:SecurityErrorEvent) : void {
trace("SecurityError: " + event.text + " " + event.target);
this.callback('errorSending', 'Security error: ' + event.text);
}
public function sentPhoto(event:Event) : void {
var url:String = event.target.data;
this.callback('sentPhoto', url);
}
}
}
|
Use apply() properly Call back into a particular camera by cameraid Call back out on IO or security error when sending
|
Use apply() properly
Call back into a particular camera by cameraid
Call back out on IO or security error when sending
|
ActionScript
|
mit
|
markpasc/cameraman
|
55f9c7c2aa5e9901c133c63943c585d39471aff7
|
src/CameraMan.as
|
src/CameraMan.as
|
package {
import flash.display.Sprite;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.geom.Point;
import flash.external.ExternalInterface;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.media.Camera;
import flash.media.Video;
import flash.utils.ByteArray;
import mx.graphics.codec.JPEGEncoder;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class CameraMan extends Sprite {
private var videoface:Video;
private var cam:Camera;
private var photo:BitmapData;
private var sendto:String;
private var movieSize:Point;
public function CameraMan() {
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
trace("START ME UP");
this.loaderInfo.addEventListener("init", init);
if (ExternalInterface.available) {
ExternalInterface.addCallback("takePhoto", takePhoto);
ExternalInterface.addCallback("sendPhoto", sendPhoto);
}
}
public function init(event:Event) : void {
trace("initizing");
sendto = this.loaderInfo.parameters.sendto;
movieSize = new Point(this.loaderInfo.width, this.loaderInfo.height);
trace("Movie size is " + this.loaderInfo.width + ", " + this.loaderInfo.height);
cam = Camera.getCamera();
cam.setMode(movieSize.x, movieSize.y, 15);
trace("Camera size is " + cam.width + ", " + cam.height);
videoface = new Video(cam.width, cam.height);
videoface.attachCamera(cam);
this.addChild(videoface);
}
public function takePhoto() : void {
// freeze image
try {
photo = new BitmapData(videoface.videoWidth, videoface.videoHeight, false);
photo.draw(videoface);
// Swap the video for the captured bitmap.
var bitty:Bitmap = new Bitmap(photo);
this.addChild(bitty);
this.removeChild(videoface);
} catch(err:Error) {
trace(err.name + " " + err.message);
}
if (ExternalInterface.available) {
ExternalInterface.call('cameraman._tookPhoto');
}
}
public function sendPhoto() : void {
try {
// produce image file
var peggy:JPEGEncoder = new JPEGEncoder(75.0);
var image:ByteArray = peggy.encode(photo);
// send image file to server
var req:URLRequest = new URLRequest();
req.url = this.sendto;
req.method = "POST";
req.contentType = peggy.contentType;
req.data = image;
var http:URLLoader = new URLLoader();
http.addEventListener("complete", sentPhoto);
http.addEventListener("ioError", sendingIOError);
http.addEventListener("securityError", sendingSecurityError);
http.addEventListener("httpStatus", sendingHttpStatus);
http.load(req);
} catch(err:Error) {
trace(err.name + " " + err.message);
}
}
public function sendingHttpStatus(event:HTTPStatusEvent) : void {
trace("HTTPStatus: " + event.status + " " + event.target);
}
public function sendingIOError(event:IOErrorEvent) : void {
trace("IOError: " + event.type + " " + event.text + " " + event.target + " " + event.target.bytesLoaded);
}
public function sendingSecurityError(event:SecurityErrorEvent) : void {
trace("SecurityError: " + event.text + " " + event.target);
}
public function sentPhoto(event:Event) : void {
var url:String = event.target.data;
if (ExternalInterface.available)
ExternalInterface.call('cameraman._sentPhoto', url);
}
}
}
|
package {
import flash.display.Sprite;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.geom.Point;
import flash.external.ExternalInterface;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.media.Camera;
import flash.media.Video;
import flash.utils.ByteArray;
import mx.graphics.codec.JPEGEncoder;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class CameraMan extends Sprite {
private var videoface:Video;
private var cam:Camera;
private var photo:BitmapData;
private var sendto:String;
private var movieSize:Point;
public function CameraMan() {
stage.addEventListener(Event.RESIZE, configureCamera);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
trace("START ME UP");
sendto = this.loaderInfo.parameters.sendto;
configureCamera(null);
if (ExternalInterface.available) {
ExternalInterface.addCallback("takePhoto", takePhoto);
ExternalInterface.addCallback("sendPhoto", sendPhoto);
}
}
public function awesome(event:Event) : void {
trace("~~ AWESOME " + event.target.muted);
}
public function createCamera(event:Event) : void {
cam = Camera.getCamera();
cam.addEventListener("status", awesome);
trace("got camera " + cam.name + ". muted: " + cam.muted
+ '. size: ' + cam.width + ',' + cam.height + '. fps: '
+ cam.currentFPS + '. max fps: ' + cam.fps + ' total cameras: ' + Camera.names.length);
cam.setMode(stage.stageWidth, stage.stageHeight, 15);
videoface = new Video(cam.width, cam.height);
videoface.attachCamera(cam);
this.addChild(videoface);
}
public function configureCamera(event:Event) : void {
trace("o hai configure camera!!");
if (stage.stageWidth == 0) {
trace("stage is zero-width, so skip");
return;
}
if (!cam)
return this.createCamera(event);
cam.setMode(stage.stageWidth, stage.stageHeight, 15);
trace("Camera size is " + cam.width + ", " + cam.height);
videoface.width = cam.width;
videoface.height = cam.height;
}
public function takePhoto() : void {
// freeze image
try {
photo = new BitmapData(videoface.videoWidth, videoface.videoHeight, false);
photo.draw(videoface);
// Swap the video for the captured bitmap.
var bitty:Bitmap = new Bitmap(photo);
this.addChild(bitty);
this.removeChild(videoface);
} catch(err:Error) {
trace(err.name + " " + err.message);
}
if (ExternalInterface.available) {
ExternalInterface.call('cameraman._tookPhoto');
}
}
public function sendPhoto() : void {
try {
// produce image file
var peggy:JPEGEncoder = new JPEGEncoder(75.0);
var image:ByteArray = peggy.encode(photo);
// send image file to server
var req:URLRequest = new URLRequest();
req.url = this.sendto;
req.method = "POST";
req.contentType = peggy.contentType;
req.data = image;
var http:URLLoader = new URLLoader();
http.addEventListener("complete", sentPhoto);
http.addEventListener("ioError", sendingIOError);
http.addEventListener("securityError", sendingSecurityError);
http.addEventListener("httpStatus", sendingHttpStatus);
http.load(req);
} catch(err:Error) {
trace(err.name + " " + err.message);
}
}
public function sendingHttpStatus(event:HTTPStatusEvent) : void {
trace("HTTPStatus: " + event.status + " " + event.target);
}
public function sendingIOError(event:IOErrorEvent) : void {
trace("IOError: " + event.type + " " + event.text + " " + event.target + " " + event.target.bytesLoaded);
}
public function sendingSecurityError(event:SecurityErrorEvent) : void {
trace("SecurityError: " + event.text + " " + event.target);
}
public function sentPhoto(event:Event) : void {
var url:String = event.target.data;
if (ExternalInterface.available)
ExternalInterface.call('cameraman._sentPhoto', url);
}
}
}
|
Set up the camera opportunistically, either in the constructor or on the stage resize event
|
Set up the camera opportunistically, either in the constructor or on the stage resize event
|
ActionScript
|
mit
|
markpasc/cameraman
|
5f2308b3915628e3e6994f21fcf40eca24601491
|
exporter/src/main/as/flump/export/DeviceType.as
|
exporter/src/main/as/flump/export/DeviceType.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import com.threerings.util.Enum;
public final class DeviceType extends Enum
{
public static const IPHONE :DeviceType = new DeviceType("IPHONE", "iPhone", "", 480, 320);
public static const IPHONE_RETINA :DeviceType = new DeviceType("IPHONE_RETINA", "iPhone Retina",
"@2x", 960, 640);
public static const IPAD :DeviceType = new DeviceType("IPAD", "iPad", "", 1024, 768);
public static const IPAD_RETINA :DeviceType = new DeviceType("IPAD_RETINA", "iPad Retina",
"", 2048, 1536);
finishedEnumerating(DeviceType);
public function get displayName () :String { return _displayName; }
public function get extension () :String { return _extension; }
public function get resWidth () :int { return _resWidth; }
public function get resHeight () :int { return _resHeight; }
public function DeviceType (name :String, displayName :String, extension :String,
resWidth :int, resHeight :int) {
super(name);
_displayName = displayName;
_extension = extension;
_resWidth = resWidth;
_resHeight = resHeight;
}
public static function valueOf (name :String) :DeviceType {
return Enum.valueOf(DeviceType, name) as DeviceType;
}
public static function values () :Array { return Enum.values(DeviceType); }
protected var _displayName :String;
protected var _extension :String;
protected var _resWidth :int;
protected var _resHeight :int;
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import com.threerings.util.Enum;
public final class DeviceType extends Enum
{
public static const IPHONE :DeviceType = new DeviceType("IPHONE", "iPhone", "", 480, 320);
public static const IPHONE_RETINA :DeviceType = new DeviceType("IPHONE_RETINA", "iPhone Retina",
"@2x", 960, 640);
public static const IPAD :DeviceType = new DeviceType("IPAD", "iPad", "", 1024, 768);
public static const IPAD_RETINA :DeviceType = new DeviceType("IPAD_RETINA", "iPad Retina",
"", 2048, 1536);
public static const NOD_TEMP :DeviceType = new DeviceType("NOD_TEMP", "Nod-temp", "", 960*2.67,
640*2.67);
finishedEnumerating(DeviceType);
public function get displayName () :String { return _displayName; }
public function get extension () :String { return _extension; }
public function get resWidth () :int { return _resWidth; }
public function get resHeight () :int { return _resHeight; }
public function DeviceType (name :String, displayName :String, extension :String,
resWidth :int, resHeight :int) {
super(name);
_displayName = displayName;
_extension = extension;
_resWidth = resWidth;
_resHeight = resHeight;
}
public static function valueOf (name :String) :DeviceType {
return Enum.valueOf(DeviceType, name) as DeviceType;
}
public static function values () :Array { return Enum.values(DeviceType); }
protected var _displayName :String;
protected var _extension :String;
protected var _resWidth :int;
protected var _resHeight :int;
}
}
|
add a very temporary Nod-specific DeviceType
|
add a very temporary Nod-specific DeviceType
DeviceType is going to be ripped out soon and replaced with a more
flexible scaling system.
|
ActionScript
|
mit
|
mathieuanthoine/flump,tconkling/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump
|
8a6ca3df2f3e4fa3128b58f8d0573d4214e4c1da
|
src/aerys/minko/render/shader/part/phong/LightAwareShaderPart.as
|
src/aerys/minko/render/shader/part/phong/LightAwareShaderPart.as
|
package aerys.minko.render.shader.part.phong
{
import aerys.minko.ns.minko_lighting;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.ParallaxMappingShaderPart;
import aerys.minko.render.shader.part.ShaderPart;
import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart;
import aerys.minko.scene.data.LightDataProvider;
import aerys.minko.type.enum.NormalMappingType;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.TriangleCulling;
public class LightAwareShaderPart extends ShaderPart
{
use namespace minko_lighting;
private var _vertexAnimationShaderPart : VertexAnimationShaderPart;
private var _parallaxMappingShaderPart : ParallaxMappingShaderPart;
private function get vertexAnimationShaderPart() : VertexAnimationShaderPart
{
_vertexAnimationShaderPart ||= new VertexAnimationShaderPart(main);
return _vertexAnimationShaderPart;
}
private function get parallaxMappingShaderPart() : ParallaxMappingShaderPart
{
_parallaxMappingShaderPart ||= new ParallaxMappingShaderPart(main);
return _parallaxMappingShaderPart;
}
protected function get vsLocalPosition() : SFloat
{
return vertexAnimationShaderPart.getAnimatedVertexPosition();
}
protected function get fsLocalPosition() : SFloat
{
return interpolate(vsLocalPosition);
}
protected function get fsUV() : SFloat
{
var result : SFloat = getVertexAttribute(VertexComponent.UV);
if (meshBindings.propertyExists(BasicProperties.UV_SCALE))
result.scaleBy(meshBindings.getParameter(BasicProperties.UV_SCALE, 2));
if (meshBindings.propertyExists(BasicProperties.UV_OFFSET))
result.incrementBy(meshBindings.getParameter(BasicProperties.UV_OFFSET, 2));
result = interpolate(result.xy);
var normalMappingType : uint = meshBindings.getConstant(
PhongProperties.NORMAL_MAPPING_TYPE, NormalMappingType.NONE
);
switch (normalMappingType)
{
case NormalMappingType.NONE:
case NormalMappingType.NORMAL:
return result;
case NormalMappingType.PARALLAX:
return parallaxMappingShaderPart.getSteepParallaxMappedUV(result);
default:
throw new Error('Unknown normal mapping type.');
}
}
protected function get vsWorldPosition() : SFloat
{
return localToWorld(vsLocalPosition);
}
protected function get fsWorldPosition() : SFloat
{
return interpolate(vsWorldPosition);
}
protected function get vsLocalNormal() : SFloat
{
return vertexAnimationShaderPart.getAnimatedVertexNormal();
}
protected function get vsWorldNormal() : SFloat
{
var v : SFloat = deltaLocalToWorld(vsLocalNormal);
return normalize(v.xyz);
}
protected function get fsLocalNormal() : SFloat
{
return normalize(interpolate(vsLocalNormal));
}
protected function get fsWorldNormal() : SFloat
{
return normalize(interpolate(deltaLocalToWorld(vsLocalNormal)));
}
protected function get vsLocalTangent() : SFloat
{
var vertexTangent : SFloat = vertexAnimationShaderPart.getAnimatedVertexTangent();
if (meshBindings.getConstant(BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK) != TriangleCulling.BACK)
vertexTangent.negate();
return vertexTangent;
}
protected function get fsLocalTangent() : SFloat
{
return interpolate(fsLocalTangent);
}
protected function get fsTangentNormal() : SFloat
{
var normalMappingType : uint = meshBindings.getConstant(
PhongProperties.NORMAL_MAPPING_TYPE,
NormalMappingType.NONE
);
switch (normalMappingType)
{
case NormalMappingType.NONE:
return normalize(deltaLocalToTangent(fsLocalNormal));
case NormalMappingType.NORMAL:
case NormalMappingType.PARALLAX:
var fsNormalMap : SFloat = meshBindings.getTextureParameter(
PhongProperties.NORMAL_MAP,
meshBindings.getConstant('normalFiltering', SamplerFiltering.LINEAR),
meshBindings.getConstant('normalMipMapping', SamplerMipMapping.LINEAR)
);
var fsPixel : SFloat = sampleTexture(fsNormalMap, fsUV);
fsPixel.scaleBy(2).decrementBy(1);
return normalize(fsPixel.rgb);
default:
throw new Error('Invalid normap mapping type value');
}
}
public function LightAwareShaderPart(main : Shader)
{
super(main);
}
protected function deltaLocalToTangent(v : SFloat) : SFloat
{
var vsLocalNormal : SFloat = this.vsLocalNormal;
var vsLocalTangent : SFloat = this.vsLocalTangent;
var vsLocalBinormal : SFloat = crossProduct(vsLocalNormal, vsLocalTangent);
return float3(
dotProduct3(v, vsLocalTangent),
dotProduct3(v, vsLocalBinormal),
dotProduct3(v, vsLocalNormal)
);
}
protected function deltaWorldToTangent(v : SFloat) : SFloat
{
return deltaLocalToTangent(deltaWorldToLocal(v));
}
protected function lightPropertyExists(lightId : uint, name : String) : Boolean
{
return sceneBindings.propertyExists(
LightDataProvider.getLightPropertyName(name, lightId)
);
}
protected function getLightConstant(lightId : uint,
name : String,
defaultValue : Object = null) : *
{
return sceneBindings.getConstant(
LightDataProvider.getLightPropertyName(name, lightId),
defaultValue
);
}
protected function getLightParameter(lightId : uint, name : String, size : uint) : SFloat
{
return sceneBindings.getParameter(
LightDataProvider.getLightPropertyName(name, lightId),
size
);
}
protected function getLightTextureParameter(lightId : uint,
name : String,
filter : uint = 1,
mipmap : uint = 0,
wrapping : uint = 1,
dimension : uint = 0) : SFloat
{
return sceneBindings.getTextureParameter(
LightDataProvider.getLightPropertyName(name, lightId),
filter,
mipmap,
wrapping,
dimension
);
}
}
}
|
package aerys.minko.render.shader.part.phong
{
import aerys.minko.ns.minko_lighting;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.ParallaxMappingShaderPart;
import aerys.minko.render.shader.part.ShaderPart;
import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart;
import aerys.minko.scene.data.LightDataProvider;
import aerys.minko.type.enum.NormalMappingType;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.TriangleCulling;
public class LightAwareShaderPart extends ShaderPart
{
use namespace minko_lighting;
private var _vertexAnimationShaderPart : VertexAnimationShaderPart;
private var _parallaxMappingShaderPart : ParallaxMappingShaderPart;
private function get vertexAnimationShaderPart() : VertexAnimationShaderPart
{
_vertexAnimationShaderPart ||= new VertexAnimationShaderPart(main);
return _vertexAnimationShaderPart;
}
private function get parallaxMappingShaderPart() : ParallaxMappingShaderPart
{
_parallaxMappingShaderPart ||= new ParallaxMappingShaderPart(main);
return _parallaxMappingShaderPart;
}
protected function get vsLocalPosition() : SFloat
{
return vertexAnimationShaderPart.getAnimatedVertexPosition();
}
protected function get fsLocalPosition() : SFloat
{
return interpolate(vsLocalPosition);
}
protected function get fsUV() : SFloat
{
var result : SFloat = getVertexAttribute(VertexComponent.UV);
if (meshBindings.propertyExists(BasicProperties.UV_SCALE))
result.scaleBy(meshBindings.getParameter(BasicProperties.UV_SCALE, 2));
if (meshBindings.propertyExists(BasicProperties.UV_OFFSET))
result.incrementBy(meshBindings.getParameter(BasicProperties.UV_OFFSET, 2));
result = interpolate(result.xy);
var normalMappingType : uint = meshBindings.getConstant(
PhongProperties.NORMAL_MAPPING_TYPE, NormalMappingType.NONE
);
switch (normalMappingType)
{
case NormalMappingType.NONE:
case NormalMappingType.NORMAL:
return result;
case NormalMappingType.PARALLAX:
return parallaxMappingShaderPart.getSteepParallaxMappedUV(result);
default:
throw new Error('Unknown normal mapping type.');
}
}
protected function get vsWorldPosition() : SFloat
{
return localToWorld(vsLocalPosition);
}
protected function get fsWorldPosition() : SFloat
{
return interpolate(vsWorldPosition);
}
protected function get vsLocalNormal() : SFloat
{
return vertexAnimationShaderPart.getAnimatedVertexNormal();
}
protected function get vsWorldNormal() : SFloat
{
var v : SFloat = deltaLocalToWorld(vsLocalNormal);
return normalize(v.xyz);
}
protected function get fsLocalNormal() : SFloat
{
return normalize(interpolate(vsLocalNormal));
}
protected function get fsWorldNormal() : SFloat
{
return normalize(interpolate(deltaLocalToWorld(vsLocalNormal)));
}
protected function get vsLocalTangent() : SFloat
{
var vertexTangent : SFloat = vertexAnimationShaderPart.getAnimatedVertexTangent();
if (meshBindings.getConstant(BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK)
!= TriangleCulling.BACK)
vertexTangent.negate();
return vertexTangent;
}
protected function get fsLocalTangent() : SFloat
{
return interpolate(fsLocalTangent);
}
protected function get fsTangentNormal() : SFloat
{
var normalMappingType : uint = meshBindings.getConstant(
PhongProperties.NORMAL_MAPPING_TYPE,
NormalMappingType.NONE
);
switch (normalMappingType)
{
case NormalMappingType.NONE:
return normalize(deltaLocalToTangent(fsLocalNormal));
case NormalMappingType.NORMAL:
case NormalMappingType.PARALLAX:
var fsNormalMap : SFloat = meshBindings.getTextureParameter(
PhongProperties.NORMAL_MAP,
meshBindings.getConstant('normalFiltering', SamplerFiltering.LINEAR),
meshBindings.getConstant('normalMipMapping', SamplerMipMapping.LINEAR)
);
var fsPixel : SFloat = sampleTexture(fsNormalMap, fsUV);
fsPixel.scaleBy(2).decrementBy(1);
return normalize(fsPixel.rgb);
default:
throw new Error('Invalid normap mapping type value');
}
}
public function LightAwareShaderPart(main : Shader)
{
super(main);
}
protected function deltaLocalToTangent(v : SFloat) : SFloat
{
var vsLocalNormal : SFloat = this.vsLocalNormal;
var vsLocalTangent : SFloat = this.vsLocalTangent;
var vsLocalBinormal : SFloat = crossProduct(vsLocalNormal, vsLocalTangent);
return float3(
dotProduct3(v, vsLocalTangent),
dotProduct3(v, vsLocalBinormal),
dotProduct3(v, vsLocalNormal)
);
}
protected function deltaWorldToTangent(v : SFloat) : SFloat
{
return deltaLocalToTangent(deltaWorldToLocal(v));
}
protected function lightPropertyExists(lightId : uint, name : String) : Boolean
{
return sceneBindings.propertyExists(
LightDataProvider.getLightPropertyName(name, lightId)
);
}
protected function getLightConstant(lightId : uint,
name : String,
defaultValue : Object = null) : *
{
return sceneBindings.getConstant(
LightDataProvider.getLightPropertyName(name, lightId),
defaultValue
);
}
protected function getLightParameter(lightId : uint, name : String, size : uint) : SFloat
{
return sceneBindings.getParameter(
LightDataProvider.getLightPropertyName(name, lightId),
size
);
}
protected function getLightTextureParameter(lightId : uint,
name : String,
filter : uint = 1,
mipmap : uint = 0,
wrapping : uint = 1,
dimension : uint = 0) : SFloat
{
return sceneBindings.getTextureParameter(
LightDataProvider.getLightPropertyName(name, lightId),
filter,
mipmap,
wrapping,
dimension
);
}
}
}
|
fix coding style
|
fix coding style
|
ActionScript
|
mit
|
aerys/minko-as3
|
bd794a3fd369e8f37d15417d623cf7b9edbd3ee9
|
dolly-framework/src/test/actionscript/dolly/utils/PropertyUtilTests.as
|
dolly-framework/src/test/actionscript/dolly/utils/PropertyUtilTests.as
|
package dolly.utils {
import dolly.core.dolly_internal;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.flexunit.assertThat;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertTrue;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class PropertyUtilTests {
private var sourceObj:Object;
private var targetObj:Object;
[Before]
public function before():void {
sourceObj = {};
sourceObj.array = [0, 1, 2, 3, 4];
sourceObj.arrayList = new ArrayList([0, 1, 2, 3, 4]);
sourceObj.arrayCollection = new ArrayCollection([0, 1, 2, 3, 4]);
targetObj = {};
}
[After]
public function after():void {
sourceObj = targetObj = null;
}
[Test]
public function copyingOfArray():void {
PropertyUtil.copyArray(sourceObj, targetObj, "array");
assertThat(targetObj.array, arrayWithSize(5));
assertThat(targetObj.array, sourceObj.array);
assertTrue(targetObj.array != sourceObj.array);
assertThat(targetObj.array, everyItem(isA(Number)));
assertThat(targetObj.array, array(equalTo(0), equalTo(1), equalTo(2), equalTo(3), equalTo(4)));
}
[Test]
public function copyingOfArrayList():void {
PropertyUtil.copyArrayList(sourceObj, targetObj, "arrayList");
const targetArrayList:ArrayList = targetObj.arrayList;
assertNotNull(targetArrayList);
assertFalse(targetObj.arrayList == sourceObj.arrayList);
assertEquals(targetArrayList.length, 5);
assertEquals(targetArrayList.getItemAt(0), 0);
assertEquals(targetArrayList.getItemAt(1), 1);
assertEquals(targetArrayList.getItemAt(2), 2);
assertEquals(targetArrayList.getItemAt(3), 3);
assertEquals(targetArrayList.getItemAt(4), 4);
}
}
}
|
package dolly.utils {
import dolly.core.dolly_internal;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.flexunit.assertThat;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertTrue;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class PropertyUtilTests {
private var sourceObj:Object;
private var targetObj:Object;
[Before]
public function before():void {
sourceObj = {};
sourceObj.array = [0, 1, 2, 3, 4];
sourceObj.arrayList = new ArrayList([0, 1, 2, 3, 4]);
sourceObj.arrayCollection = new ArrayCollection([0, 1, 2, 3, 4]);
targetObj = {};
}
[After]
public function after():void {
sourceObj = targetObj = null;
}
[Test]
public function copyingOfArray():void {
PropertyUtil.copyArray(sourceObj, targetObj, "array");
assertThat(targetObj.array, arrayWithSize(5));
assertThat(targetObj.array, sourceObj.array);
assertTrue(targetObj.array != sourceObj.array);
assertThat(targetObj.array, everyItem(isA(Number)));
assertThat(targetObj.array, array(equalTo(0), equalTo(1), equalTo(2), equalTo(3), equalTo(4)));
}
[Test]
public function copyingOfArrayList():void {
PropertyUtil.copyArrayList(sourceObj, targetObj, "arrayList");
const targetArrayList:ArrayList = targetObj.arrayList;
assertNotNull(targetArrayList);
assertFalse(targetObj.arrayList == sourceObj.arrayList);
assertEquals(targetArrayList.length, 5);
assertEquals(targetArrayList.getItemAt(0), 0);
assertEquals(targetArrayList.getItemAt(1), 1);
assertEquals(targetArrayList.getItemAt(2), 2);
assertEquals(targetArrayList.getItemAt(3), 3);
assertEquals(targetArrayList.getItemAt(4), 4);
}
[Test]
public function copyingOfArrayCollection():void {
PropertyUtil.copyArrayCollection(sourceObj, targetObj, "arrayCollection");
const targetArrayCollection:ArrayCollection = targetObj.arrayCollection;
assertNotNull(targetArrayCollection);
assertFalse(targetObj.arrayList == sourceObj.arrayList);
assertEquals(targetArrayCollection.length, 5);
assertEquals(targetArrayCollection.getItemAt(0), 0);
assertEquals(targetArrayCollection.getItemAt(1), 1);
assertEquals(targetArrayCollection.getItemAt(2), 2);
assertEquals(targetArrayCollection.getItemAt(3), 3);
assertEquals(targetArrayCollection.getItemAt(4), 4);
}
}
}
|
Test for PropertyUtil.copyArrayCollection() method.
|
Test for PropertyUtil.copyArrayCollection() method.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
ff56b4a2e1ef4a9f8e14ac87a59ac39b610a9f95
|
src/spitfire.as
|
src/spitfire.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
include "corsaair/server/spitfire/SimpleSocketServer.as";
include "corsaair/server/spitfire/SimpleSocketServerSelect.as";
include "corsaair/server/spitfire/SimpleSocketServerSelect2.as";
import corsaair.server.spitfire.*;
// example1
/*
var server = new SimpleSocketServer();
server.main();
*/
// example2
/*
var server = new SimpleSocketServerSelect();
server.showAddressInfo1();
server.showAddressInfo2();
server.showAddressInfo3();
server.showAddressInfo3( "localhost" );
// pass trough cloudflare
server.showAddressInfo3( "www.corsaair.com" );
// direct to the server
server.showAddressInfo3( "www.as3lang.org" );
// more example
server.showAddressInfo3( "www.google.com" );
server.showAddressInfo3( "www.yahoo.com" );
server.showAddressInfo3( "www.cloudflare.com" );
server.main();
*/
// example2
var server = new SimpleSocketServerSelect2();
server.main();
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
include "corsaair/server/spitfire/SimpleSocketServer.as";
include "corsaair/server/spitfire/SimpleSocketServerSelect.as";
include "corsaair/server/spitfire/SimpleSocketServerSelect2.as";
import corsaair.server.spitfire.*;
// example1
/*
var server = new SimpleSocketServer();
server.main();
*/
// example2
/*
var server = new SimpleSocketServerSelect();
server.showAddressInfo1();
server.showAddressInfo2();
server.showAddressInfo3();
server.showAddressInfo3( "localhost" );
// pass trough cloudflare
server.showAddressInfo3( "www.corsaair.com" );
// direct to the server
server.showAddressInfo3( "www.as3lang.org" );
// more example
server.showAddressInfo3( "www.google.com" );
server.showAddressInfo3( "www.yahoo.com" );
server.showAddressInfo3( "www.cloudflare.com" );
server.main();
*/
// example3
var server = new SimpleSocketServerSelect2();
server.main();
|
update main file
|
update main file
git-svn-id: 44dac414ef660a76a1e627c7b7c0e36d248d62e4@22 c2cce57b-6cbb-4450-ba62-5fdab5196ef5
|
ActionScript
|
mpl-2.0
|
Corsaair/spitfire
|
f80f7cf7f675251f34370c43c3c0948610ff5f62
|
com/segonquart/idiomesAnimation.as
|
com/segonquart/idiomesAnimation.as
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class idiomesAnimation extends Movieclip
{
private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function idiomesAnimation():Void
{
this.onEnterFrame = this.enterSlide;
}
private function enterSlide()
{
arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);
return this;
}
public function IdiomesColour()
{
this.onRelease = this arrayColour;
target = this.arrayLang_arr[i];
target._tint = 0x8DC60D;
return this;
}
private function arrayColour()
{
for ( var:i ; arrayLang_arr[i] <4; i++)
{
this.colorTo("#628D22", 0.3, "easeOutCirc");
_parent.colorTo('#4b4b4b', 1, 'linear', .2);
}
}
}
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class idiomesAnimation extends Movieclip
{
private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function idiomesAnimation():Void
{
this.onEnterFrame = this.enterSlide;
}
private function onSlideIN()
{
this.stop();
this.onEnterFrame = this.enterSlide;
}
private function enterSlide()
{
arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);
}
public function IdiomesColour()
{
this.onRelease = this arrayColour;
target = this.arrayLang_arr[i];
target._tint = 0x8DC60D;
return this;
}
private function arrayColour()
{
for ( var:i ; arrayLang_arr[i] <4; i++)
{
this.colorTo("#628D22", 0.3, "easeOutCirc");
_parent.colorTo('#4b4b4b', 1, 'linear', .2);
}
}
}
|
Update idiomesAnimation.as
|
Update idiomesAnimation.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
c12519e26081e30e9898ce9b552c8b32ef92a088
|
bin/Data/Scripts/Player.as
|
bin/Data/Scripts/Player.as
|
shared class Player: ScriptObject
{
float RestingFriction;
float MovingFriction;
float pitch_;
float yaw_;
Node@ cameraMount_;
Vector3 debugDirection_;
Player()
{
pitch_ = 0.0f;
yaw_ = 0.0f;
RestingFriction = MovingFriction = 2.0f;
}
void Start()
{
SubscribeToEvent("KeyDown", "HandleKeyDown");
SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
}
void DelayedStart()
{
cameraMount_ = node.GetChild("CameraMount", true);
}
void Update(float timestep)
{
const float MOVEMENT_STRENGTH = 20.0f;
const float MOUSE_SENSITIVITY = 0.1f;
IntVector2 mouseMove = input.mouseMove;
yaw_ += MOUSE_SENSITIVITY * mouseMove.x;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y;
pitch_ = Clamp(pitch_, -15.0f, 15.0f);
cameraMount_.rotation = Quaternion(pitch_, yaw_, 0.0f);
Vector3 direction = Vector3::ZERO;
if (input.keyDown[KEY_W] || input.keyDown[KEY_UP])
{
direction += Vector3::FORWARD;
}
if (input.keyDown[KEY_S] || input.keyDown[KEY_DOWN])
{
direction += Vector3::BACK;
}
if (input.keyDown[KEY_A] || input.keyDown[KEY_LEFT])
{
direction += Vector3::LEFT;
}
if (input.keyDown[KEY_D] || input.keyDown[KEY_RIGHT])
{
direction += Vector3::RIGHT;
}
RigidBody@ rigidBody = node.GetComponent("RigidBody");
if (direction != Vector3::ZERO)
{
Quaternion dirRotation = Quaternion(0.0f, yaw_, 0.0f);
direction = dirRotation * direction;
debugDirection_ = direction;
direction *= MOVEMENT_STRENGTH;
rigidBody.friction = MovingFriction;
rigidBody.ApplyForce(direction);
}
else
{
rigidBody.friction = RestingFriction;
}
}
void Save(Serializer& serializer)
{
serializer.WriteFloat(MovingFriction);
serializer.WriteFloat(RestingFriction);
}
void Load(Deserializer& deserializer)
{
MovingFriction = deserializer.ReadFloat();
RestingFriction = deserializer.ReadFloat();
}
void Stop()
{
}
void HandleKeyDown(StringHash type, VariantMap& data)
{
if (data["Key"] == KEY_ESCAPE)
{
engine.Exit();
}
}
void HandlePostRenderUpdate(StringHash type, VariantMap& data)
{
if (input.keyDown[KEY_P])
{
DebugRenderer@ debugRenderer = node.scene.GetComponent("DebugRenderer");
PhysicsWorld@ world = node.scene.GetComponent("PhysicsWorld");
Vector3 origin = node.position + Vector3::UP;
Vector3 target = node.position + debugDirection_ * 2 + Vector3::UP;
debugRenderer.AddLine(origin, target, Color(1.0, 0, 0));
world.DrawDebugGeometry(debugRenderer, true);
}
}
}
|
shared class Player: ScriptObject
{
float RestingFriction;
float MovingFriction;
float pitch_;
float yaw_;
Quaternion modelRotation_;
Node@ cameraMountNode_;
Node@ modelNode_;
Vector3 debugDirection_;
Player()
{
pitch_ = 0.0f;
yaw_ = 0.0f;
RestingFriction = MovingFriction = 2.0f;
}
void Start()
{
SubscribeToEvent("KeyDown", "HandleKeyDown");
SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
}
void DelayedStart()
{
cameraMountNode_ = node.GetChild("CameraMount", true);
modelNode_ = node.GetChild("Model", true);
modelRotation_ = modelNode_.rotation;
}
void Update(float timestep)
{
const float MOVEMENT_STRENGTH = 20.0f;
const float MOVEMENT_MARGIN = 0.1f;
const float MOUSE_SENSITIVITY = 0.1f;
IntVector2 mouseMove = input.mouseMove;
yaw_ += MOUSE_SENSITIVITY * mouseMove.x;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y;
pitch_ = Clamp(pitch_, -15.0f, 15.0f);
cameraMountNode_.rotation = Quaternion(pitch_, yaw_, 0.0f);
Vector3 direction = Vector3::ZERO;
if (input.keyDown[KEY_W] || input.keyDown[KEY_UP])
{
direction += Vector3::FORWARD;
}
if (input.keyDown[KEY_S] || input.keyDown[KEY_DOWN])
{
direction += Vector3::BACK;
}
if (input.keyDown[KEY_A] || input.keyDown[KEY_LEFT])
{
direction += Vector3::LEFT;
}
if (input.keyDown[KEY_D] || input.keyDown[KEY_RIGHT])
{
direction += Vector3::RIGHT;
}
RigidBody@ rigidBody = node.GetComponent("RigidBody");
if (direction != Vector3::ZERO)
{
Quaternion dirRotation = Quaternion(0.0f, yaw_, 0.0f);
direction = dirRotation * direction;
debugDirection_ = direction;
direction *= MOVEMENT_STRENGTH;
rigidBody.friction = MovingFriction;
rigidBody.ApplyForce(direction);
}
else
{
rigidBody.friction = RestingFriction;
}
if (rigidBody.linearVelocity.lengthSquared > MOVEMENT_MARGIN)
{
Vector3 lateralVelocity = Vector3(rigidBody.linearVelocity.x, 0, rigidBody.linearVelocity.z);
Quaternion lateralRotation;
lateralRotation.FromLookRotation(lateralVelocity, Vector3::UP);
lateralRotation = lateralRotation * modelRotation_;
modelNode_.rotation = modelNode_.rotation.Nlerp(lateralRotation, 0.3, true);
}
}
void Save(Serializer& serializer)
{
serializer.WriteFloat(MovingFriction);
serializer.WriteFloat(RestingFriction);
}
void Load(Deserializer& deserializer)
{
MovingFriction = deserializer.ReadFloat();
RestingFriction = deserializer.ReadFloat();
}
void Stop()
{
}
void HandleKeyDown(StringHash type, VariantMap& data)
{
if (data["Key"] == KEY_ESCAPE)
{
engine.Exit();
}
}
void HandlePostRenderUpdate(StringHash type, VariantMap& data)
{
if (input.keyDown[KEY_P])
{
DebugRenderer@ debugRenderer = node.scene.GetComponent("DebugRenderer");
PhysicsWorld@ world = node.scene.GetComponent("PhysicsWorld");
Vector3 origin = node.position + Vector3::UP;
Vector3 moveTarget = origin + debugDirection_ * 2;
Vector3 faceTarget = (modelNode_.rotation * Vector3::FORWARD) * 3 + origin;
debugRenderer.AddLine(origin, faceTarget, Color(0, 1, 0));
debugRenderer.AddLine(origin, moveTarget, Color(1.0, 0, 0));
world.DrawDebugGeometry(debugRenderer, true);
}
}
}
|
Add rotation to the player movement
|
Add rotation to the player movement
|
ActionScript
|
mit
|
leyarotheconquerer/on-off
|
3a13f09399e0864110731230fa1c1b3414a40a3d
|
build-aux/urbi.as
|
build-aux/urbi.as
|
## -*- shell-script -*-
## urbi.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_pattern_allow([^URBI_SERVER$])
m4_divert_text([URBI-INIT],
[
# check_dir VARIABLE WITNESS
# --------------------------
# Check that VARIABLE contains a directory name that contains WITNESS.
check_dir ()
{
local var=$[1]
local witness=$[2]
local dir
eval "dir=\$$[1]"
test x"$dir" != x ||
fatal "undefined variable: $var"
shift
test -e "$dir" ||
fatal "$var does not exist: $dir" "(pwd = $(pwd))"
test -d "$dir" ||
fatal "$var is not a directory: $dir" "(pwd = $(pwd))"
if test x"$witness" != x; then
test -f "$dir/$witness" ||
fatal "$var does not contain $witness: $dir" "(pwd = $(pwd))"
fi
}
# check_and_abs_dir VAR WITNESS
# -----------------------------
# Check that $VAR/WITNESS exists, and set VAR to $(absolute $VAR).
check_and_abs_dir ()
{
local var=$[1]
local witness=$[2]
check_dir "$[@]"
# Normalize the directory name, and as safety belts, run the same
# tests on it. But save time if possible. So put in "$@" the dirs
# to check, the last one being the actual result.
AS_IF([! is_absolute "$val"],
[local dir
eval "dir=\$$[1]"
dir=$(absolute "$val")
check_dir "$dir" "$witness"
eval "$var='$dir'"
])
}
# find_srcdir WITNESS
# -------------------
# Find the location of the src directory of the tests suite.
# Make sure the value is correct by checking for the presence of WITNESS.
find_srcdir ()
{
# Guess srcdir if not defined.
if test -z "$srcdir"; then
# Try to compute it from $[0].
srcdir=$(dirname "$[0]")
fi
check_dir srcdir "$[1]"
}
# find_top_builddir [POSSIBILITIES]
# ---------------------------------
# Set/check top_builddir.
# - $top_builddir if the user wants to define it,
# - (dirname $0)/.. since that's where we are supposed to be
# - ../.. for the common case where we're in tests/my-test.dir
# - .. if we're in tests/
# - . if we're in top-builddir.
find_top_builddir ()
{
if test x"$top_builddir" = x; then
if test $[#] = 0; then
set $(dirname "$0")/.. ../.. .. .
fi
for d
do
if test -f "$d/config.status"; then
top_builddir=$d
break
fi
done
fi
check_dir top_builddir "config.status"
}
# find_urbi_server
# ----------------
# Set URBI_SERVER to the location of urbi-server.
find_urbi_server ()
{
case $URBI_SERVER in
('')
# If URBI_SERVER is not defined, try to find one. If we are in
# $top_builddir/tests/TEST.dir, then look in $top_builddir/src.
URBI_SERVER=$(find_prog "urbi-server" \
"$top_builddir/src${PATH_SEPARATOR}.")
;;
(*[[\\/]]*) # A path, relative or absolute. Make it absolute.
URBI_SERVER=$(absolute "$URBI_SERVER")
;;
(*) # A simple name, most certainly urbi-server.
# Find it in the PATH.
local res
res=$(find_prog "$URBI_SERVER")
# If we can't find it, then ucore-pc was probably not installed.
# Skip.
test x"$res" != x ||
error 77 "cannot find $URBI_SERVER in $PATH"
URBI_SERVER=$res
;;
esac
if test -z "$URBI_SERVER"; then
fatal "cannot find urbi-server, please define URBI_SERVER"
fi
if test ! -f "$URBI_SERVER"; then
fatal "cannot find urbi-server, please check \$URBI_SERVER: $URBI_SERVER"
fi
# Check its version.
if ! run "Server version" "$URBI_SERVER" --version >&3; then
fatal "cannot run $URBI_SERVER --version"
fi
}
# spawn_urbi_server FLAGS
# -----------------------
# Spawn an $URBI_SERVER in back-ground, registering it as the child "server".
# Wait until the server.port file is created. Make it fatal if this does
# not happen with 10s.
spawn_urbi_server ()
{
rm -f server.port
local flags="--port 0 --port-file server.port $*"
local cmd="$(instrument "server.val") $URBI_SERVER $flags"
echo "$cmd" >server.cmd
$cmd </dev/null >server.out 2>server.err &
children_register server
# Wait for the port file to be completed: it must have one full line
# (with \n to be sure it is complete).
local t=0
local tmax=8
local dt=.5
while test ! -f server.port || test $(wc -l <server.port) = 0;
do
test $t -lt $tmax ||
fatal "$URBI_SERVER did not issue port in server.port in ${tmax}s"
sleep $dt
t=$(($t + $dt))
done
}
])
|
## -*- shell-script -*-
## urbi.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##
m4_pattern_allow([^URBI_SERVER$])
m4_divert_text([URBI-INIT],
[
# check_dir VARIABLE WITNESS
# --------------------------
# Check that VARIABLE contains a directory name that contains WITNESS.
check_dir ()
{
local var=$[1]
local witness=$[2]
local dir
eval "dir=\$$[1]"
test x"$dir" != x ||
fatal "undefined variable: $var"
shift
test -e "$dir" ||
fatal "$var does not exist: $dir" "(pwd = $(pwd))"
test -d "$dir" ||
fatal "$var is not a directory: $dir" "(pwd = $(pwd))"
if test x"$witness" != x; then
test -f "$dir/$witness" ||
fatal "$var does not contain $witness: $dir" "(pwd = $(pwd))"
fi
}
# check_and_abs_dir VAR WITNESS
# -----------------------------
# Check that $VAR/WITNESS exists, and set VAR to $(absolute $VAR).
check_and_abs_dir ()
{
local var=$[1]
local witness=$[2]
check_dir "$[@]"
# Normalize the directory name, and as safety belts, run the same
# tests on it. But save time if possible. So put in "$@" the dirs
# to check, the last one being the actual result.
AS_IF([! is_absolute "$val"],
[local dir
eval "dir=\$$[1]"
dir=$(absolute "$val")
check_dir "$dir" "$witness"
eval "$var='$dir'"
])
}
# find_srcdir WITNESS
# -------------------
# Find the location of the src directory of the tests suite.
# Make sure the value is correct by checking for the presence of WITNESS.
find_srcdir ()
{
# Guess srcdir if not defined.
if test -z "$srcdir"; then
# Try to compute it from $[0].
srcdir=$(dirname "$[0]")
fi
check_dir srcdir "$[1]"
}
# find_top_builddir [POSSIBILITIES]
# ---------------------------------
# Set/check top_builddir.
# - $top_builddir if the user wants to define it,
# - (dirname $0)/.. since that's where we are supposed to be
# - ../.. for the common case where we're in tests/my-test.dir
# - .. if we're in tests/
# - . if we're in top-builddir.
find_top_builddir ()
{
if test x"$top_builddir" = x; then
if test $[#] = 0; then
set $(dirname "$0")/.. ../.. .. .
fi
for d
do
if test -f "$d/config.status"; then
top_builddir=$d
break
fi
done
fi
check_dir top_builddir "config.status"
}
# find_urbi_server
# ----------------
# Set URBI_SERVER to the location of urbi-server.
find_urbi_server ()
{
case $URBI_SERVER in
('')
# If URBI_SERVER is not defined, try to find one. If we are in
# $top_builddir/tests/TEST.dir, then look in $top_builddir/src.
URBI_SERVER=$(find_prog "urbi-server" \
"$top_builddir/src${PATH_SEPARATOR}.")
;;
(*[[\\/]]*) # A path, relative or absolute. Make it absolute.
URBI_SERVER=$(absolute "$URBI_SERVER")
;;
(*) # A simple name, most certainly urbi-server.
# Find it in the PATH.
local res
res=$(find_prog "$URBI_SERVER")
# If we can't find it, then ucore-pc was probably not installed.
# Skip.
test x"$res" != x ||
error 77 "cannot find $URBI_SERVER in $PATH"
URBI_SERVER=$res
;;
esac
if test -z "$URBI_SERVER"; then
fatal "cannot find urbi-server, please define URBI_SERVER"
fi
if test ! -f "$URBI_SERVER"; then
fatal "cannot find urbi-server, please check \$URBI_SERVER: $URBI_SERVER"
fi
# Check its version.
if ! run "Server version" "$URBI_SERVER" --version >&3; then
fatal "cannot run $URBI_SERVER --version"
fi
}
# spawn_urbi_server FLAGS
# -----------------------
# Spawn an $URBI_SERVER in back-ground, registering it as the child "server".
# Wait until the server.port file is created. Make it fatal if this does
# not happen with 10s.
spawn_urbi_server ()
{
rm -f server.port
local flags="--port 0 --port-file server.port $*"
local cmd="$(instrument "server.val") $URBI_SERVER $flags"
echo "$cmd" >server.cmd
$cmd </dev/null >server.out 2>server.err &
children_register server
# Wait for the port file to be completed: it must have one full line
# (with \n to be sure it is complete).
local t=0
local tmax=8
local dt=.5
while test ! -f server.port || test $(wc -l <server.port) = 0;
do
# test/expr don't like floating points.
case $(echo "$t <= $tmax" | bc) in
(1) sleep $dt
t=$(echo "$t + $dt" | bc);;
(0)
fatal "$URBI_SERVER did not issue port in server.port in ${tmax}s";;
esac
done
}
])
|
test and expr have problems with floats.
|
test and expr have problems with floats.
* build-aux/urbi.as: Use bc instead.
|
ActionScript
|
bsd-3-clause
|
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
|
5fedf2d2724af45c435760b16e94d1682a15009f
|
src/aerys/minko/scene/controller/ScriptController.as
|
src/aerys/minko/scene/controller/ScriptController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import flash.display.BitmapData;
public class ScriptController extends EnterFrameController
{
private var _lastTime : Number = 0.0;
private var _deltaTime : Number = 0.0;
private var _currentTarget : ISceneNode = null;
private var _viewport : Viewport = null;
protected function get deltaTime() : Number
{
return _deltaTime;
}
protected function get keyboard() : KeyboardManager
{
return _viewport.keyboardManager;
}
protected function get mouse() : MouseManager
{
return _viewport.mouseManager;
}
protected function get viewport() : Viewport
{
return _viewport;
}
public function ScriptController(targetType : Class = null)
{
super(targetType);
initialize();
}
private function initialize() : void
{
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
start(getTarget(i));
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
_viewport = viewport;
_deltaTime = _lastTime - time;
_lastTime = time;
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
update(getTarget(i));
}
protected function start(target : ISceneNode) : void
{
// nothing
}
protected function update(target : ISceneNode) : void
{
// nothing
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import flash.display.BitmapData;
public class ScriptController extends EnterFrameController
{
private var _lastTime : Number = 0.0;
private var _deltaTime : Number = 0.0;
private var _currentTarget : ISceneNode = null;
private var _viewport : Viewport = null;
protected function get deltaTime() : Number
{
return _deltaTime;
}
protected function get keyboard() : KeyboardManager
{
return _viewport.keyboardManager;
}
protected function get mouse() : MouseManager
{
return _viewport.mouseManager;
}
protected function get viewport() : Viewport
{
return _viewport;
}
public function ScriptController(targetType : Class = null)
{
super(targetType);
initialize();
}
private function initialize() : void
{
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
start(getTarget(i));
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
_viewport = viewport;
_deltaTime = _lastTime - time;
_lastTime = time;
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
update(getTarget(i));
}
override protected function targetRemovedFromSceneHandler(target : ISceneNode,
scene : Scene) : void
{
super.targetRemovedFromSceneHandler(target, scene);
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
stop(getTarget(i));
}
protected function start(target : ISceneNode) : void
{
// nothing
}
protected function update(target : ISceneNode) : void
{
// nothing
}
protected function stop(target : ISceneNode) : void
{
// nothing
}
}
}
|
add ScriptController.stop(target), called when the target is removed from the scene
|
add ScriptController.stop(target), called when the target is removed from the scene
|
ActionScript
|
mit
|
aerys/minko-as3
|
0a0c2d3baebd9bed995f2e8fb24349ac35cc0184
|
src/com/ryanberdeen/echonest/api/v4/track/TrackApi.as
|
src/com/ryanberdeen/echonest/api/v4/track/TrackApi.as
|
/*
* Copyright 2011 Ryan Berdeen. All rights reserved.
* Distributed under the terms of the MIT License.
* See accompanying file LICENSE.txt
*/
package com.ryanberdeen.echonest.api.v4.track {
import com.ryanberdeen.echonest.api.v4.ApiSupport;
import com.ryanberdeen.echonest.api.v4.EchoNestError;
import flash.events.DataEvent;
import flash.events.Event;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
/**
* Methods to interact with the Echo Nest track API.
*
* <p>All of the API methods in this class accept basically the same
* parameters. The <code>parameters</code> parameter contains the parameters
* to pass to the Echo Nest method. For most methods, this will be
* <strong><code>id</code></strong> or <strong><code>md5</code></strong>.
* The <code>api_key</code> parameter will always be
* set.</p>
*
* <p>The <code>loaderOptions</code> parameter contains the event listeners
* for the loading process. Most importantly, the
* <strong><code>onResponse</code></strong> method will be called with the
* results of the API method. See the <code>ApiSupport.createLoader()</code>
* method for a description of the loader options.</p>
*
* <p>For a description of the response formats, see the various
* <code>process...Response()</code> methods.</p>
*
* <p>Be sure to set the <code>apiKey</code> property before calling any API
* methods.</p>
*/
public class TrackApi extends ApiSupport {
/**
* Adds the standard Echo Nest Flash API event listeners to a file
* reference.
*
* @param options The event listener options. See
* <code>createLoader()</code> for the list of available options.
* @param dispatcher The file reference to add the event listeners to.
*/
public function addFileReferenceEventListeners(options:Object, fileReference:FileReference, responseProcessor:Function, ...responseProcessorArgs):void {
if (options.onComplete) {
fileReference.addEventListener(Event.COMPLETE, options.onComplete);
}
if (options.onResponse) {
fileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, function(e:DataEvent):void {
try {
var responseObject:* = parseRawResponse(e.data);
responseProcessorArgs.push(responseObject);
var response:Object = responseProcessor.apply(responseProcessor, responseProcessorArgs);
options.onResponse(response);
}
catch (e:EchoNestError) {
if (options.onEchoNestError) {
options.onEchoNestError(e);
}
}
});
}
addEventListeners(options, fileReference);
}
/**
* Processes the response from the <code>upload</code> API method.
*
* @param response The response to process.
*
* @return The result of processing the response.
*
* @see #upload()
* @see #uploadFileData()
*/
public function processUploadResponse(response:*):Object {
return response.track;
}
/**
* Invokes the Echo Nest <code>upload</code> API method with a file
* reference.
*
* <p>The <code>parameters</code> object must include a <code>track</code>
* property, which must be a <code>FileReference</code> that may be
* <code>upload()</code>ed.</p>
*
* @param parameters The parameters to include in the API request.
* @param loaderOptions The event listener options for the loader.
*
* @see com.ryanberdeen.echonest.api.v3.ApiSupport#createRequest()
* @see #processUploadResponse()
* @see http://developer.echonest.com/docs/v4/track.html#upload
*/
public function uploadFileReference(parameters:Object, loaderOptions:Object):URLRequest {
var fileReference:FileReference = parameters.track;
delete parameters.track;
addFileReferenceEventListeners(loaderOptions, fileReference, processUploadResponse);
var request:URLRequest = createRequest('track/upload', parameters);
fileReference.upload(request, 'track');
return request;
}
/**
* Invokes the Echo Nest <code>upload</code> API method.
*
* <p>This method is for uploads using the <code>url</code> parameter.
* To upload a file, use <code>uploadFileReference()</code>.
*
* @param parameters The parameters to include in the API request.
* @param loaderOptions The event listener options for the loader.
*
* @return The <code>URLLoader</code> being used to perform the API call.
*
* @see com.ryanberdeen.echonest.api.v4.ApiSupport#createRequest()
* @see com.ryanberdeen.echonest.api.v4.ApiSupport#createLoader()
* @see #processUploadResponse()
* @see http://developer.echonest.com/docs/v4/track.html#upload
*/
public function upload(parameters:Object, loaderOptions:Object):URLLoader {
var request:URLRequest = createRequest('track/upload', parameters);
request.method = URLRequestMethod.POST;
var loader:URLLoader = createLoader(loaderOptions, processUploadResponse);
loader.load(request);
return loader;
}
}
}
|
/*
* Copyright 2011 Ryan Berdeen. All rights reserved.
* Distributed under the terms of the MIT License.
* See accompanying file LICENSE.txt
*/
package com.ryanberdeen.echonest.api.v4.track {
import com.adobe.serialization.json.JSON;
import com.ryanberdeen.echonest.api.v4.ApiSupport;
import com.ryanberdeen.echonest.api.v4.EchoNestError;
import flash.events.DataEvent;
import flash.events.Event;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
/**
* Methods to interact with the Echo Nest track API.
*
* <p>All of the API methods in this class accept basically the same
* parameters. The <code>parameters</code> parameter contains the parameters
* to pass to the Echo Nest method. For most methods, this will be
* <strong><code>id</code></strong> or <strong><code>md5</code></strong>.
* The <code>api_key</code> parameter will always be
* set.</p>
*
* <p>The <code>loaderOptions</code> parameter contains the event listeners
* for the loading process. Most importantly, the
* <strong><code>onResponse</code></strong> method will be called with the
* results of the API method. See the <code>ApiSupport.createLoader()</code>
* method for a description of the loader options.</p>
*
* <p>For a description of the response formats, see the various
* <code>process...Response()</code> methods.</p>
*
* <p>Be sure to set the <code>apiKey</code> property before calling any API
* methods.</p>
*/
public class TrackApi extends ApiSupport {
/**
* Adds the standard Echo Nest Flash API event listeners to a file
* reference.
*
* @param options The event listener options. See
* <code>createLoader()</code> for the list of available options.
* @param dispatcher The file reference to add the event listeners to.
*/
public function addFileReferenceEventListeners(options:Object, fileReference:FileReference, responseProcessor:Function, ...responseProcessorArgs):void {
// TODO document
if (options.onOpen) {
fileReference.addEventListener(Event.OPEN, options.onOpen);
}
if (options.onComplete) {
fileReference.addEventListener(Event.COMPLETE, options.onComplete);
}
if (options.onResponse) {
fileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, function(e:DataEvent):void {
try {
var responseObject:* = parseRawResponse(e.data);
responseProcessorArgs.push(responseObject);
var response:Object = responseProcessor.apply(responseProcessor, responseProcessorArgs);
options.onResponse(response);
}
catch (e:EchoNestError) {
if (options.onEchoNestError) {
options.onEchoNestError(e);
}
}
});
}
addEventListeners(options, fileReference);
}
public function loadAnalysis(track:Object, loaderOptions:Object):URLLoader {
var loader:URLLoader = new URLLoader();
if (loaderOptions.onComplete) {
loader.addEventListener(Event.COMPLETE, loaderOptions.onComplete);
}
if (loaderOptions.onResponse) {
loader.addEventListener(Event.COMPLETE, function(e:Event):void {
var analysis:Object = JSON.decode(loader.data);
loaderOptions.onResponse(analysis);
});
}
addEventListeners(loaderOptions, loader);
var request:URLRequest = new URLRequest();
request.url = track.audio_summary.analysis_url;
loader.load(request);
return loader;
}
/**
* Processes the response from the <code>upload</code> API method.
*
* @param response The response to process.
*
* @return The result of processing the response.
*
* @see #upload()
* @see #uploadFileData()
*/
public function processUploadResponse(response:*):Object {
return response.track;
}
/**
* Invokes the Echo Nest <code>upload</code> API method with a file
* reference.
*
* <p>The <code>parameters</code> object must include a <code>track</code>
* property, which must be a <code>FileReference</code> that may be
* <code>upload()</code>ed.</p>
*
* @param parameters The parameters to include in the API request.
* @param loaderOptions The event listener options for the loader.
*
* @see com.ryanberdeen.echonest.api.v3.ApiSupport#createRequest()
* @see #processUploadResponse()
* @see http://developer.echonest.com/docs/v4/track.html#upload
*/
public function uploadFileReference(parameters:Object, loaderOptions:Object):URLRequest {
var fileReference:FileReference = parameters.track;
delete parameters.track;
addFileReferenceEventListeners(loaderOptions, fileReference, processUploadResponse);
var request:URLRequest = createRequest('track/upload', parameters);
fileReference.upload(request, 'track');
return request;
}
/**
* Invokes the Echo Nest <code>upload</code> API method.
*
* <p>This method is for uploads using the <code>url</code> parameter.
* To upload a file, use <code>uploadFileReference()</code>.
*
* @param parameters The parameters to include in the API request.
* @param loaderOptions The event listener options for the loader.
*
* @return The <code>URLLoader</code> being used to perform the API call.
*
* @see com.ryanberdeen.echonest.api.v4.ApiSupport#createRequest()
* @see com.ryanberdeen.echonest.api.v4.ApiSupport#createLoader()
* @see #processUploadResponse()
* @see http://developer.echonest.com/docs/v4/track.html#upload
*/
public function upload(parameters:Object, loaderOptions:Object):URLLoader {
var request:URLRequest = createRequest('track/upload', parameters);
request.method = URLRequestMethod.POST;
var loader:URLLoader = createLoader(loaderOptions, processUploadResponse);
loader.load(request);
return loader;
}
}
}
|
add method to download track analysis
|
add method to download track analysis
|
ActionScript
|
mit
|
also/echo-nest-flash-api
|
621f2100004d798978d68b6e6dbba5fc5e7580c8
|
exporter/src/test/as/flump/test/RuntimePlaybackTest.as
|
exporter/src/test/as/flump/test/RuntimePlaybackTest.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.test {
import flash.events.TimerEvent;
import flash.utils.Timer;
import flump.display.Movie;
import flump.display.StarlingResources;
import flump.executor.Finisher;
import com.threerings.util.F;
public class RuntimePlaybackTest
{
public static function addTests (runner :TestRunner, res :StarlingResources) :void {
runner.run("Goto frame and label", new RuntimePlaybackTest(runner, res).gotoFrameAndLabel);
runner.runAsync("Play, stop, loop", new RuntimePlaybackTest(runner, res).playStopLoop);
runner.runAsync("Stop, play", new RuntimePlaybackTest(runner, res).stopPlay);
runner.runAsync("Play when added", new RuntimePlaybackTest(runner, res).playWhenAdded);
runner.runAsync("Play once", new RuntimePlaybackTest(runner, res).playOnce);
runner.runAsync("Pause while removed", new RuntimePlaybackTest(runner, res).pauseWhileRemoved);
}
public function RuntimePlaybackTest (runner :TestRunner, res :StarlingResources) {
_runner = runner;
_res = res;
}
protected function setup (finisher :Finisher) :void {
_finisher = finisher;
_movie = _res.loadMovie("nesteddance");
assert(_movie.frame == 0, "Frame starts at 0");
assert(_movie.isPlaying, "Movie starts out playing");
_runner.addChild(_movie);
_movie.labelPassed.add(_labelsPassed.push);
}
public function gotoFrameAndLabel () :void {
_movie = _res.loadMovie("nesteddance");
_movie.goto("timepassed");
assert(_movie.frame == 9);
assert(_movie.isPlaying, "Playing changed in goto");
_movie.stop();
_movie.goto(_movie.frame + 1);
assert(_movie.frame == 10);
assert(!_movie.isPlaying, "Stopped changed in goto");
assertThrows(F.callback(_movie.goto, _movie.frames), "Went past frames");
assertThrows(F.callback(_movie.goto, "nonexistent label"), "Went to nonexistent label");
}
public function playWhenAdded (finisher :Finisher) :void {
setup(finisher);
delayForAtLeastOneFrame(checkAdvanced);
}
public function checkAdvanced () :void {
assert(_movie.frame > 0, "Frame advances with time");
delayForOnePlaythrough(checkAllLabelsFired);
}
public function checkAllLabelsFired () :void {
_runner.removeChild(_movie);
passedAllLabels();
_finisher.succeed();
}
public function playOnce (finisher :Finisher) :void {
setup(finisher);
_movie.goto(0).play();
delayForOnePlaythrough(checkPlayOnce);
}
public function checkPlayOnce () :void {
passedAllLabels();
assert(_labelsPassed.length == 4, "Only pass the labels once");
assert(_movie.frame == _movie.frames - 1, "Play once stops at last frame");
_runner.removeChild(_movie);
_finisher.succeed();
}
public function pauseWhileRemoved (finisher :Finisher) :void {
setup(finisher);
delayForAtLeastOneFrame(checkAdvancedToRemove);
}
public function checkAdvancedToRemove () :void {
assert(_movie.frame > 0, "Playing initially");
assert(_labelsPassed.length == 0, "Passed labels initially?");
_runner.removeChild(_movie);
delayForOnePlaythrough(checkNotAdvancedWhileRemoved);
}
public function checkNotAdvancedWhileRemoved () :void {
assert(_labelsPassed.length == 0, "Labels passed while removed?");
_runner.addChild(_movie);
delayForOnePlaythrough(checkAllLabelsFired);
}
public function stopPlay (finisher :Finisher) :void {
setup(finisher);
_movie.stop();
delayForAtLeastOneFrame(checkNotAdvancedWhileStopped);
}
public function checkNotAdvancedWhileStopped () :void {
assert(_movie.frame == 0, "Frame advanced passed while stopped?");
_movie.goto(Movie.FIRST_FRAME).playTo("timepassed");
delayForOnePlaythrough(checkPlayedToTimePassed);
}
public function checkPlayedToTimePassed () :void {
passed(Movie.FIRST_FRAME);
passed("timepassed");
assert(_labelsPassed.length == 2, "Should stop at timepassed: " + _labelsPassed);
_runner.removeChild(_movie);
_finisher.succeed();
}
public function playStopLoop (finisher :Finisher) :void {
setup(finisher);
_movie.goto(10).play().stop().loop();
assert(_movie.frame == 10, "Play stop or loop changed the frame");
delayFor(2.6, checkDoublePass);
}
public function checkDoublePass () :void {
passedAllLabels();
assert(_labelsPassed.length >= 8);
_runner.removeChild(_movie);
_finisher.succeed();
}
public function passedAllLabels () :void {
passed("timepassed");
passed("moretimepassed");
passed(Movie.LAST_FRAME);
passed(Movie.FIRST_FRAME);
}
protected function passed (label :String) :void {
assert(_labelsPassed.indexOf(label) != -1, "Should've passed " + label);
}
protected function delayForOnePlaythrough (then :Function) :void { delayFor(1.3, then); }
protected function delayForAtLeastOneFrame (then :Function) :void { delayFor(.1, then); }
protected function delayFor (seconds :Number, then :Function) :void {
const t :Timer = new Timer(1000 * seconds);
t.addEventListener(TimerEvent.TIMER, function (..._) :void { postDelay(t, then); });
t.start();
}
protected function postDelay (t :Timer, then :Function) :void {
t.stop();
_finisher.monitor(then);
}
protected var _finisher :Finisher;
protected var _movie :Movie;
protected var _runner :TestRunner;
protected var _res :StarlingResources;
protected var _t :Timer = new Timer(1);
protected const _labelsPassed :Vector.<String> = new Vector.<String>();
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.test {
import flash.events.TimerEvent;
import flash.utils.Timer;
import flump.display.Movie;
import flump.display.StarlingResources;
import flump.executor.Finisher;
import com.threerings.util.F;
public class RuntimePlaybackTest
{
public static function addTests (runner :TestRunner, res :StarlingResources) :void {
runner.run("Goto frame and label", new RuntimePlaybackTest(runner, res).gotoFrameAndLabel);
runner.runAsync("Play, stop, loop", new RuntimePlaybackTest(runner, res).playStopLoop);
runner.runAsync("Stop, play", new RuntimePlaybackTest(runner, res).stopPlay);
runner.runAsync("Play when added", new RuntimePlaybackTest(runner, res).playWhenAdded);
runner.runAsync("Play once", new RuntimePlaybackTest(runner, res).playOnce);
runner.runAsync("Pause while removed", new RuntimePlaybackTest(runner, res).pauseWhileRemoved);
}
public function RuntimePlaybackTest (runner :TestRunner, res :StarlingResources) {
_runner = runner;
_res = res;
}
protected function setup (finisher :Finisher) :void {
_finisher = finisher;
_movie = _res.loadMovie("nesteddance");
assert(_movie.frame == 0, "Frame starts at 0");
assert(_movie.isPlaying, "Movie starts out playing");
_runner.addChild(_movie);
_movie.labelPassed.add(_labelsPassed.push);
}
public function gotoFrameAndLabel () :void {
_movie = _res.loadMovie("nesteddance");
_movie.labelPassed.add(_labelsPassed.push);
_movie.goto("timepassed");
assert(_movie.frame == 9);
passed("timepassed");
assert(_labelsPassed.length == 1);
_movie.goto("timepassed");
assert(_labelsPassed.length == 2);
assert(_movie.isPlaying, "Playing changed in goto");
_movie.stop();
_movie.goto(_movie.frame + 1);
assert(_movie.frame == 10);
assert(!_movie.isPlaying, "Stopped changed in goto");
assertThrows(F.callback(_movie.goto, _movie.frames), "Went past frames");
assertThrows(F.callback(_movie.goto, "nonexistent label"), "Went to nonexistent label");
}
public function playWhenAdded (finisher :Finisher) :void {
setup(finisher);
delayForAtLeastOneFrame(checkAdvanced);
}
public function checkAdvanced () :void {
assert(_movie.frame > 0, "Frame advances with time");
delayForOnePlaythrough(checkAllLabelsFired);
}
public function checkAllLabelsFired () :void {
_runner.removeChild(_movie);
passedAllLabels();
_finisher.succeed();
}
public function playOnce (finisher :Finisher) :void {
setup(finisher);
_movie.goto(0).play();
delayForOnePlaythrough(checkPlayOnce);
}
public function checkPlayOnce () :void {
passedAllLabels();
assert(_labelsPassed.length == 4, "Only pass the labels once");
assert(_movie.frame == _movie.frames - 1, "Play once stops at last frame");
_runner.removeChild(_movie);
_finisher.succeed();
}
public function pauseWhileRemoved (finisher :Finisher) :void {
setup(finisher);
delayForAtLeastOneFrame(checkAdvancedToRemove);
}
public function checkAdvancedToRemove () :void {
assert(_movie.frame > 0, "Playing initially");
assert(_labelsPassed.length == 0, "Passed labels initially?");
_runner.removeChild(_movie);
delayForOnePlaythrough(checkNotAdvancedWhileRemoved);
}
public function checkNotAdvancedWhileRemoved () :void {
assert(_labelsPassed.length == 0, "Labels passed while removed?");
_runner.addChild(_movie);
delayForOnePlaythrough(checkAllLabelsFired);
}
public function stopPlay (finisher :Finisher) :void {
setup(finisher);
_movie.stop();
delayForAtLeastOneFrame(checkNotAdvancedWhileStopped);
}
public function checkNotAdvancedWhileStopped () :void {
assert(_movie.frame == 0, "Frame advanced passed while stopped?");
_movie.goto(Movie.FIRST_FRAME).playTo("timepassed");
delayForOnePlaythrough(checkPlayedToTimePassed);
}
public function checkPlayedToTimePassed () :void {
passed(Movie.FIRST_FRAME);
passed("timepassed");
assert(_labelsPassed.length == 2, "Should stop at timepassed: " + _labelsPassed);
_runner.removeChild(_movie);
_finisher.succeed();
}
public function playStopLoop (finisher :Finisher) :void {
setup(finisher);
_movie.goto(10).play().stop().loop();
assert(_movie.frame == 10, "Play stop or loop changed the frame");
delayFor(2.6, checkDoublePass);
}
public function checkDoublePass () :void {
passedAllLabels();
assert(_labelsPassed.length >= 8);
_runner.removeChild(_movie);
_finisher.succeed();
}
public function passedAllLabels () :void {
passed("timepassed");
passed("moretimepassed");
passed(Movie.LAST_FRAME);
passed(Movie.FIRST_FRAME);
}
protected function passed (label :String) :void {
assert(_labelsPassed.indexOf(label) != -1, "Should've passed " + label);
}
protected function delayForOnePlaythrough (then :Function) :void { delayFor(1.3, then); }
protected function delayForAtLeastOneFrame (then :Function) :void { delayFor(.1, then); }
protected function delayFor (seconds :Number, then :Function) :void {
const t :Timer = new Timer(1000 * seconds);
t.addEventListener(TimerEvent.TIMER, function (..._) :void { postDelay(t, then); });
t.start();
}
protected function postDelay (t :Timer, then :Function) :void {
t.stop();
_finisher.monitor(then);
}
protected var _finisher :Finisher;
protected var _movie :Movie;
protected var _runner :TestRunner;
protected var _res :StarlingResources;
protected var _t :Timer = new Timer(1);
protected const _labelsPassed :Vector.<String> = new Vector.<String>();
}
}
|
Check that goto fires labels
|
Check that goto fires labels
|
ActionScript
|
mit
|
mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,tconkling/flump
|
98ac1ce0955d103914dc9227603eeb0d35214f32
|
actionscript/src/com/freshplanet/ane/AirInAppPurchase/InAppPurchase.as
|
actionscript/src/com/freshplanet/ane/AirInAppPurchase/InAppPurchase.as
|
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2012 Freshplanet (http://freshplanet.com | [email protected])
//
// Licensed 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 com.freshplanet.ane.AirInAppPurchase {
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class InAppPurchase extends EventDispatcher {
private var _context:ExtensionContext = null;
private var _iosPendingPurchases:Vector.<Object> = new Vector.<Object>();
private static const EXTENSION_ID:String = "com.freshplanet.AirInAppPurchase";
private static var _instance:InAppPurchase = null;
/**
*
* @param lock
*/
public function InAppPurchase(lock:SingletonLock) {
if (!isSupported)
return;
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
throw Error("Extension context is null. Please check if extension.xml is setup correctly.");
_context.addEventListener(StatusEvent.STATUS, _onStatus);
}
/**
*
*/
public static function get instance():InAppPurchase {
if (!_instance)
_instance = new InAppPurchase(new SingletonLock());
return _instance;
}
/**
*
*/
public static function get isSupported():Boolean {
return Capabilities.manufacturer.indexOf('iOS') > -1 || Capabilities.manufacturer.indexOf('Android') > -1;
}
/**
*
* @param googlePlayKey
* @param debug
*/
public function init(googlePlayKey:String, debug:Boolean = false):void {
if (!isSupported)
return;
trace("[InAppPurchase] init library");
_context.call("initLib", googlePlayKey, debug);
}
/**
*
* @param productId
*/
public function makePurchase(productId:String):void {
if (!isSupported) {
_dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported");
return;
}
trace("[InAppPurchase] purchasing", productId);
_context.call("makePurchase", productId);
}
/**
* receipt is for android device.
* @param productId
* @param receipt
*/
public function removePurchaseFromQueue(productId:String, receipt:String):void {
if (!isSupported)
return;
trace("[InAppPurchase] removing product from queue", productId, receipt);
_context.call("removePurchaseFromQueue", productId, receipt);
if (Capabilities.manufacturer.indexOf("iOS") > -1)
{
_iosPendingPurchases = _iosPendingPurchases.filter(function(jsonPurchase:String, index:int, purchases:Vector.<Object>):Boolean {
try
{
var purchase:Object = JSON.parse(jsonPurchase);
return JSON.stringify(purchase.receipt) != receipt;
}
catch(error:Error)
{
trace("[InAppPurchase] Couldn't parse purchase: " + jsonPurchase);
}
return false;
});
}
}
/**
*
* @param productsId
* @param subscriptionIds
*/
public function getProductsInfo(productsId:Array, subscriptionIds:Array):void {
if (!isSupported) {
_dispatchEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR, "InAppPurchase not supported");
return;
}
trace("[InAppPurchase] get Products Info");
_context.call("getProductsInfo", productsId, subscriptionIds);
}
/**
*
*/
public function userCanMakeAPurchase():void {
if (!isSupported) {
_dispatchEvent(InAppPurchaseEvent.PURCHASE_DISABLED, "InAppPurchase not supported");
return;
}
trace("[InAppPurchase] check user can make a purchase");
_context.call("userCanMakeAPurchase");
}
/**
*
*/
public function userCanMakeASubscription():void {
if (Capabilities.manufacturer.indexOf('Android') > -1) {
trace("[InAppPurchase] check user can make a purchase");
_context.call("userCanMakeASubscription");
}
else {
_dispatchEvent(InAppPurchaseEvent.PURCHASE_DISABLED, "subscriptions not supported");
}
}
/**
*
* @param productId
*/
public function makeSubscription(productId:String):void {
if (Capabilities.manufacturer.indexOf('Android') > -1) {
trace("[InAppPurchase] check user can make a subscription");
_context.call("makeSubscription", productId);
}
else {
_dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "subscriptions not supported");
}
}
/**
*
*/
public function restoreTransactions():void {
if (Capabilities.manufacturer.indexOf('Android') > -1)
_context.call("restoreTransaction");
else if (Capabilities.manufacturer.indexOf("iOS") > -1) {
var jsonPurchases:String = "[" + _iosPendingPurchases.join(",") + "]";
var jsonData:String = "{ \"purchases\": " + jsonPurchases + "}";
_dispatchEvent(InAppPurchaseEvent.RESTORE_INFO_RECEIVED, jsonData);
}
}
/**
*
*/
public function stop():void {
if (Capabilities.manufacturer.indexOf('Android') > -1) {
trace("[InAppPurchase] stop library");
_context.call("stopLib");
}
}
/**
*
* @param type
* @param eventData
*/
private function _dispatchEvent(type:String, eventData:String):void {
this.dispatchEvent(new InAppPurchaseEvent(type, eventData))
}
/**
*
* @param event
*/
private function _onStatus(event:StatusEvent):void {
trace(event);
if (event.code == InAppPurchaseEvent.PURCHASE_SUCCESSFUL && Capabilities.manufacturer.indexOf("iOS") > -1)
_iosPendingPurchases.push(event.level);
_dispatchEvent(event.code, event.level);
}
}
}
class SingletonLock {}
|
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2012 Freshplanet (http://freshplanet.com | [email protected])
//
// Licensed 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 com.freshplanet.ane.AirInAppPurchase {
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class InAppPurchase extends EventDispatcher {
private var _context:ExtensionContext = null;
private var _iosPendingPurchases:Vector.<Object> = new Vector.<Object>();
private static const EXTENSION_ID:String = "com.freshplanet.AirInAppPurchase";
private static var _instance:InAppPurchase = null;
/**
*
* @param lock
*/
public function InAppPurchase(lock:SingletonLock) {
if (!isSupported)
return;
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
throw Error("Extension context is null. Please check if extension.xml is setup correctly.");
_context.addEventListener(StatusEvent.STATUS, _onStatus);
}
/**
*
*/
public static function get instance():InAppPurchase {
if (!_instance)
_instance = new InAppPurchase(new SingletonLock());
return _instance;
}
/**
*
*/
public static function get isSupported():Boolean {
return Capabilities.manufacturer.indexOf('iOS') > -1 || Capabilities.manufacturer.indexOf('Android') > -1;
}
/**
*
* @param googlePlayKey
* @param debug
*/
public function init(googlePlayKey:String, debug:Boolean = false):void {
if (!isSupported)
return;
trace("[InAppPurchase] init library");
_context.call("initLib", googlePlayKey, debug);
}
/**
*
* @param productId
*/
public function makePurchase(productId:String):void {
if (!isSupported) {
_dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported");
return;
}
trace("[InAppPurchase] purchasing", productId);
_context.call("makePurchase", productId);
}
/**
* receipt is for android device.
* @param productId
* @param receipt
*/
public function removePurchaseFromQueue(productId:String, receipt:String):void {
if (!isSupported)
return;
trace("[InAppPurchase] removing product from queue", productId, receipt);
_context.call("removePurchaseFromQueue", productId, receipt);
if (Capabilities.manufacturer.indexOf("iOS") > -1)
{
_iosPendingPurchases = _iosPendingPurchases.filter(function(jsonPurchase:String, index:int, purchases:Vector.<Object>):Boolean {
try
{
var purchase:Object = JSON.parse(jsonPurchase);
return JSON.stringify(purchase.receipt) != receipt;
}
catch(error:Error)
{
trace("[InAppPurchase] Couldn't parse purchase: " + jsonPurchase);
}
return false;
});
}
}
/**
*
* @param productsId
* @param subscriptionIds
*/
public function getProductsInfo(productsId:Array, subscriptionIds:Array):void {
if (!isSupported) {
_dispatchEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR, "InAppPurchase not supported");
return;
}
trace("[InAppPurchase] get Products Info");
_context.call("getProductsInfo", productsId, subscriptionIds);
}
/**
* PURCHASE_ERROR
* PURCHASE_ERROR
* @param productId
*/
public function makeSubscription(productId:String):void {
if (Capabilities.manufacturer.indexOf('Android') > -1) {
trace("[InAppPurchase] check user can make a subscription");
_context.call("makeSubscription", productId);
}
else {
_dispatchEvent(InAppPurchaseEvent.PURCHASE_ERROR, "subscriptions not supported");
}
}
/**
* RESTORE_INFO_RECEIVED
*/
public function restoreTransactions():void {
if (Capabilities.manufacturer.indexOf('Android') > -1)
_context.call("restoreTransaction");
else if (Capabilities.manufacturer.indexOf("iOS") > -1) {
var jsonPurchases:String = "[" + _iosPendingPurchases.join(",") + "]";
var jsonData:String = "{ \"purchases\": " + jsonPurchases + "}";
_dispatchEvent(InAppPurchaseEvent.RESTORE_INFO_RECEIVED, jsonData);
}
}
/**
*
* @param type
* @param eventData
*/
private function _dispatchEvent(type:String, eventData:String):void {
this.dispatchEvent(new InAppPurchaseEvent(type, eventData))
}
/**
*
* @param event
*/
private function _onStatus(event:StatusEvent):void {
trace(event);
if (event.code == InAppPurchaseEvent.PURCHASE_SUCCESSFUL && Capabilities.manufacturer.indexOf("iOS") > -1)
_iosPendingPurchases.push(event.level);
_dispatchEvent(event.code, event.level);
}
}
}
class SingletonLock {}
|
remove unused methods
|
remove unused methods
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-In-App-Purchase,freshplanet/ANE-In-App-Purchase,freshplanet/ANE-In-App-Purchase
|
b412d3f4044fe5d24cb16e59b466db172137bf81
|
src/aerys/minko/render/effect/vertex/VertexUVShader.as
|
src/aerys/minko/render/effect/vertex/VertexUVShader.as
|
package aerys.minko.render.effect.vertex
{
import aerys.minko.render.RenderTarget;
import aerys.minko.render.effect.basic.BasicShader;
import aerys.minko.render.shader.SFloat;
import aerys.minko.type.stream.format.VertexComponent;
public class VertexUVShader extends BasicShader
{
public function VertexUVShader(target : RenderTarget = null,
priority : Number = 0)
{
super(target, priority);
}
override protected function getPixelColor() : SFloat
{
var uv : SFloat = getVertexAttribute(VertexComponent.UV);
var interpolatedUv : SFloat = normalize(interpolate(uv));
return float4(interpolatedUv.x, interpolatedUv.y, 0, 1);
}
}
}
|
package aerys.minko.render.effect.vertex
{
import aerys.minko.render.RenderTarget;
import aerys.minko.render.effect.basic.BasicProperties;
import aerys.minko.render.effect.basic.BasicShader;
import aerys.minko.render.shader.SFloat;
import aerys.minko.type.stream.format.VertexComponent;
public class VertexUVShader extends BasicShader
{
public function VertexUVShader(target : RenderTarget = null,
priority : Number = 0)
{
super(target, priority);
}
override protected function getPixelColor() : SFloat
{
var uv : SFloat = getVertexAttribute(VertexComponent.UV);
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_SCALE))
uv.scaleBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_SCALE, 2));
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_OFFSET))
uv.incrementBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_OFFSET, 2));
var interpolatedUv : SFloat = fractional(interpolate(uv));
return float4(interpolatedUv.x, interpolatedUv.y, 0, 1);
}
}
}
|
Fix Vertex uvs shader
|
Fix Vertex uvs shader
A Support of uvoffset and uvscale in the vertex uvs shader
M Use a fractional instruction to fix the shader
|
ActionScript
|
mit
|
aerys/minko-as3
|
604437d465208fb246823ce7c43c4b2c76cca2e2
|
src/aerys/minko/render/resource/texture/TextureResource.as
|
src/aerys/minko/render/resource/texture/TextureResource.as
|
package aerys.minko.render.resource.texture
{
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.type.enum.SamplerFormat;
import flash.display.BitmapData;
import flash.display3D.Context3DTextureFormat;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Matrix;
import flash.utils.ByteArray;
/**
* @inheritdoc
* @author Jean-Marc Le Roux
*
*/
public class TextureResource implements ITextureResource
{
private static const MAX_SIZE : uint = 2048;
private static const TMP_MATRIX : Matrix = new Matrix();
private static const FORMAT_BGRA : String = Context3DTextureFormat.BGRA
private static const FORMAT_COMPRESSED : String = Context3DTextureFormat.COMPRESSED;
private static const FORMAT_COMPRESSED_ALPHA : String = Context3DTextureFormat.COMPRESSED_ALPHA;
private static const TEXTURE_FORMAT_TO_SAMPLER : Array = []
{
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_BGRA] = SamplerFormat.RGBA;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED] = SamplerFormat.COMPRESSED;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED_ALPHA] = SamplerFormat.COMPRESSED_ALPHA;
}
private var _texture : Texture = null;
private var _mipmap : Boolean = false;
private var _bitmapData : BitmapData = null;
private var _atf : ByteArray = null;
private var _atfFormat : uint = 0;
private var _format : String = FORMAT_BGRA;
private var _width : Number = 0;
private var _height : Number = 0;
private var _update : Boolean = false;
public function get format() : uint
{
return TEXTURE_FORMAT_TO_SAMPLER[_format];
}
public function get mipMapping() : Boolean
{
return _mipmap;
}
public function get width() : uint
{
return _width;
}
public function get height() : uint
{
return _height;
}
public function TextureResource(width : uint = 0,
height : uint = 0)
{
_width = width;
_height = height;
}
public function setContentFromBitmapData(bitmapData : BitmapData,
mipmap : Boolean,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = bitmapData.width;
var bitmapHeight : uint = bitmapData.height;
var w : int = 0;
var h : int = 0;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (w > MAX_SIZE)
w = MAX_SIZE;
if (h > MAX_SIZE)
h = MAX_SIZE;
if (_bitmapData == null || _bitmapData.width != w || _bitmapData.height != h)
_bitmapData = new BitmapData(w, h, bitmapData.transparent, 0);
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_bitmapData.draw(bitmapData, TMP_MATRIX);
}
else
{
_bitmapData.draw(bitmapData);
}
if (_texture
&& (mipmap != _mipmap
|| bitmapData.width != _width
|| bitmapData.height != _height))
{
_texture.dispose();
_texture = null;
}
_width = _bitmapData.width;
_height = _bitmapData.height;
_mipmap = mipmap;
_update = true;
}
public function setContentFromATF(atf : ByteArray) : void
{
_atf = atf;
_bitmapData = null;
_update = true;
var oldWidth : Number = _width;
var oldHeight : Number = _height;
var oldMipmap : Boolean = _mipmap;
atf.position = 6;
var formatByte : uint = atf.readUnsignedByte();
_atfFormat = formatByte & 7;
_width = 1 << atf.readUnsignedByte();
_height = 1 << atf.readUnsignedByte();
_mipmap = atf.readUnsignedByte() > 1;
atf.position = 0;
if (_atfFormat == 5)
_format = FORMAT_COMPRESSED_ALPHA;
else if (_atfFormat == 3)
_format = FORMAT_COMPRESSED;
if (_texture
&& (oldMipmap != _mipmap
|| oldWidth != _width
|| oldHeight != _height))
{
_texture.dispose();
_texture = null;
}
}
public function getTexture(context : Context3DResource) : TextureBase
{
if (!_texture && _width && _height)
{
if (_texture)
_texture.dispose();
_texture = context.createTexture(
_width,
_height,
_format,
_bitmapData == null && _atf == null
);
}
if (_update)
{
_update = false;
uploadBitmapDataWithMipMaps();
}
_atf = null;
_bitmapData = null;
return _texture;
}
private function uploadBitmapDataWithMipMaps() : void
{
if (_bitmapData)
{
if (_mipmap)
{
var level : uint = 0;
var size : uint = _width > _height ? _width : _height;
var transparent : Boolean = _bitmapData.transparent;
var tmp : BitmapData = new BitmapData(size, size, transparent, 0);
var transform : Matrix = new Matrix();
while (size >= 1)
{
tmp.draw(_bitmapData, transform, null, null, null, true);
_texture.uploadFromBitmapData(tmp, level);
transform.scale(.5, .5);
level++;
size >>= 1;
if (tmp.transparent)
tmp.fillRect(tmp.rect, 0);
}
tmp.dispose();
}
else
{
_texture.uploadFromBitmapData(_bitmapData, 0);
}
_bitmapData.dispose();
}
else if (_atf)
{
_texture.uploadCompressedTextureFromByteArray(_atf, 0);
}
}
public function dispose() : void
{
if (_texture)
{
_texture.dispose();
_texture = null;
}
}
}
}
|
package aerys.minko.render.resource.texture
{
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.type.enum.SamplerFormat;
import flash.display.BitmapData;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Matrix;
import flash.utils.ByteArray;
/**
* @inheritdoc
* @author Jean-Marc Le Roux
*
*/
public class TextureResource implements ITextureResource
{
private static const MAX_SIZE : uint = 2048;
private static const TMP_MATRIX : Matrix = new Matrix();
private static const FORMAT_BGRA : String = 'bgra';
private static const FORMAT_COMPRESSED : String = 'compressed';
private static const FORMAT_COMPRESSED_ALPHA : String = 'compressedAlpha';
private static const TEXTURE_FORMAT_TO_SAMPLER : Array = []
{
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_BGRA] = SamplerFormat.RGBA;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED] = SamplerFormat.COMPRESSED;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED_ALPHA] = SamplerFormat.COMPRESSED_ALPHA;
}
private var _texture : Texture;
private var _mipmap : Boolean;
private var _bitmapData : BitmapData;
private var _atf : ByteArray;
private var _atfFormat : uint;
private var _format : String;
private var _width : Number;
private var _height : Number;
private var _update : Boolean;
public function get format() : uint
{
return TEXTURE_FORMAT_TO_SAMPLER[_format];
}
public function get mipMapping() : Boolean
{
return _mipmap;
}
public function get width() : uint
{
return _width;
}
public function get height() : uint
{
return _height;
}
public function TextureResource(width : uint = 0,
height : uint = 0)
{
_width = width;
_height = height;
_format = FORMAT_BGRA;
}
public function setContentFromBitmapData(bitmapData : BitmapData,
mipmap : Boolean,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = bitmapData.width;
var bitmapHeight : uint = bitmapData.height;
var w : int = 0;
var h : int = 0;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (w > MAX_SIZE)
w = MAX_SIZE;
if (h > MAX_SIZE)
h = MAX_SIZE;
if (_bitmapData == null || _bitmapData.width != w || _bitmapData.height != h)
_bitmapData = new BitmapData(w, h, bitmapData.transparent, 0);
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_bitmapData.draw(bitmapData, TMP_MATRIX);
}
else
{
_bitmapData.draw(bitmapData);
}
if (_texture
&& (_format != FORMAT_BGRA
|| mipmap != _mipmap
|| bitmapData.width != _width
|| bitmapData.height != _height))
{
_texture.dispose();
_texture = null;
}
_width = _bitmapData.width;
_height = _bitmapData.height;
_format = FORMAT_BGRA;
_mipmap = mipmap;
_update = true;
}
public function setContentFromATF(atf : ByteArray) : void
{
_atf = atf;
_bitmapData = null;
_update = true;
var oldWidth : Number = _width;
var oldHeight : Number = _height;
var oldMipmap : Boolean = _mipmap;
var oldFormat : String = _format;
atf.position = 6;
var formatByte : uint = atf.readUnsignedByte();
_atfFormat = formatByte & 7;
_width = 1 << atf.readUnsignedByte();
_height = 1 << atf.readUnsignedByte();
_mipmap = atf.readUnsignedByte() > 1;
atf.position = 0;
if (_atfFormat == 5)
_format = FORMAT_COMPRESSED_ALPHA;
else if (_atfFormat == 3)
_format = FORMAT_COMPRESSED;
else
_format = FORMAT_BGRA;
if (_texture
&& (oldFormat != _format
|| oldMipmap != _mipmap
|| oldWidth != _width
|| oldHeight != _height))
{
_texture.dispose();
_texture = null;
}
}
public function getTexture(context : Context3DResource) : TextureBase
{
if (!_texture && _width && _height)
{
if (_texture)
_texture.dispose();
_texture = context.createTexture(
_width,
_height,
_format,
_bitmapData == null && _atf == null
);
}
if (_update)
{
_update = false;
uploadBitmapDataWithMipMaps();
}
_atf = null;
_bitmapData = null;
return _texture;
}
private function uploadBitmapDataWithMipMaps() : void
{
if (_bitmapData)
{
if (_mipmap)
{
var level : uint = 0;
var size : uint = _width > _height ? _width : _height;
var transparent : Boolean = _bitmapData.transparent;
var tmp : BitmapData = new BitmapData(size, size, transparent, 0);
var transform : Matrix = new Matrix();
while (size >= 1)
{
tmp.draw(_bitmapData, transform, null, null, null, true);
_texture.uploadFromBitmapData(tmp, level);
transform.scale(.5, .5);
level++;
size >>= 1;
if (tmp.transparent)
tmp.fillRect(tmp.rect, 0);
}
tmp.dispose();
}
else
{
_texture.uploadFromBitmapData(_bitmapData, 0);
}
_bitmapData.dispose();
}
else if (_atf)
{
_texture.uploadCompressedTextureFromByteArray(_atf, 0);
}
}
public function dispose() : void
{
if (_texture)
{
_texture.dispose();
_texture = null;
}
}
}
}
|
use string literals for texture formats to avoid compatibility issues
|
use string literals for texture formats to avoid compatibility issues
|
ActionScript
|
mit
|
aerys/minko-as3
|
81df22ca98c748f311305a3c7978ea7e47da0bcf
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/ContainerBase.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/ContainerBase.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.core
{
import mx.states.State;
import org.apache.flex.core.IMXMLDocument;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.ValueChangeEvent;
import org.apache.flex.utils.MXMLDataInterpreter;
/**
* Indicates that the state change has completed. All properties
* that need to change have been changed, and all transitinos
* that need to run have completed. However, any deferred work
* may not be completed, and the screen may not be updated until
* code stops executing.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="stateChangeComplete", type="org.apache.flex.events.Event")]
/**
* Indicates that the initialization of the container is complete.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="initComplete", type="org.apache.flex.events.Event")]
/**
* Indicates that the children of the container is have been added.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="childrenAdded", type="org.apache.flex.events.Event")]
[DefaultProperty("mxmlContent")]
/**
* The ContainerBase class is the base class for most containers
* in FlexJS. It is usable as the root tag of MXML
* documents and UI controls and containers are added to it.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ContainerBase extends UIBase implements IMXMLDocument
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ContainerBase()
{
super();
}
/**
* A ContainerBase doesn't create its children until it is added to
* a parent.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function addedToParent():void
{
// each MXML file can also have styles in fx:Style block
ValuesManager.valuesImpl.init(this);
super.addedToParent();
MXMLDataInterpreter.generateMXMLInstances(_mxmlDocument, this, MXMLDescriptor);
dispatchEvent(new Event("initComplete"))
dispatchEvent(new Event("childrenAdded"));
}
private var _mxmlDescriptor:Array;
private var _mxmlDocument:Object = this;
/**
* @copy org.apache.flex.core.Application#MXMLDescriptor
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get MXMLDescriptor():Array
{
return _mxmlDescriptor;
}
/**
* @private
*/
public function setMXMLDescriptor(document:Object, value:Array):void
{
_mxmlDocument = document;
_mxmlDescriptor = value;
}
/**
* @copy org.apache.flex.core.Application#generateMXMLAttributes()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateMXMLAttributes(data:Array):void
{
MXMLDataInterpreter.generateMXMLProperties(this, data);
}
/**
* @copy org.apache.flex.core.ItemRendererClassFactory#mxmlContent
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var mxmlContent:Array;
private var _states:Array;
/**
* The array of view states. These should
* be instances of mx.states.State.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get states():Array
{
return _states;
}
/**
* @private
*/
public function set states(value:Array):void
{
_states = value;
_currentState = _states[0].name;
try{
if (getBeadByType(IStatesImpl) == null)
addBead(new (ValuesManager.valuesImpl.getValue(this, "iStatesImpl")) as IBead);
}
//TODO: Need to handle this case more gracefully
catch(e:Error)
{
trace(e.message);
}
}
/**
* <code>true</code> if the array of states
* contains a state with this name.
*
* @param state The state namem.
* @return True if state in state array
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function hasState(state:String):Boolean
{
for each (var s:State in _states)
{
if (s.name == state)
return true;
}
return false;
}
private var _currentState:String;
[Bindable("currentStateChange")]
/**
* The name of the current state.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get currentState():String
{
return _currentState;
}
/**
* @private
*/
public function set currentState(value:String):void
{
var event:ValueChangeEvent = new ValueChangeEvent("currentStateChange", false, false, _currentState, value)
_currentState = value;
dispatchEvent(event);
}
private var _transitions:Array;
/**
* The array of transitions.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get transitions():Array
{
return _transitions;
}
/**
* @private
*/
public function set transitions(value:Array):void
{
_transitions = value;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.core
{
import mx.states.State;
import org.apache.flex.core.IMXMLDocument;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.ValueChangeEvent;
import org.apache.flex.utils.MXMLDataInterpreter;
/**
* Indicates that the state change has completed. All properties
* that need to change have been changed, and all transitinos
* that need to run have completed. However, any deferred work
* may not be completed, and the screen may not be updated until
* code stops executing.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="stateChangeComplete", type="org.apache.flex.events.Event")]
/**
* Indicates that the initialization of the container is complete.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="initComplete", type="org.apache.flex.events.Event")]
/**
* Indicates that the children of the container is have been added.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="childrenAdded", type="org.apache.flex.events.Event")]
[DefaultProperty("mxmlContent")]
/**
* The ContainerBase class is the base class for most containers
* in FlexJS. It is usable as the root tag of MXML
* documents and UI controls and containers are added to it.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ContainerBase extends UIBase implements IMXMLDocument, IStatesObject
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ContainerBase()
{
super();
}
/**
* A ContainerBase doesn't create its children until it is added to
* a parent.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function addedToParent():void
{
// each MXML file can also have styles in fx:Style block
ValuesManager.valuesImpl.init(this);
super.addedToParent();
MXMLDataInterpreter.generateMXMLInstances(_mxmlDocument, this, MXMLDescriptor);
dispatchEvent(new Event("initComplete"))
dispatchEvent(new Event("childrenAdded"));
}
private var _mxmlDescriptor:Array;
private var _mxmlDocument:Object = this;
/**
* @copy org.apache.flex.core.Application#MXMLDescriptor
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get MXMLDescriptor():Array
{
return _mxmlDescriptor;
}
/**
* @private
*/
public function setMXMLDescriptor(document:Object, value:Array):void
{
_mxmlDocument = document;
_mxmlDescriptor = value;
}
/**
* @copy org.apache.flex.core.Application#generateMXMLAttributes()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateMXMLAttributes(data:Array):void
{
MXMLDataInterpreter.generateMXMLProperties(this, data);
}
/**
* @copy org.apache.flex.core.ItemRendererClassFactory#mxmlContent
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var mxmlContent:Array;
private var _states:Array;
/**
* The array of view states. These should
* be instances of mx.states.State.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get states():Array
{
return _states;
}
/**
* @private
*/
public function set states(value:Array):void
{
_states = value;
_currentState = _states[0].name;
try{
if (getBeadByType(IStatesImpl) == null)
addBead(new (ValuesManager.valuesImpl.getValue(this, "iStatesImpl")) as IBead);
}
//TODO: Need to handle this case more gracefully
catch(e:Error)
{
trace(e.message);
}
}
/**
* <code>true</code> if the array of states
* contains a state with this name.
*
* @param state The state namem.
* @return True if state in state array
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function hasState(state:String):Boolean
{
for each (var s:State in _states)
{
if (s.name == state)
return true;
}
return false;
}
private var _currentState:String;
[Bindable("currentStateChange")]
/**
* The name of the current state.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get currentState():String
{
return _currentState;
}
/**
* @private
*/
public function set currentState(value:String):void
{
var event:ValueChangeEvent = new ValueChangeEvent("currentStateChange", false, false, _currentState, value)
_currentState = value;
dispatchEvent(event);
}
private var _transitions:Array;
/**
* The array of transitions.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get transitions():Array
{
return _transitions;
}
/**
* @private
*/
public function set transitions(value:Array):void
{
_transitions = value;
}
}
}
|
handle initial state
|
handle initial state
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
ece602fa24e5ea8880a720fa7dc4f5cee26045be
|
HLSPlugin/src/com/kaltura/hls/manifest/HLSManifestEncryptionKey.as
|
HLSPlugin/src/com/kaltura/hls/manifest/HLSManifestEncryptionKey.as
|
package com.kaltura.hls.manifest
{
import com.hurlant.util.Hex;
import com.kaltura.hls.crypto.FastAESKey;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.utils.getTimer;
CONFIG::LOGGING
{
import org.osmf.logging.Logger;
import org.osmf.logging.Log;
}
/**
* HLSManifestEncryptionKey is used to parse AES decryption key data from a m3u8
* manifest, load the specified key file into memory, and use the key data to decrypt
* audio and video streams. It supports AES-128 encryption with #PKCS7 padding, and uses
* explicitly passed in Initialization Vectors.
*/
public class HLSManifestEncryptionKey extends EventDispatcher
{
CONFIG::LOGGING
{
private static const logger:Logger = Log.getLogger("com.kaltura.hls.manifest.HLSManifestEncryptionKey");
}
private static const LOADER_CACHE:Dictionary = new Dictionary();
private var _key:FastAESKey;
public var usePadding:Boolean = false;
public var iv:String = "";
public var url:String = "";
private var iv0 : uint;
private var iv1 : uint;
private var iv2 : uint;
private var iv3 : uint;
// Keep track of the segments this key applies to
public var startSegmentId:uint = 0;
public var endSegmentId:uint = uint.MAX_VALUE;
private var _keyData:ByteArray;
public var isLoading:Boolean = false;
public function HLSManifestEncryptionKey()
{
}
public function get isLoaded():Boolean { return _keyData != null; }
public override function toString():String
{
return "[HLSManifestEncryptionKey start=" + startSegmentId +", end=" + endSegmentId + ", iv=" + iv + ", url=" + url + ", loaded=" + isLoaded + "]";
}
public static function fromParams( params:String ):HLSManifestEncryptionKey
{
var result:HLSManifestEncryptionKey = new HLSManifestEncryptionKey();
var tokens:Array = KeyParamParser.parseParams( params );
var tokenCount:int = tokens.length;
for ( var i:int = 0; i < tokenCount; i += 2 )
{
var name:String = tokens[ i ];
var value:String = tokens[ i + 1 ];
switch ( name )
{
case "URI" :
result.url = value;
break;
case "IV" :
result.iv = value;
break;
}
}
return result;
}
/**
* Creates an initialization vector from the passed in uint ID, usually
* a segment ID.
*/
public static function createIVFromID( id:uint ):ByteArray
{
var result:ByteArray = new ByteArray();
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( id );
return result;
}
public static function clearLoaderCache():void
{
for ( var key:String in LOADER_CACHE ) delete LOADER_CACHE[ key ];
}
/**
* Decrypts a video or audio stream using AES-128 with the provided initialization vector.
*/
public function decrypt( data:ByteArray, iv:ByteArray ):ByteArray
{
//logger.debug("got " + data.length + " bytes");
if(data.length == 0)
return data;
var startTime:uint = getTimer();
_key = new FastAESKey(_keyData);
iv.position = 0;
iv0 = iv.readUnsignedInt();
iv1 = iv.readUnsignedInt();
iv2 = iv.readUnsignedInt();
iv3 = iv.readUnsignedInt();
data.position = 0;
data = _decryptCBC(data,data.length);
if ( usePadding ){
data = unpad( data );
}
// logger.debug( "DECRYPTION OF " + data.length + " BYTES TOOK " + ( getTimer() - startTime ) + " MS" );
return data;
}
/* Cypher Block Chaining Decryption, refer to
* http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_
* for algorithm description
*/
private function _decryptCBC(crypt : ByteArray, len : uint) : ByteArray {
var src : Vector.<uint> = new Vector.<uint>(4);
var dst : Vector.<uint> = new Vector.<uint>(4);
var decrypt : ByteArray = new ByteArray();
decrypt.length = len;
for (var i : uint = 0; i < len / 16; i++) {
// read src byte array
src[0] = crypt.readUnsignedInt();
src[1] = crypt.readUnsignedInt();
src[2] = crypt.readUnsignedInt();
src[3] = crypt.readUnsignedInt();
// AES decrypt src vector into dst vector
_key.decrypt128(src, dst);
// CBC : write output = XOR(decrypted,IV)
decrypt.writeUnsignedInt(dst[0] ^ iv0);
decrypt.writeUnsignedInt(dst[1] ^ iv1);
decrypt.writeUnsignedInt(dst[2] ^ iv2);
decrypt.writeUnsignedInt(dst[3] ^ iv3);
// CBC : next IV = (input)
iv0 = src[0];
iv1 = src[1];
iv2 = src[2];
iv3 = src[3];
}
return decrypt;
}
public function unpad(bytesToUnpad : ByteArray) : ByteArray {
if ((bytesToUnpad.length % 16) != 0)
{
throw new Error("PKCS#5::unpad: ByteArray.length isn't a multiple of the blockSize");
return a;
}
const paddingValue:int = bytesToUnpad[bytesToUnpad.length - 1];
var doUnpad:Boolean = true;
for (var i:int = 0; i<paddingValue; i++) {
var readValue:int = bytesToUnpad[bytesToUnpad.length - (1 + i)];
if (paddingValue != readValue)
{
//throw new Error("PKCS#5:unpad: Invalid padding value. expected [" + paddingValue + "], found [" + readValue + "]");
//break;
doUnpad = false;
//Break to make sure we don't underrun the byte array with a byte value bigger than 16
break;
}
}
if(doUnpad)
{
//subtract paddingValue + 1 since the value is one less than the number of padded bytes
bytesToUnpad.length -= paddingValue + 1;
}
return bytesToUnpad;
}
public function retrieveStoredIV():ByteArray
{
CONFIG::LOGGING
{
logger.debug("IV of " + iv + " for " + url + ", key=" + Hex.fromArray(_keyData));
}
return Hex.toArray( iv );
}
private static function getLoader( url:String ):URLLoader
{
if ( LOADER_CACHE[ url ] != null ) return LOADER_CACHE[ url ] as URLLoader;
var newLoader:URLLoader = new URLLoader();
newLoader.dataFormat = URLLoaderDataFormat.BINARY;
newLoader.load( new URLRequest( url ) );
LOADER_CACHE[ url ] = newLoader;
return newLoader;
}
public function load():void
{
isLoading = true;
if ( isLoaded ) throw new Error( "Already loaded!" );
var loader:URLLoader = getLoader( url );
if ( loader.bytesTotal > 0 && loader.bytesLoaded == loader.bytesTotal ) onLoad();
else loader.addEventListener( Event.COMPLETE, onLoad );
}
private function onLoad( e:Event = null ):void
{
isLoading = false;
CONFIG::LOGGING
{
logger.debug("KEY LOADED! " + url);
}
var loader:URLLoader = getLoader( url );
_keyData = loader.data as ByteArray;
loader.removeEventListener( Event.COMPLETE, onLoad );
dispatchEvent( new Event( Event.COMPLETE ) );
}
}
}
class KeyParamParser
{
private static const STATE_PARSE_NAME:String = "ParseName";
private static const STATE_BEGIN_PARSE_VALUE:String = "BeginParseValue";
private static const STATE_PARSE_VALUE:String = "ParseValue";
public static function parseParams( paramString:String ):Array
{
var result:Array = [];
var cursor:int = 0;
var state:String = STATE_PARSE_NAME;
var accum:String = "";
var usingQuotes:Boolean = false;
while ( cursor < paramString.length )
{
var char:String = paramString.charAt( cursor );
switch ( state )
{
case STATE_PARSE_NAME:
if ( char == '=' )
{
result.push( accum );
accum = "";
state = STATE_BEGIN_PARSE_VALUE;
}
else accum += char;
break;
case STATE_BEGIN_PARSE_VALUE:
if ( char == '"' ) usingQuotes = true;
else accum += char;
state = STATE_PARSE_VALUE;
break;
case STATE_PARSE_VALUE:
if ( !usingQuotes && char == ',' )
{
result.push( accum );
accum = "";
state = STATE_PARSE_NAME;
break;
}
if ( usingQuotes && char == '"' )
{
usingQuotes = false;
break;
}
accum += char;
break;
}
cursor++;
if ( cursor == paramString.length ) result.push( accum );
}
return result;
}
}
|
package com.kaltura.hls.manifest
{
import com.hurlant.util.Hex;
import com.kaltura.hls.crypto.FastAESKey;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.utils.getTimer;
CONFIG::LOGGING
{
import org.osmf.logging.Logger;
import org.osmf.logging.Log;
}
/**
* HLSManifestEncryptionKey is used to parse AES decryption key data from a m3u8
* manifest, load the specified key file into memory, and use the key data to decrypt
* audio and video streams. It supports AES-128 encryption with #PKCS7 padding, and uses
* explicitly passed in Initialization Vectors.
*/
public class HLSManifestEncryptionKey extends EventDispatcher
{
CONFIG::LOGGING
{
private static const logger:Logger = Log.getLogger("com.kaltura.hls.manifest.HLSManifestEncryptionKey");
}
private static const LOADER_CACHE:Dictionary = new Dictionary();
private var _key:FastAESKey;
public var usePadding:Boolean = false;
public var iv:String = "";
public var url:String = "";
private var iv0 : uint;
private var iv1 : uint;
private var iv2 : uint;
private var iv3 : uint;
// Keep track of the segments this key applies to
public var startSegmentId:uint = 0;
public var endSegmentId:uint = uint.MAX_VALUE;
private var _keyData:ByteArray;
public var isLoading:Boolean = false;
public function HLSManifestEncryptionKey()
{
}
public function get isLoaded():Boolean { return _keyData != null; }
public override function toString():String
{
return "[HLSManifestEncryptionKey start=" + startSegmentId +", end=" + endSegmentId + ", iv=" + iv + ", url=" + url + ", loaded=" + isLoaded + "]";
}
public static function fromParams( params:String ):HLSManifestEncryptionKey
{
var result:HLSManifestEncryptionKey = new HLSManifestEncryptionKey();
var tokens:Array = KeyParamParser.parseParams( params );
var tokenCount:int = tokens.length;
for ( var i:int = 0; i < tokenCount; i += 2 )
{
var name:String = tokens[ i ];
var value:String = tokens[ i + 1 ];
switch ( name )
{
case "URI" :
result.url = value;
break;
case "IV" :
result.iv = value;
break;
}
}
return result;
}
/**
* Creates an initialization vector from the passed in uint ID, usually
* a segment ID.
*/
public static function createIVFromID( id:uint ):ByteArray
{
var result:ByteArray = new ByteArray();
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( id );
return result;
}
public static function clearLoaderCache():void
{
for ( var key:String in LOADER_CACHE ) delete LOADER_CACHE[ key ];
}
/**
* Decrypts a video or audio stream using AES-128 with the provided initialization vector.
*/
public function decrypt( data:ByteArray, iv:ByteArray ):ByteArray
{
//logger.debug("got " + data.length + " bytes");
if(data.length == 0)
return data;
var startTime:uint = getTimer();
_key = new FastAESKey(_keyData);
iv.position = 0;
iv0 = iv.readUnsignedInt();
iv1 = iv.readUnsignedInt();
iv2 = iv.readUnsignedInt();
iv3 = iv.readUnsignedInt();
data.position = 0;
data = _decryptCBC(data,data.length);
if ( usePadding ){
data = unpad( data );
}
// logger.debug( "DECRYPTION OF " + data.length + " BYTES TOOK " + ( getTimer() - startTime ) + " MS" );
return data;
}
/* Cypher Block Chaining Decryption, refer to
* http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_
* for algorithm description
*/
private function _decryptCBC(crypt : ByteArray, len : uint) : ByteArray {
var src : Vector.<uint> = new Vector.<uint>(4);
var dst : Vector.<uint> = new Vector.<uint>(4);
var decrypt : ByteArray = new ByteArray();
decrypt.length = len;
for (var i : uint = 0; i < len / 16; i++) {
// read src byte array
src[0] = crypt.readUnsignedInt();
src[1] = crypt.readUnsignedInt();
src[2] = crypt.readUnsignedInt();
src[3] = crypt.readUnsignedInt();
// AES decrypt src vector into dst vector
_key.decrypt128(src, dst);
// CBC : write output = XOR(decrypted,IV)
decrypt.writeUnsignedInt(dst[0] ^ iv0);
decrypt.writeUnsignedInt(dst[1] ^ iv1);
decrypt.writeUnsignedInt(dst[2] ^ iv2);
decrypt.writeUnsignedInt(dst[3] ^ iv3);
// CBC : next IV = (input)
iv0 = src[0];
iv1 = src[1];
iv2 = src[2];
iv3 = src[3];
}
return decrypt;
}
public function unpad(bytesToUnpad : ByteArray) : ByteArray {
if ((bytesToUnpad.length % 16) != 0)
{
throw new Error("PKCS#5::unpad: ByteArray.length isn't a multiple of the blockSize");
return a;
}
const paddingValue:int = bytesToUnpad[bytesToUnpad.length - 1];
if (paddingValue > 15)
{
return bytesToUnpad;
}
var doUnpad:Boolean = true;
for (var i:int = 0; i<paddingValue; i++) {
var readValue:int = bytesToUnpad[bytesToUnpad.length - (1 + i)];
if (paddingValue != readValue)
{
//throw new Error("PKCS#5:unpad: Invalid padding value. expected [" + paddingValue + "], found [" + readValue + "]");
//break;
doUnpad = false;
//Break to make sure we don't underrun the byte array with a byte value bigger than 16
break;
}
}
if(doUnpad)
{
//subtract paddingValue + 1 since the value is one less than the number of padded bytes
bytesToUnpad.length -= paddingValue + 1;
}
return bytesToUnpad;
}
public function retrieveStoredIV():ByteArray
{
CONFIG::LOGGING
{
logger.debug("IV of " + iv + " for " + url + ", key=" + Hex.fromArray(_keyData));
}
return Hex.toArray( iv );
}
private static function getLoader( url:String ):URLLoader
{
if ( LOADER_CACHE[ url ] != null ) return LOADER_CACHE[ url ] as URLLoader;
var newLoader:URLLoader = new URLLoader();
newLoader.dataFormat = URLLoaderDataFormat.BINARY;
newLoader.load( new URLRequest( url ) );
LOADER_CACHE[ url ] = newLoader;
return newLoader;
}
public function load():void
{
isLoading = true;
if ( isLoaded ) throw new Error( "Already loaded!" );
var loader:URLLoader = getLoader( url );
if ( loader.bytesTotal > 0 && loader.bytesLoaded == loader.bytesTotal ) onLoad();
else loader.addEventListener( Event.COMPLETE, onLoad );
}
private function onLoad( e:Event = null ):void
{
isLoading = false;
CONFIG::LOGGING
{
logger.debug("KEY LOADED! " + url);
}
var loader:URLLoader = getLoader( url );
_keyData = loader.data as ByteArray;
loader.removeEventListener( Event.COMPLETE, onLoad );
dispatchEvent( new Event( Event.COMPLETE ) );
}
}
}
class KeyParamParser
{
private static const STATE_PARSE_NAME:String = "ParseName";
private static const STATE_BEGIN_PARSE_VALUE:String = "BeginParseValue";
private static const STATE_PARSE_VALUE:String = "ParseValue";
public static function parseParams( paramString:String ):Array
{
var result:Array = [];
var cursor:int = 0;
var state:String = STATE_PARSE_NAME;
var accum:String = "";
var usingQuotes:Boolean = false;
while ( cursor < paramString.length )
{
var char:String = paramString.charAt( cursor );
switch ( state )
{
case STATE_PARSE_NAME:
if ( char == '=' )
{
result.push( accum );
accum = "";
state = STATE_BEGIN_PARSE_VALUE;
}
else accum += char;
break;
case STATE_BEGIN_PARSE_VALUE:
if ( char == '"' ) usingQuotes = true;
else accum += char;
state = STATE_PARSE_VALUE;
break;
case STATE_PARSE_VALUE:
if ( !usingQuotes && char == ',' )
{
result.push( accum );
accum = "";
state = STATE_PARSE_NAME;
break;
}
if ( usingQuotes && char == '"' )
{
usingQuotes = false;
break;
}
accum += char;
break;
}
cursor++;
if ( cursor == paramString.length ) result.push( accum );
}
return result;
}
}
|
Update HLSManifestEncryptionKey.as
|
Update HLSManifestEncryptionKey.as
Adds optimized logic to early-out the unpadding algorithm of the end byte is 16 or larger, which would indicate there is no padding.
|
ActionScript
|
agpl-3.0
|
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
|
791cc75bd057a44774e14e727213d5966698bb31
|
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMP2TSFileHandler.as
|
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMP2TSFileHandler.as
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the at.matthew.httpstreaming package.
*
* The Initial Developer of the Original Code is
* Matthew Kaufman.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
package org.denivip.osmf.net.httpstreaming.hls
{
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import com.hurlant.util.Hex;
import org.denivip.osmf.utility.decrypt.AES;
import org.osmf.logging.Log;
import org.osmf.logging.Logger;
import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase;
[Event(name="notifySegmentDuration", type="org.osmf.events.HTTPStreamingFileHandlerEvent")]
[Event(name="notifyTimeBias", type="org.osmf.events.HTTPStreamingFileHandlerEvent")]
public class HTTPStreamingMP2TSFileHandler extends HTTPStreamingFileHandlerBase
{
private var _syncFound:Boolean;
private var _pmtPID:uint;
private var _audioPID:uint;
private var _videoPID:uint;
private var _mp3AudioPID:uint;
private var _audioPES:HTTPStreamingMP2PESAudio;
private var _videoPES:HTTPStreamingMP2PESVideo;
private var _mp3audioPES:HTTPStreamingMp3Audio2ToPESAudio;
private var _cachedOutputBytes:ByteArray;
private var alternatingYieldCounter:int = 0;
private var _key:HTTPStreamingM3U8IndexKey = null;
private var _iv:ByteArray = null;
private var _decryptBuffer:ByteArray = new ByteArray;
// AES-128 specific variables
private var _decryptAES:AES = null;
public function HTTPStreamingMP2TSFileHandler()
{
_audioPES = new HTTPStreamingMP2PESAudio;
_videoPES = new HTTPStreamingMP2PESVideo;
_mp3audioPES = new HTTPStreamingMp3Audio2ToPESAudio;
}
override public function beginProcessFile(seek:Boolean, seekTime:Number):void
{
_syncFound = false;
}
override public function get inputBytesNeeded():Number
{
return _syncFound ? 187 : 1;
}
override public function processFileSegment(input:IDataInput):ByteArray
{
var bytesAvailableStart:uint = input.bytesAvailable;
var output:ByteArray;
if (_cachedOutputBytes !== null) {
output = _cachedOutputBytes;
_cachedOutputBytes = null;
}
else {
output = new ByteArray();
}
while (true) {
if(!_syncFound)
{
if (_key) {
if (_key.type == "AES-128") {
if (input.bytesAvailable < 16) {
if (_decryptBuffer.bytesAvailable < 1) {
break;
}
} else {
if (!decryptToBuffer(input, 16)) {
break;
}
}
if (_decryptBuffer.readByte() == 0x47) {
_syncFound = true;
}
}
} else {
if(input.bytesAvailable < 1)
break;
if(input.readByte() == 0x47)
_syncFound = true;
}
}
else
{
_syncFound = false;
var packet:ByteArray = new ByteArray();
if (_key) {
if (_key.type == "AES-128") {
if (input.bytesAvailable < 176) {
if (_decryptBuffer.bytesAvailable < 187) {
break;
}
} else {
var bytesLeft:uint = input.bytesAvailable - 176;
if (bytesLeft > 0 && bytesLeft < 15) {
if (!decryptToBuffer(input, input.bytesAvailable)) {
break;
}
} else {
if (!decryptToBuffer(input, 176)) {
break;
}
}
}
_decryptBuffer.readBytes(packet, 0, 187);
}
} else {
if(input.bytesAvailable < 187)
break;
input.readBytes(packet, 0, 187);
}
var result:ByteArray = processPacket(packet);
if (result !== null) {
output.writeBytes(result);
}
if (bytesAvailableStart - input.bytesAvailable > 10000) {
alternatingYieldCounter = (alternatingYieldCounter + 1) & 0x03;
if (alternatingYieldCounter /*& 0x01 === 1*/) {
_cachedOutputBytes = output;
return null;
}
break;
}
}
}
output.position = 0;
return output.length === 0 ? null : output;
}
private function decryptToBuffer(input:IDataInput, blockSize:int):Boolean{
if (_key) {
// Clear buffer
if (_decryptBuffer.bytesAvailable == 0) {
_decryptBuffer.clear();
}
if (_key.type == "AES-128" && blockSize % 16 == 0 && _key.key) {
if (!_decryptAES) {
trace("Creating a new AES object");
_decryptAES = new AES(_key.key);
_decryptAES.pad = "none";
_decryptAES.iv = _iv;
}
// Save buffer position
var currentPosition:uint = _decryptBuffer.position;
_decryptBuffer.position += _decryptBuffer.bytesAvailable;
// Save block to decrypt
var decrypt:ByteArray = new ByteArray;
input.readBytes(decrypt, 0, blockSize);
// Save new IV from ciphertext
var newIv:ByteArray = new ByteArray;
decrypt.position += (decrypt.bytesAvailable-16);
decrypt.readBytes(newIv, 0, 16);
decrypt.position = 0;
// Decrypt
if (input.bytesAvailable == 0) {
_decryptAES.pad = "pkcs7";
}
_decryptAES.decrypt(decrypt);
decrypt.position = 0;
// Write into buffer
_decryptBuffer.writeBytes(decrypt);
_decryptBuffer.position = currentPosition;
// Update AES IV
_decryptAES.iv = newIv;
return true;
}
}
return false;
}
override public function endProcessFile(input:IDataInput):ByteArray
{
_decryptBuffer.clear();
if (_decryptAES) {
_decryptAES.destroy();
}
_decryptAES = null;
return null;
}
public function resetCache():void{
_cachedOutputBytes = null;
alternatingYieldCounter = 0;
_decryptBuffer.clear();
if (_decryptAES) {
_decryptAES.destroy();
}
_decryptAES = null;
}
public function set initialOffset(offset:Number):void{
offset *= 1000; // convert to ms
_videoPES.initialTimestamp = offset;
_audioPES.initialTimestamp = offset;
_mp3audioPES.initialTimestamp = offset;
}
public function set key(key:HTTPStreamingM3U8IndexKey):void {
_key = key;
if (_decryptAES) {
_decryptAES.destroy();
}
_decryptAES = null;
}
public function set iv(iv:String):void {
if (iv) {
_iv = Hex.toArray(iv);
}
}
private function processPacket(packet:ByteArray):ByteArray
{
// decode rest of transport stream prefix (after the 0x47 flag byte)
// top of second byte
var value:uint = packet.readUnsignedByte();
//var tei:Boolean = Boolean(value & 0x80); // error indicator
var pusi:Boolean = Boolean(value & 0x40); // payload unit start indication
//var tpri:Boolean = Boolean(value & 0x20); // transport priority indication
// bottom of second byte and all of third
value <<= 8;
value += packet.readUnsignedByte();
var pid:uint = value & 0x1fff; // packet ID
// fourth byte
value = packet.readUnsignedByte();
//var scramblingControl:uint = (value >> 6) & 0x03; // scrambling control bits
var hasAF:Boolean = Boolean(value & 0x20); // has adaptation field
var hasPD:Boolean = Boolean(value & 0x10); // has payload data
//var ccount:uint = value & 0x0f; // continuty count
// technically hasPD without hasAF is an error, see spec
if(hasAF)
{
// process adaptation field
// don't care about flags
// don't care about clocks here
var af:uint = packet.readUnsignedByte();
packet.position += af; // skip to end
}
return hasPD ? processES(pid, pusi, packet) : null;
}
private function processES(pid:uint, pusi:Boolean, packet:ByteArray):ByteArray
{
var output:ByteArray = null;
if(pid == 0) // PAT
{
if(pusi)
processPAT(packet);
}
else if(pid == _pmtPID)
{
if(pusi)
processPMT(packet);
}
else if(pid == _audioPID)
{
output = _audioPES.processES(pusi, packet);
}
else if(pid == _videoPID)
{
output = _videoPES.processES(pusi, packet);
}
else if(pid == _mp3AudioPID)
{
output = _mp3audioPES.processES(pusi, packet);
}
return output;
}
private function processPAT(packet:ByteArray):void
{
packet.readUnsignedByte(); // pointer:uint
packet.readUnsignedByte(); // tableID:uint
var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring misc and reserved bits
packet.position += 5; // skip tsid + version/cni + sec# + last sec#
remaining -= 5;
while(remaining > 4)
{
packet.readUnsignedShort(); // program number
_pmtPID = packet.readUnsignedShort() & 0x1fff; // 13 bits
remaining -= 4;
//return; // immediately after reading the first pmt ID, if we don't we get the LAST one
}
// and ignore the CRC (4 bytes)
}
private function processPMT(packet:ByteArray):void
{
packet.readUnsignedByte(); // pointer:uint
var tableID:uint = packet.readUnsignedByte();
if (tableID != 0x02)
{
CONFIG::LOGGING
{
logger.warn("PAT pointed to PMT that isn't PMT");
}
return; // don't try to parse it
}
var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring section syntax and reserved
packet.position += 7; // skip program num, rserved, version, cni, section num, last section num, reserved, PCR PID
remaining -= 7;
var piLen:uint = packet.readUnsignedShort() & 0x0fff;
remaining -= 2;
packet.position += piLen; // skip program info
remaining -= piLen;
while(remaining > 4)
{
var type:uint = packet.readUnsignedByte();
var pid:uint = packet.readUnsignedShort() & 0x1fff;
var esiLen:uint = packet.readUnsignedShort() & 0x0fff;
remaining -= 5;
packet.position += esiLen;
remaining -= esiLen;
switch(type)
{
case 0x1b: // H.264 video
_videoPID = pid;
break;
case 0x0f: // AAC Audio / ADTS
_audioPID = pid;
break;
case 0x03: // MP3 Audio (3 & 4)
case 0x04:
_mp3AudioPID = pid;
break;
default:
CONFIG::LOGGING
{
logger.error("unsupported type "+type.toString(16)+" in PMT");
}
break;
}
}
// and ignore CRC
}
override public function flushFileSegment(input:IDataInput):ByteArray
{
var flvBytes:ByteArray = new ByteArray();
var flvBytesVideo:ByteArray = _videoPES.processES(false, null, true);
var flvBytesAudio:ByteArray = _audioPES.processES(false, null, true);
if(flvBytesVideo)
flvBytes.readBytes(flvBytesVideo);
if(flvBytesAudio)
flvBytes.readBytes(flvBytesAudio);
return flvBytes;
}
CONFIG::LOGGING
{
private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMP2TSFileHandler') as Logger;
}
}
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the at.matthew.httpstreaming package.
*
* The Initial Developer of the Original Code is
* Matthew Kaufman.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
package org.denivip.osmf.net.httpstreaming.hls
{
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import com.hurlant.util.Hex;
import org.denivip.osmf.utility.decrypt.AES;
import org.osmf.logging.Log;
import org.osmf.logging.Logger;
import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase;
[Event(name="notifySegmentDuration", type="org.osmf.events.HTTPStreamingFileHandlerEvent")]
[Event(name="notifyTimeBias", type="org.osmf.events.HTTPStreamingFileHandlerEvent")]
public class HTTPStreamingMP2TSFileHandler extends HTTPStreamingFileHandlerBase
{
private var _syncFound:Boolean;
private var _pmtPID:uint;
private var _audioPID:uint;
private var _videoPID:uint;
private var _mp3AudioPID:uint;
private var _audioPES:HTTPStreamingMP2PESAudio;
private var _videoPES:HTTPStreamingMP2PESVideo;
private var _mp3audioPES:HTTPStreamingMp3Audio2ToPESAudio;
private var _cachedOutputBytes:ByteArray;
private var alternatingYieldCounter:int = 0;
private var _key:HTTPStreamingM3U8IndexKey = null;
private var _iv:ByteArray = null;
private var _decryptBuffer:ByteArray = new ByteArray;
// AES-128 specific variables
private var _decryptAES:AES = null;
public function HTTPStreamingMP2TSFileHandler()
{
_audioPES = new HTTPStreamingMP2PESAudio;
_videoPES = new HTTPStreamingMP2PESVideo;
_mp3audioPES = new HTTPStreamingMp3Audio2ToPESAudio;
}
override public function beginProcessFile(seek:Boolean, seekTime:Number):void
{
_syncFound = false;
}
override public function get inputBytesNeeded():Number
{
return _syncFound ? 187 : 1;
}
override public function processFileSegment(input:IDataInput):ByteArray
{
var bytesAvailableStart:uint = input.bytesAvailable;
var output:ByteArray;
if (_cachedOutputBytes !== null) {
output = _cachedOutputBytes;
_cachedOutputBytes = null;
}
else {
output = new ByteArray();
}
while (true) {
if(!_syncFound)
{
if (_key) {
if (_key.type == "AES-128") {
if (input.bytesAvailable < 16) {
if (_decryptBuffer.bytesAvailable < 1) {
break;
}
} else {
if (!decryptToBuffer(input, 16)) {
break;
}
}
if (_decryptBuffer.readByte() == 0x47) {
_syncFound = true;
}
}
} else {
if(input.bytesAvailable < 1)
break;
if(input.readByte() == 0x47)
_syncFound = true;
}
}
else
{
_syncFound = false;
var packet:ByteArray = new ByteArray();
if (_key) {
if (_key.type == "AES-128") {
if (input.bytesAvailable < 176) {
if (_decryptBuffer.bytesAvailable < 187) {
break;
}
} else {
var bytesLeft:uint = input.bytesAvailable - 176;
if (bytesLeft > 0 && bytesLeft < 15) {
if (!decryptToBuffer(input, input.bytesAvailable)) {
break;
}
} else {
if (!decryptToBuffer(input, 176)) {
break;
}
}
}
_decryptBuffer.readBytes(packet, 0, 187);
}
} else {
if(input.bytesAvailable < 187)
break;
input.readBytes(packet, 0, 187);
}
var result:ByteArray = processPacket(packet);
if (result !== null) {
output.writeBytes(result);
}
if (bytesAvailableStart - input.bytesAvailable > 10000) {
alternatingYieldCounter = (alternatingYieldCounter + 1) & 0x03;
if (alternatingYieldCounter /*& 0x01 === 1*/) {
_cachedOutputBytes = output;
return null;
}
break;
}
}
}
output.position = 0;
return output.length === 0 ? null : output;
}
private function decryptToBuffer(input:IDataInput, blockSize:int):Boolean{
if (_key) {
// Clear buffer
if (_decryptBuffer.bytesAvailable == 0) {
_decryptBuffer.clear();
}
if (_key.type == "AES-128" && blockSize % 16 == 0 && _key.key) {
if (!_decryptAES) {
_decryptAES = new AES(_key.key);
_decryptAES.pad = "none";
_decryptAES.iv = _iv;
}
// Save buffer position
var currentPosition:uint = _decryptBuffer.position;
_decryptBuffer.position += _decryptBuffer.bytesAvailable;
// Save block to decrypt
var decrypt:ByteArray = new ByteArray;
input.readBytes(decrypt, 0, blockSize);
// Save new IV from ciphertext
var newIv:ByteArray = new ByteArray;
decrypt.position += (decrypt.bytesAvailable-16);
decrypt.readBytes(newIv, 0, 16);
decrypt.position = 0;
// Decrypt
if (input.bytesAvailable == 0) {
_decryptAES.pad = "pkcs7";
}
_decryptAES.decrypt(decrypt);
decrypt.position = 0;
// Write into buffer
_decryptBuffer.writeBytes(decrypt);
_decryptBuffer.position = currentPosition;
// Update AES IV
_decryptAES.iv = newIv;
return true;
}
}
return false;
}
override public function endProcessFile(input:IDataInput):ByteArray
{
_decryptBuffer.clear();
if (_decryptAES) {
_decryptAES.destroy();
}
_decryptAES = null;
return null;
}
public function resetCache():void{
_cachedOutputBytes = null;
alternatingYieldCounter = 0;
_decryptBuffer.clear();
if (_decryptAES) {
_decryptAES.destroy();
}
_decryptAES = null;
}
public function set initialOffset(offset:Number):void{
offset *= 1000; // convert to ms
_videoPES.initialTimestamp = offset;
_audioPES.initialTimestamp = offset;
_mp3audioPES.initialTimestamp = offset;
}
public function set key(key:HTTPStreamingM3U8IndexKey):void {
_key = key;
if (_decryptAES) {
_decryptAES.destroy();
}
_decryptAES = null;
}
public function set iv(iv:String):void {
if (iv) {
_iv = Hex.toArray(iv);
}
}
private function processPacket(packet:ByteArray):ByteArray
{
// decode rest of transport stream prefix (after the 0x47 flag byte)
// top of second byte
var value:uint = packet.readUnsignedByte();
//var tei:Boolean = Boolean(value & 0x80); // error indicator
var pusi:Boolean = Boolean(value & 0x40); // payload unit start indication
//var tpri:Boolean = Boolean(value & 0x20); // transport priority indication
// bottom of second byte and all of third
value <<= 8;
value += packet.readUnsignedByte();
var pid:uint = value & 0x1fff; // packet ID
// fourth byte
value = packet.readUnsignedByte();
//var scramblingControl:uint = (value >> 6) & 0x03; // scrambling control bits
var hasAF:Boolean = Boolean(value & 0x20); // has adaptation field
var hasPD:Boolean = Boolean(value & 0x10); // has payload data
//var ccount:uint = value & 0x0f; // continuty count
// technically hasPD without hasAF is an error, see spec
if(hasAF)
{
// process adaptation field
// don't care about flags
// don't care about clocks here
var af:uint = packet.readUnsignedByte();
packet.position += af; // skip to end
}
return hasPD ? processES(pid, pusi, packet) : null;
}
private function processES(pid:uint, pusi:Boolean, packet:ByteArray):ByteArray
{
var output:ByteArray = null;
if(pid == 0) // PAT
{
if(pusi)
processPAT(packet);
}
else if(pid == _pmtPID)
{
if(pusi)
processPMT(packet);
}
else if(pid == _audioPID)
{
output = _audioPES.processES(pusi, packet);
}
else if(pid == _videoPID)
{
output = _videoPES.processES(pusi, packet);
}
else if(pid == _mp3AudioPID)
{
output = _mp3audioPES.processES(pusi, packet);
}
return output;
}
private function processPAT(packet:ByteArray):void
{
packet.readUnsignedByte(); // pointer:uint
packet.readUnsignedByte(); // tableID:uint
var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring misc and reserved bits
packet.position += 5; // skip tsid + version/cni + sec# + last sec#
remaining -= 5;
while(remaining > 4)
{
packet.readUnsignedShort(); // program number
_pmtPID = packet.readUnsignedShort() & 0x1fff; // 13 bits
remaining -= 4;
//return; // immediately after reading the first pmt ID, if we don't we get the LAST one
}
// and ignore the CRC (4 bytes)
}
private function processPMT(packet:ByteArray):void
{
packet.readUnsignedByte(); // pointer:uint
var tableID:uint = packet.readUnsignedByte();
if (tableID != 0x02)
{
CONFIG::LOGGING
{
logger.warn("PAT pointed to PMT that isn't PMT");
}
return; // don't try to parse it
}
var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring section syntax and reserved
packet.position += 7; // skip program num, rserved, version, cni, section num, last section num, reserved, PCR PID
remaining -= 7;
var piLen:uint = packet.readUnsignedShort() & 0x0fff;
remaining -= 2;
packet.position += piLen; // skip program info
remaining -= piLen;
while(remaining > 4)
{
var type:uint = packet.readUnsignedByte();
var pid:uint = packet.readUnsignedShort() & 0x1fff;
var esiLen:uint = packet.readUnsignedShort() & 0x0fff;
remaining -= 5;
packet.position += esiLen;
remaining -= esiLen;
switch(type)
{
case 0x1b: // H.264 video
_videoPID = pid;
break;
case 0x0f: // AAC Audio / ADTS
_audioPID = pid;
break;
case 0x03: // MP3 Audio (3 & 4)
case 0x04:
_mp3AudioPID = pid;
break;
default:
CONFIG::LOGGING
{
logger.error("unsupported type "+type.toString(16)+" in PMT");
}
break;
}
}
// and ignore CRC
}
override public function flushFileSegment(input:IDataInput):ByteArray
{
var flvBytes:ByteArray = new ByteArray();
var flvBytesVideo:ByteArray = _videoPES.processES(false, null, true);
var flvBytesAudio:ByteArray = _audioPES.processES(false, null, true);
if(flvBytesVideo)
flvBytes.readBytes(flvBytesVideo);
if(flvBytesAudio)
flvBytes.readBytes(flvBytesAudio);
return flvBytes;
}
CONFIG::LOGGING
{
private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMP2TSFileHandler') as Logger;
}
}
}
|
Remove trace call
|
Remove trace call
|
ActionScript
|
isc
|
mruse/osmf-hls-plugin,denivip/osmf-hls-plugin,mruse/osmf-hls-plugin,denivip/osmf-hls-plugin
|
134614d212cbd45645fbbaae3e671b101f5a31fb
|
source/fairygui/GRichTextField.as
|
source/fairygui/GRichTextField.as
|
package fairygui {
import fairygui.utils.ToolSet;
import laya.html.dom.HTMLDivElement;
public class GRichTextField extends GTextField {
public var div:laya.html.dom.HTMLDivElement;
private var _ubbEnabled: Boolean;
private var _color:String;
public function GRichTextField() {
super();
this._text = "";
}
override protected function createDisplayObject(): void {
this._displayObject = this.div = new HTMLDivElement();
this._displayObject.mouseEnabled = true;
this._displayObject["$owner"] = this;
}
override public function set text(value: String):void {
this._text = value;
var text2:String = _text;
if (_templateVars != null)
text2 = parseTemplate(text2);
if(this._ubbEnabled)
this.div.innerHTML = ToolSet.parseUBB(text2);
else
this.div.innerHTML = text2;
}
override public function get text():String {
return this._text;
}
override public function get font(): String {
return this.div.style.font;
}
override public function set font(value: String):void {
if(value)
this.div.style.font = value;
else
this.div.style.font = fairygui.UIConfig.defaultFont;
}
override public function get fontSize(): Number {
return this.div.style.fontSize;
}
override public function set fontSize(value: Number):void {
this.div.style.fontSize = value;
}
override public function get color(): String {
return _color;
}
override public function set color(value: String):void {
if (_color != value) {
_color = value;
this.div.style.color = value;
if (this._gearColor.controller)
this._gearColor.updateState();
}
}
override public function get align(): String {
return this.div.style.align;
}
override public function set align(value: String):void {
this.div.style.align = value;
}
override public function get valign(): String {
return this.div.style.valign;
}
override public function set valign(value: String):void {
this.div.style.valign = value;
}
override public function get leading(): Number {
return this.div.style.leading;
}
override public function set leading(value: Number):void {
this.div.style.leading = value;
}
override public function get bold(): Boolean {
return this.div.style.bold;
}
override public function set bold(value: Boolean):void {
this.div.style.bold = value;
}
override public function get italic(): Boolean {
return this.div.style.italic;
}
override public function set italic(value: Boolean):void {
this.div.style.italic = value;
}
override public function get stroke(): Number {
return this.div.style.stroke;
}
override public function set stroke(value: Number):void {
this.div.style.stroke = value;
}
override public function get strokeColor(): String {
return this.div.style.strokeColor;
}
override public function set strokeColor(value: String):void {
this.div.style.strokeColor = value;
updateGear(4);
}
override public function set ubbEnabled(value: Boolean):void {
this._ubbEnabled = value;
}
override public function get ubbEnabled(): Boolean {
return this._ubbEnabled;
}
override protected function handleSizeChanged(): void {
this.div.size(this.width, this.height);
}
}
}
|
package fairygui {
import fairygui.utils.ToolSet;
import laya.html.dom.HTMLDivElement;
public class GRichTextField extends GTextField {
public var div:laya.html.dom.HTMLDivElement;
private var _ubbEnabled: Boolean;
private var _color:String;
public function GRichTextField() {
super();
this._text = "";
}
override protected function createDisplayObject(): void {
this._displayObject = this.div = new HTMLDivElement();
this._displayObject.mouseEnabled = true;
this._displayObject["$owner"] = this;
}
override public function set text(value: String):void {
this._text = value;
var text2:String = _text;
if (_templateVars != null)
text2 = parseTemplate(text2);
if(this._ubbEnabled)
this.div.innerHTML = ToolSet.parseUBB(text2);
else
this.div.innerHTML = text2;
}
override public function get text():String {
return this._text;
}
override public function get font(): String {
return this.div.style.font;
}
override public function set font(value: String):void {
if(value)
this.div.style.font = value;
else
this.div.style.font = fairygui.UIConfig.defaultFont;
}
override public function get fontSize(): Number {
return this.div.style.fontSize;
}
override public function set fontSize(value: Number):void {
this.div.style.fontSize = value;
}
override public function get color(): String {
return _color;
}
override public function set color(value: String):void {
if (_color != value) {
_color = value;
this.div.style.color = value;
if (this._gearColor.controller)
this._gearColor.updateState();
}
}
override public function get align(): String {
return this.div.style.align;
}
override public function set align(value: String):void {
this.div.style.align = value;
}
override public function get valign(): String {
return this.div.style.valign;
}
override public function set valign(value: String):void {
this.div.style.valign = value;
}
override public function get leading(): Number {
return this.div.style.leading;
}
override public function set leading(value: Number):void {
this.div.style.leading = value;
}
override public function get bold(): Boolean {
return this.div.style.bold;
}
override public function set bold(value: Boolean):void {
this.div.style.bold = value;
}
override public function get italic(): Boolean {
return this.div.style.italic;
}
override public function set italic(value: Boolean):void {
this.div.style.italic = value;
}
override public function get stroke(): Number {
return this.div.style.stroke;
}
override public function set stroke(value: Number):void {
this.div.style.stroke = value;
}
override public function get strokeColor(): String {
return this.div.style.strokeColor;
}
override public function set strokeColor(value: String):void {
this.div.style.strokeColor = value;
updateGear(4);
}
override public function set ubbEnabled(value: Boolean):void {
this._ubbEnabled = value;
}
override public function get ubbEnabled(): Boolean {
return this._ubbEnabled;
}
override protected function handleSizeChanged(): void {
this.div.size(this.width, this.height);
this.div.style.width = this.width;
this.div.style.height = this.height;
}
}
}
|
fix #25
|
fix #25
|
ActionScript
|
mit
|
fairygui/FairyGUI-layabox,fairygui/FairyGUI-layabox
|
d45e875c94f22d75ced714ad6f378f0086c93dec
|
src/org/mangui/hls/demux/ID3.as
|
src/org/mangui/hls/demux/ID3.as
|
package org.mangui.hls.demux {
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class ID3 {
public var len : int;
public var hasTimestamp : Boolean = false;
public var timestamp : Number;
/* create ID3 object by parsing ByteArray, looking for ID3 tag length, and timestamp */
public function ID3(data : ByteArray) {
var tagSize : uint = 0;
try {
var pos : uint = data.position;
var header : String;
do {
header = data.readUTFBytes(3);
if (header == 'ID3') {
// skip 24 bits
data.position += 3;
// retrieve tag length
var byte1 : uint = data.readUnsignedByte() & 0x7f;
var byte2 : uint = data.readUnsignedByte() & 0x7f;
var byte3 : uint = data.readUnsignedByte() & 0x7f;
var byte4 : uint = data.readUnsignedByte() & 0x7f;
tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
var end_pos : uint = data.position + tagSize;
CONFIG::LOGGING {
Log.debug2("ID3 tag found, size/end pos:" + tagSize + "/" + end_pos);
}
// read tag
_parseFrame(data, end_pos);
data.position = end_pos;
} else if (header == '3DI') {
// http://id3.org/id3v2.4.0-structure chapter 3.4. ID3v2 footer
data.position += 7;
CONFIG::LOGGING {
Log.debug2("3DI footer found, end pos:" + data.position);
}
} else {
data.position -= 3;
len = data.position - pos;
CONFIG::LOGGING {
if (len) {
Log.debug2("ID3 len:" + len);
if (!hasTimestamp) {
Log.warn("ID3 tag found, but no timestamp");
}
}
}
return;
}
} while (true);
} catch(e : Error) {
}
len = 0;
return;
};
/* Each Elementary Audio Stream segment MUST signal the timestamp of
its first sample with an ID3 PRIV tag [ID3] at the beginning of
the segment. The ID3 PRIV owner identifier MUST be
"com.apple.streaming.transportStreamTimestamp". The ID3 payload
MUST be a 33-bit MPEG-2 Program Elementary Stream timestamp
expressed as a big-endian eight-octet number, with the upper 31
bits set to zero.
*/
private function _parseFrame(data : ByteArray, end_pos : uint) : void {
if (data.readUTFBytes(4) == "PRIV") {
while (data.position + 53 <= end_pos) {
// owner should be "com.apple.streaming.transportStreamTimestamp"
if (data.readUTFBytes(44) == 'com.apple.streaming.transportStreamTimestamp') {
// smelling even better ! we found the right descriptor
// skip null character (string end) + 3 first bytes
data.position += 4;
// timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
var pts_33_bit : Number = data.readUnsignedByte() & 0x1;
hasTimestamp = true;
timestamp = (data.readUnsignedInt() / 90) << pts_33_bit;
CONFIG::LOGGING {
Log.debug("ID3 timestamp found:" + timestamp);
}
return;
} else {
// rewind 44 read bytes + move to next byte
data.position -= 43;
}
}
}
}
}
}
|
package org.mangui.hls.demux {
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class ID3 {
public var len : int;
public var hasTimestamp : Boolean = false;
public var timestamp : Number;
/* create ID3 object by parsing ByteArray, looking for ID3 tag length, and timestamp */
public function ID3(data : ByteArray) {
var tagSize : uint = 0;
try {
var pos : uint = data.position;
var header : String;
do {
header = data.readUTFBytes(3);
if (header == 'ID3') {
// skip 24 bits
data.position += 3;
// retrieve tag length
var byte1 : uint = data.readUnsignedByte() & 0x7f;
var byte2 : uint = data.readUnsignedByte() & 0x7f;
var byte3 : uint = data.readUnsignedByte() & 0x7f;
var byte4 : uint = data.readUnsignedByte() & 0x7f;
tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
var end_pos : uint = data.position + tagSize;
CONFIG::LOGGING {
Log.debug2("ID3 tag found, size/end pos:" + tagSize + "/" + end_pos);
}
// read tag
_parseFrame(data, end_pos);
data.position = end_pos;
} else if (header == '3DI') {
// http://id3.org/id3v2.4.0-structure chapter 3.4. ID3v2 footer
data.position += 7;
CONFIG::LOGGING {
Log.debug2("3DI footer found, end pos:" + data.position);
}
} else {
data.position -= 3;
len = data.position - pos;
CONFIG::LOGGING {
if (len) {
Log.debug2("ID3 len:" + len);
if (!hasTimestamp) {
Log.warn("ID3 tag found, but no timestamp");
}
}
}
return;
}
} while (true);
} catch(e : Error) {
}
len = 0;
return;
};
/* Each Elementary Audio Stream segment MUST signal the timestamp of
its first sample with an ID3 PRIV tag [ID3] at the beginning of
the segment. The ID3 PRIV owner identifier MUST be
"com.apple.streaming.transportStreamTimestamp". The ID3 payload
MUST be a 33-bit MPEG-2 Program Elementary Stream timestamp
expressed as a big-endian eight-octet number, with the upper 31
bits set to zero.
*/
private function _parseFrame(data : ByteArray, end_pos : uint) : void {
if (data.readUTFBytes(4) == "PRIV") {
while (data.position + 53 <= end_pos) {
// owner should be "com.apple.streaming.transportStreamTimestamp"
if (data.readUTFBytes(44) == 'com.apple.streaming.transportStreamTimestamp') {
// smelling even better ! we found the right descriptor
// skip null character (string end) + 3 first bytes
data.position += 4;
// timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
var pts_33_bit : int = data.readUnsignedByte() & 0x1;
hasTimestamp = true;
timestamp = (data.readUnsignedInt() / 90);
if (pts_33_bit) {
timestamp += 47721858.84; // 2^32 / 90
}
CONFIG::LOGGING {
Log.debug("ID3 timestamp found:" + timestamp);
}
return;
} else {
// rewind 44 read bytes + move to next byte
data.position -= 43;
}
}
}
}
}
}
|
fix ID3 timestamp 33bit handling
|
fix ID3 timestamp 33bit handling
|
ActionScript
|
mpl-2.0
|
loungelogic/flashls,stevemayhew/flashls,NicolasSiver/flashls,dighan/flashls,School-Improvement-Network/flashls,loungelogic/flashls,mangui/flashls,hola/flashls,Peer5/flashls,tedconf/flashls,stevemayhew/flashls,codex-corp/flashls,thdtjsdn/flashls,suuhas/flashls,aevange/flashls,fixedmachine/flashls,mangui/flashls,Boxie5/flashls,Peer5/flashls,JulianPena/flashls,clappr/flashls,suuhas/flashls,stevemayhew/flashls,tedconf/flashls,ryanhefner/flashls,jlacivita/flashls,NicolasSiver/flashls,suuhas/flashls,dighan/flashls,ryanhefner/flashls,aevange/flashls,vidible/vdb-flashls,ryanhefner/flashls,Corey600/flashls,School-Improvement-Network/flashls,fixedmachine/flashls,codex-corp/flashls,viktorot/flashls,stevemayhew/flashls,School-Improvement-Network/flashls,neilrackett/flashls,Boxie5/flashls,aevange/flashls,jlacivita/flashls,suuhas/flashls,viktorot/flashls,vidible/vdb-flashls,hola/flashls,aevange/flashls,neilrackett/flashls,clappr/flashls,Corey600/flashls,Peer5/flashls,Peer5/flashls,JulianPena/flashls,viktorot/flashls,thdtjsdn/flashls,ryanhefner/flashls
|
8df8c10c5f17acc057a3d75dc571fd19113e6d48
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
if (value != _frustumCulling)
{
_frustumCulling = value;
if (value == FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
if (_mesh.localToWorldTransformChanged.hasCallback(meshLocalToWorldChangedHandler))
{
_mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
}
}
else if (_mesh && _mesh.scene)
{
_mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
testCulling();
}
}
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider(
{ computedVisibility : true },
'MeshVisibilityDataProvider',
DataProviderUsage.EXCLUSIVE
);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
{
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
}
mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler);
mesh.bindings.addProvider(_data);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler);
mesh.bindings.removeProvider(_data);
}
private function computedVisiblityChangedHandler(node : ISceneNode,
computedVisibility : Boolean) : void
{
_data.computedVisibility = computedVisibility;
}
private function worldToScreenChangedHandler(bindings : DataBindings,
propertyName : String,
bindingName : String,
value : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (_mesh && _mesh.geometry && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
if (value != _frustumCulling)
{
_frustumCulling = value;
if (value == FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
if (_mesh.localToWorldTransformChanged.hasCallback(meshLocalToWorldChangedHandler))
{
_mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
}
}
else if (_mesh && _mesh.scene)
{
_mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
testCulling();
}
}
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider(
{ computedVisibility : true },
'MeshVisibilityDataProvider',
DataProviderUsage.EXCLUSIVE
);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
{
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
}
mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler);
mesh.bindings.addProvider(_data);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler);
mesh.bindings.removeProvider(_data);
}
private function computedVisiblityChangedHandler(node : ISceneNode,
computedVisibility : Boolean) : void
{
_data.computedVisibility = computedVisibility;
}
private function worldToScreenChangedHandler(bindings : DataBindings,
bindingName : String,
oldValue : Matrix4x4,
value : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (_mesh && _mesh.geometry && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();
}
}
}
|
Fix for Bug #1244 suspicious calls to Matrix4x4.toString(), propertyName and BindingName were the same parameter and bindingName (String) was used instead of oldValue (Matrix4x4).
|
Fix for Bug #1244 suspicious calls to Matrix4x4.toString(), propertyName and BindingName were the same parameter and bindingName (String) was used instead of oldValue (Matrix4x4).
|
ActionScript
|
mit
|
aerys/minko-as3
|
7df60521d537e9d9d17f02208738e0723b6f87cc
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/binding/PropertyWatcher.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/binding/PropertyWatcher.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.binding
{
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.events.ValueChangeEvent;
/**
* The PropertyWatcher class is the data-binding class that watches
* for changes to various properties in objects.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class PropertyWatcher extends WatcherBase
{
/**
* Constructor.
*
* @param source The object who's property we are watching.
* @param proeprtyName The name of the property we are watching.
* @param eventNames The name or array of names of events that get
* dispatched when the property changes.
* @param getterFunction A function to call to get the value
* of the property changes if the property is not public.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function PropertyWatcher(source:Object, propertyName:String, eventNames:Object,
getterFunction:Function)
{
this.source = source;
this.propertyName = propertyName;
this.getterFunction = getterFunction;
this.eventNames = eventNames;
}
/**
* The object who's property we are watching.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var source:Object;
/**
* The name of the property we are watching.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var propertyName:String;
/**
* The name or array of names of events that get
* dispatched when the property changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var eventNames:Object;
/**
* A function to call to get the value
* of the property changes if the property is
* not public.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var getterFunction:Function;
/**
* The event handler that gets called when
* the change events are dispatched.
*
* @param event The event that was dispatched to notify of a value change.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected function changeHandler(event:Event):void
{
if (event is ValueChangeEvent)
{
var propName:String = ValueChangeEvent(event).propertyName;
if (propName != propertyName)
return;
}
wrapUpdate(updateProperty);
notifyListeners();
}
//--------------------------------------------------------------------------
//
// Overridden methods: Watcher
//
//--------------------------------------------------------------------------
/**
* @private
*/
override public function parentChanged(parent:Object):void
{
if (source && source is IEventDispatcher)
removeEventListeners();
source = parent;
if (source && source is IEventDispatcher)
addEventListeners();
// Now get our property.
wrapUpdate(updateProperty);
}
private function addEventListeners():void
{
if (eventNames is String)
source.addEventListener(eventNames as String, changeHandler);
else if (eventNames is Array)
{
var arr:Array = eventNames as Array;
var n:int = arr.length;
for (var i:int = 0; i < n; i++)
{
var eventName:String = eventNames[i];
source.addEventListener(eventName, changeHandler);
}
}
}
private function removeEventListeners():void
{
if (eventNames is String)
source.removeEventListener(eventNames as String, changeHandler);
else if (eventNames is Array)
{
var arr:Array = eventNames as Array;
var n:int = arr.length;
for (var i:int = 0; i < n; i++)
{
var eventName:String = eventNames[i];
source.removeEventListener(eventName, changeHandler);
}
}
}
/**
* Gets the actual property then updates
* the Watcher's children appropriately.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
private function updateProperty():void
{
if (source)
{
if (propertyName == "this")
{
value = source;
}
else
{
if (getterFunction != null)
{
value = getterFunction.apply(source, [ propertyName ]);
}
else
{
value = source[propertyName];
}
}
}
else
{
value = null;
}
updateChildren();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.binding
{
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.events.ValueChangeEvent;
/**
* The PropertyWatcher class is the data-binding class that watches
* for changes to various properties in objects.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class PropertyWatcher extends WatcherBase
{
/**
* Constructor.
*
* @param source The object who's property we are watching.
* @param proeprtyName The name of the property we are watching.
* @param eventNames The name or array of names of events that get
* dispatched when the property changes.
* @param getterFunction A function to call to get the value
* of the property changes if the property is not public.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function PropertyWatcher(source:Object, propertyName:String, eventNames:Object,
getterFunction:Function)
{
this.source = source;
this.propertyName = propertyName;
this.getterFunction = getterFunction;
this.eventNames = eventNames;
}
/**
* The object who's property we are watching.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var source:Object;
/**
* The name of the property we are watching.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var propertyName:String;
/**
* The name or array of names of events that get
* dispatched when the property changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var eventNames:Object;
/**
* A function to call to get the value
* of the property changes if the property is
* not public.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var getterFunction:Function;
/**
* The event handler that gets called when
* the change events are dispatched.
*
* @param event The event that was dispatched to notify of a value change.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected function changeHandler(event:Event):void
{
if (event is ValueChangeEvent)
{
var propName:String = ValueChangeEvent(event).propertyName;
if (propName != propertyName)
return;
}
wrapUpdate(updateProperty);
notifyListeners();
}
//--------------------------------------------------------------------------
//
// Overridden methods: Watcher
//
//--------------------------------------------------------------------------
/**
* @private
*/
override public function parentChanged(parent:Object):void
{
if (source && source is IEventDispatcher)
removeEventListeners();
if (source is PropertyWatcher)
source = PropertyWatcher(parent).value;
else
source = parent;
if (source && source is IEventDispatcher)
addEventListeners();
// Now get our property.
wrapUpdate(updateProperty);
notifyListeners();
}
private function addEventListeners():void
{
if (eventNames is String)
source.addEventListener(eventNames as String, changeHandler);
else if (eventNames is Array)
{
var arr:Array = eventNames as Array;
var n:int = arr.length;
for (var i:int = 0; i < n; i++)
{
var eventName:String = eventNames[i];
source.addEventListener(eventName, changeHandler);
}
}
}
private function removeEventListeners():void
{
if (eventNames is String)
source.removeEventListener(eventNames as String, changeHandler);
else if (eventNames is Array)
{
var arr:Array = eventNames as Array;
var n:int = arr.length;
for (var i:int = 0; i < n; i++)
{
var eventName:String = eventNames[i];
source.removeEventListener(eventName, changeHandler);
}
}
}
/**
* Gets the actual property then updates
* the Watcher's children appropriately.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
private function updateProperty():void
{
if (source)
{
if (propertyName == "this")
{
value = source;
}
else
{
if (getterFunction != null)
{
value = getterFunction.apply(source, [ propertyName ]);
}
else
{
value = source[propertyName];
}
}
}
else
{
value = null;
}
updateChildren();
}
}
}
|
fix generic databinding
|
fix generic databinding
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
414a4b6c9d458af4ec11face70514d9a11368deb
|
com/segonquart/idiomesAnimation.as
|
com/segonquart/idiomesAnimation.as
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class idiomesAnimation extends Movieclip
{
private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function idiomesAnimation():Void
{
this.onEnterFrame = this.enterSlide;
}
private function onSlideIN()
{
this.stop();
this.onEnterFrame = this.enterSlide;
}
private function enterSlide()
{
arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);
}
public function IdiomesColour()
{
this.onRelease = this arrayColour;
target = this.arrayLang_arr[i];
target._tint = 0x8DC60D;
return this;
}
private function arrayColour()
{
for ( var:i ; arrayLang_arr[i] <4; i++)
{
this.colorTo("#628D22", 0.3, "easeOutCirc");
_parent.colorTo('#4b4b4b', 1, 'linear', .2);
}
}
}
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class idiomesAnimation extends Movieclip
{
private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function idiomesAnimation():Void
{
this.onEnterFrame = this.enterSlide;
}
private function onSlideIN()
{
this.stop();
this.onEnterFrame = this.enterSlide;
}
private function enterSlide()
{
arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);
}
public function IdiomesColour()
{
this.onRelease = this arrayColour;
target = this.arrayLang_arr[i];
target._tint = 0x8DC60D;
return this;
}
private function arrayColour()
{
for ( var:i ; arrayLang_arr[i] <4; i++)
{
this.colorTo("#628D22", 0.3, "easeOutCirc");
_parent.colorTo('#4b4b4b', 1, 'linear', .2);
}
}
}
|
Update idiomesAnimation.as
|
Update idiomesAnimation.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
b517c62500f4289dbed5c8b003760e3fa9203876
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
package org.arisgames.editor.util
{
public class AppConstants
{
//Server URL
//public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://arisgames.org/stagingserver1"; //For other URL's to append to- Staging
public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server"; //For other URL's to append to- Dev
public static const APPLICATION_ENVIRONMENT_SERVICES_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris/"; //staging
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris/uploadhandler.php"; //davembp
public static const APPLICATION_ENVIRONMENT_GATEWAY_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/gateway.php"; //services-config.xml
//Google API
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp
public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev
// Dynamic Events
public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged";
public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette";
public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded";
public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch";
public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected";
public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion";
public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem";
public static const DYNAMICEVENT_HIGHLIGHTOBJECTPALETTEITEM:String = "HighlightObjectPaletteItem";
public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor";
public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker";
public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor";
public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor";
public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap";
public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange";
public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap";
public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap";
public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor";
public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor";
public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor";
public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR";
public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR";
public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS";
// Placemark Content
public static const CONTENTTYPE_PAGE:String = "Plaque";
public static const CONTENTTYPE_CHARACTER:String = "Character";
public static const CONTENTTYPE_ITEM:String = "Item";
public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group";
public static const CONTENTTYPE_PAGE_VAL:Number = 0;
public static const CONTENTTYPE_CHARACTER_VAL:Number = 1;
public static const CONTENTTYPE_ITEM_VAL:Number = 2;
public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3;
public static const CONTENTTYPE_PAGE_DATABASE:String = "Node";
public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc";
public static const CONTENTTYPE_ITEM_DATABASE:String = "Item";
public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30;
// Label Constants
public static const BUTTON_LOGIN:String = "Login!";
public static const BUTTON_REGISTER:String = "Register!";
public static const RADIO_FORGOTPASSWORD:String = "Forgot Password";
public static const RADIO_FORGOTUSERNAME:String = "Forgot Username";
// Max allowed upload size for media.........MB....KB....Bytes
public static const MAX_UPLOAD_SIZE:Number = 10 * 1024 * 1024 //In bytes
// Media Types
public static const MEDIATYPE:String = "Media Types";
public static const MEDIATYPE_IMAGE:String = "Image";
public static const MEDIATYPE_AUDIO:String = "Audio";
public static const MEDIATYPE_VIDEO:String = "Video";
public static const MEDIATYPE_ICON:String = "Icon";
public static const MEDIATYPE_SEPARATOR:String = " ";
public static const MEDIATYPE_UPLOADNEW:String = " ";
// Media-tree-icon Types
public static const MEDIATREEICON_SEPARATOR:String = "separatorIcon";
public static const MEDIATREEICON_UPLOAD:String = "uploadIcon";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item";
// Requirement Types
public static const REQUIREMENTTYPE_LOCATION:String = "Location";
public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay";
public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete";
public static const REQUIREMENTTYPE_NODE:String = "Node";
// Requirement Options
public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM";
public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least Qty of an Item";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than Qty of an Item";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_HUMAN:String = "Player Has Completed Quest";
public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND";
public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All";
public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR";
public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one";
// Defaults
public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1;
public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2;
public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3;
// Palette Tree Stuff
public static const PALETTE_TREE_SELF_FOLDER_ID:Number = 0;
public static const PLAYER_GENERATED_MEDIA_FOLDER_ID:Number = 99;
public static const PLAYER_GENERATED_MEDIA_FOLDER_NAME:String = "Player Created Items";
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
package org.arisgames.editor.util
{
public class AppConstants
{
//Server URL
//public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://arisgames.org/stagingserver1"; //For other URL's to append to- Staging
public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server"; //For other URL's to append to- Dev
public static const APPLICATION_ENVIRONMENT_SERVICES_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris/"; //staging
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris/uploadhandler.php"; //davembp
public static const APPLICATION_ENVIRONMENT_GATEWAY_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/gateway.php"; //services-config.xml
//Google API
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp
public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev
// Dynamic Events
public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged";
public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette";
public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded";
public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch";
public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected";
public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion";
public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem";
public static const DYNAMICEVENT_HIGHLIGHTOBJECTPALETTEITEM:String = "HighlightObjectPaletteItem";
public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor";
public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker";
public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor";
public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor";
public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap";
public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange";
public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap";
public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap";
public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor";
public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor";
public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor";
public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR";
public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR";
public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS";
// Placemark Content
public static const CONTENTTYPE_PAGE:String = "Plaque";
public static const CONTENTTYPE_CHARACTER:String = "Character";
public static const CONTENTTYPE_ITEM:String = "Item";
public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group";
public static const CONTENTTYPE_PAGE_VAL:Number = 0;
public static const CONTENTTYPE_CHARACTER_VAL:Number = 1;
public static const CONTENTTYPE_ITEM_VAL:Number = 2;
public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3;
public static const CONTENTTYPE_PAGE_DATABASE:String = "Node";
public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc";
public static const CONTENTTYPE_ITEM_DATABASE:String = "Item";
public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30;
// Label Constants
public static const BUTTON_LOGIN:String = "Login!";
public static const BUTTON_REGISTER:String = "Register!";
public static const RADIO_FORGOTPASSWORD:String = "Forgot Password";
public static const RADIO_FORGOTUSERNAME:String = "Forgot Username";
// Max allowed upload size for media.........MB....KB....Bytes
public static const MAX_UPLOAD_SIZE:Number = 10 * 1024 * 1024 //In bytes
// Media Types
public static const MEDIATYPE:String = "Media Types";
public static const MEDIATYPE_IMAGE:String = "Image";
public static const MEDIATYPE_AUDIO:String = "Audio";
public static const MEDIATYPE_VIDEO:String = "Video";
public static const MEDIATYPE_ICON:String = "Icon";
public static const MEDIATYPE_SEPARATOR:String = " ";
public static const MEDIATYPE_UPLOADNEW:String = " ";
// Media-tree-icon Types
public static const MEDIATREEICON_SEPARATOR:String = "separatorIcon";
public static const MEDIATREEICON_UPLOAD:String = "uploadIcon";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item";
// Requirement Types
public static const REQUIREMENTTYPE_LOCATION:String = "Location";
public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay";
public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete";
public static const REQUIREMENTTYPE_NODE:String = "Node";
// Requirement Options
public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM";
public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least Qty of an Item";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than Qty of an Item";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_HUMAN:String = "Player Has Completed Quest";
public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND";
public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All";
public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR";
public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one";
// Defaults
public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1;
public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2;
public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3;
// Palette Tree Stuff
public static const PALETTE_TREE_SELF_FOLDER_ID:Number = 0;
public static const PLAYER_GENERATED_MEDIA_FOLDER_ID:Number = -1;
public static const PLAYER_GENERATED_MEDIA_FOLDER_NAME:String = "Player Created Items";
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
Set constant of Folder ID to -1
|
Set constant of Folder ID to -1
|
ActionScript
|
mit
|
ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames
|
632a430df657e011fc73ce29930b6a0439c0cce5
|
generator/sources/as3/delegates/QueuedRequestDelegate.as
|
generator/sources/as3/delegates/QueuedRequestDelegate.as
|
package com.kaltura.delegates {
import com.kaltura.commands.MultiRequest;
import com.kaltura.commands.QueuedRequest;
import com.kaltura.config.KalturaConfig;
import com.kaltura.errors.KalturaError;
import com.kaltura.net.KalturaCall;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
public class QueuedRequestDelegate extends WebDelegateBase {
public function QueuedRequestDelegate(call:KalturaCall = null, config:KalturaConfig = null) {
super(call, config);
}
override public function parse( result : XML ) : *
{
var resArr : Array = new Array();
for ( var i:int=0; i<(call as QueuedRequest).calls.length; i++ )
{
var callClassName : String = getQualifiedClassName( (call as QueuedRequest).calls[i] );
var commandName : String = callClassName.split("::")[1];
var packageArr : Array = (callClassName.split("::")[0]).split(".");
var importFrom : String = packageArr[packageArr.length-1];
var clsName : String ;
var cls : Class;
var myInst : Object;
if (commandName == "MultiRequest") {
clsName = "com.kaltura.delegates.MultiRequestDelegate";
cls = getDefinitionByName( clsName ) as Class;
myInst = new cls(/*(call as QueuedRequest).calls[i]*/null , null);
myInst.call = (call as QueuedRequest).calls[i];
}
else {
clsName = "com.kaltura.delegates."+importFrom+"."+ commandName +"Delegate"; //'com.kaltura.delegates.session.SessionStartDelegate'
cls = getDefinitionByName( clsName ) as Class;//(') as Class;
myInst = new cls(null , null);
}
//build the result as a regular result
var xml : String = "<result><result>";
if (commandName == "MultiRequest") {
// add as many items as the multirequest had
var nActions:int = ((call as QueuedRequest).calls[i] as MultiRequest).actions.length;
for (var j:int = 0; j<nActions ; j++) {
xml += result.result.item[j + i].toString();
}
// skip to the result of the next call that wasn't part of the MR:
i+= nActions;
}
else {
xml += result.result.item[i].children().toString();
}
xml +="</result></result>";
// add the item or a matching error:
var kErr:KalturaError = validateKalturaResponse(xml);
if (kErr == null) {
var res : XML = new XML(xml);
try {
var obj : Object = (myInst as WebDelegateBase).parse( res );
resArr.push( obj );
} catch (e:Error) {
kErr = new KalturaError();
kErr.errorCode = String(e.errorID);
kErr.errorMsg = e.message;
resArr.push( kErr );
}
}
else {
resArr.push(kErr);
}
}
return resArr;
}
}
}
|
package com.kaltura.delegates {
import com.kaltura.commands.MultiRequest;
import com.kaltura.commands.QueuedRequest;
import com.kaltura.config.KalturaConfig;
import com.kaltura.errors.KalturaError;
import com.kaltura.net.KalturaCall;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
public class QueuedRequestDelegate extends WebDelegateBase {
public function QueuedRequestDelegate(call:KalturaCall = null, config:KalturaConfig = null) {
super(call, config);
}
override public function parse( result : XML ) : *
{
var resArr : Array = new Array();
var resInd:int = 0; // index for scanning result
for ( var i:int=0; i<(call as QueuedRequest).calls.length; i++ )
{
var callClassName : String = getQualifiedClassName( (call as QueuedRequest).calls[i] );
var commandName : String = callClassName.split("::")[1];
var packageArr : Array = (callClassName.split("::")[0]).split(".");
var importFrom : String = packageArr[packageArr.length-1];
var clsName : String ;
var cls : Class;
var myInst : Object;
if (commandName == "MultiRequest") {
clsName = "com.kaltura.delegates.MultiRequestDelegate";
cls = getDefinitionByName( clsName ) as Class;
myInst = new cls(null , null);
// set the call after the constructor, so we don't fire execute()
myInst.call = (call as QueuedRequest).calls[i];
}
else {
clsName = "com.kaltura.delegates."+importFrom+"."+ commandName +"Delegate"; //'com.kaltura.delegates.session.SessionStartDelegate'
cls = getDefinitionByName( clsName ) as Class;//(') as Class;
myInst = new cls(null , null);
}
//build the result as a regular result
var xml : String = "<result><result>";
if (commandName == "MultiRequest") {
// add as many items as the multirequest had
var nActions:int = ((call as QueuedRequest).calls[i] as MultiRequest).actions.length;
for (var j:int = 0; j<nActions ; j++) {
xml += result.result.item[j + resInd].toXMLString();
}
// skip to the result of the next call that wasn't part of the MR:
resInd+= nActions-1;
}
else {
xml += result.result.item[resInd].children().toString();
resInd++;
}
xml +="</result></result>";
// add the item or a matching error:
var kErr:KalturaError = validateKalturaResponse(xml);
if (kErr == null) {
var res : XML = new XML(xml);
try {
var obj : Object = (myInst as WebDelegateBase).parse( res );
resArr.push( obj );
} catch (e:Error) {
kErr = new KalturaError();
kErr.errorCode = String(e.errorID);
kErr.errorMsg = e.message;
resArr.push( kErr );
}
}
else {
resArr.push(kErr);
}
}
return resArr;
}
}
}
|
use 2 indices when looping through result to handle calls after a MR
|
use 2 indices when looping through result to handle calls after a MR
git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@58550 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
ActionScript
|
agpl-3.0
|
matsuu/server,DBezemer/server,doubleshot/server,ratliff/server,kaltura/server,ratliff/server,ratliff/server,kaltura/server,ivesbai/server,DBezemer/server,kaltura/server,gale320/server,gale320/server,matsuu/server,DBezemer/server,doubleshot/server,ratliff/server,jorgevbo/server,gale320/server,ratliff/server,ratliff/server,gale320/server,ivesbai/server,doubleshot/server,doubleshot/server,kaltura/server,ivesbai/server,DBezemer/server,ivesbai/server,gale320/server,jorgevbo/server,ivesbai/server,jorgevbo/server,doubleshot/server,kaltura/server,matsuu/server,doubleshot/server,gale320/server,matsuu/server,DBezemer/server,matsuu/server,jorgevbo/server,jorgevbo/server,ivesbai/server,matsuu/server,ratliff/server,DBezemer/server,doubleshot/server,gale320/server,jorgevbo/server,ivesbai/server,ratliff/server,ivesbai/server,DBezemer/server,kaltura/server,jorgevbo/server,jorgevbo/server,DBezemer/server,gale320/server,matsuu/server,matsuu/server,doubleshot/server
|
cf83ff1a159e3400be1d5068b5b570b9ca3555c9
|
HLSPlugin/src/com/kaltura/hls/HLSLoader.as
|
HLSPlugin/src/com/kaltura/hls/HLSLoader.as
|
package com.kaltura.hls
{
import com.kaltura.hls.m2ts.M2TSNetLoader;
import com.kaltura.hls.manifest.HLSManifestParser;
import com.kaltura.hls.manifest.HLSManifestPlaylist;
import com.kaltura.hls.manifest.HLSManifestStream;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import org.osmf.elements.VideoElement;
import org.osmf.elements.proxyClasses.LoadFromDocumentLoadTrait;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorEvent;
import org.osmf.media.DefaultMediaFactory;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.MediaTypeUtil;
import org.osmf.media.URLResource;
import org.osmf.metadata.Metadata;
import org.osmf.metadata.MetadataNamespaces;
import org.osmf.net.DynamicStreamingItem;
import org.osmf.net.StreamType;
import org.osmf.net.StreamingItem;
import org.osmf.net.StreamingItemType;
import org.osmf.traits.LoadState;
import org.osmf.traits.LoadTrait;
import org.osmf.traits.LoaderBase;
import org.osmf.utils.URL;
public class HLSLoader extends LoaderBase
{
protected var loadTrait:LoadTrait;
protected var manifestLoader:URLLoader;
protected var parser:HLSManifestParser;
protected var factory:DefaultMediaFactory = new DefaultMediaFactory();
private var supportedMimeTypes:Vector.<String> = new Vector.<String>();
public function HLSLoader()
{
super();
supportedMimeTypes.push( "application/x-mpegURL" );
supportedMimeTypes.push( "application/vnd.apple.mpegURL" );
supportedMimeTypes.push( "vnd.apple.mpegURL" );
supportedMimeTypes.push( "video/MP2T" );
}
override protected function executeLoad(loadTrait:LoadTrait):void
{
this.loadTrait = loadTrait;
updateLoadTrait(loadTrait, LoadState.LOADING);
var url:String = URLResource(loadTrait.resource).url;
manifestLoader = new URLLoader(new URLRequest(url));
manifestLoader.addEventListener(Event.COMPLETE, onComplete);
manifestLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
manifestLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
private function onComplete(event:Event):void
{
manifestLoader.removeEventListener(Event.COMPLETE, onComplete);
manifestLoader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
manifestLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
try {
var resourceData:String = String((event.target as URLLoader).data);
var url:String = URLResource(loadTrait.resource).url;
// Start parsing the manifest.
parser = new HLSManifestParser();
parser.addEventListener(Event.COMPLETE, onManifestComplete);
parser.parse(resourceData, url);
}
catch (parseError:Error)
{
updateLoadTrait(loadTrait, LoadState.LOAD_ERROR);
loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(parseError.errorID, parseError.message)));
}
}
protected function onManifestComplete(event:Event):void
{
trace("Manifest is loaded.");
var isDVR:Boolean = false;
// Construct the streaming resource and set it as our resource.
var stream:HLSStreamingResource = new HLSStreamingResource(URLResource(loadTrait.resource).url, "", StreamType.DVR);
stream.manifest = parser;
var item:DynamicStreamingItem;
var items:Vector.<DynamicStreamingItem> = new Vector.<DynamicStreamingItem>();
for(var i:int=0; i<parser.streams.length; i++)
{
var curStream:HLSManifestStream = parser.streams[i];
//If there is more than one streaming quality available, check to see if filtering is required
if (parser.streams.length > 1)
{
//Checks to see if there are min/max bitrate restrictions then throws out the outliers
if(HLSManifestParser.MAX_BITRATE != -1 && curStream.bandwidth > HLSManifestParser.MAX_BITRATE ||
HLSManifestParser.MIN_BITRATE != -1 && curStream.bandwidth < HLSManifestParser.MIN_BITRATE)
{
continue;
}
}
item = new DynamicStreamingItem(curStream.uri, curStream.bandwidth, curStream.width, curStream.height);
curStream.dynamicStream = item;
items.push(item);
if ( !(curStream.manifest ? curStream.manifest.streamEnds : false) ) isDVR = true;
// Create dynamic streaming items for the backup streams
if (!curStream.backupStream)
continue;
var mainStream:HLSManifestStream = curStream;
curStream = curStream.backupStream;
while (curStream != mainStream)
{
curStream.dynamicStream = new DynamicStreamingItem(curStream.uri, curStream.bandwidth, curStream.width, curStream.height);
curStream = curStream.backupStream;
}
}
// Deal with single rate M3Us by stuffing a single stream in.
if(items.length == 0)
{
item = new DynamicStreamingItem(URLResource(loadTrait.resource).url, 0, 0, 0);
items.push(item);
// Also set the DVR state
if ( !stream.manifest.streamEnds ) isDVR = true;
}
var alternateAudioItems:Vector.<StreamingItem> = new <StreamingItem>[];
for ( var j:int = 0; j < parser.playLists.length; j++ )
{
var playList:HLSManifestPlaylist = parser.playLists[ j ];
if ( !playList.manifest ) continue;
var audioItem:StreamingItem = new StreamingItem( StreamingItemType.AUDIO, playList.name, 0, playList );
alternateAudioItems.push( audioItem );
}
stream.streamItems = items;
stream.alternativeAudioStreamItems = alternateAudioItems;
var preferredIndex:int;
//If there is only one stream quality (or less) sets default to first stream
if (items.length <= 1)
{
preferredIndex = 0;
}
else if (HLSManifestParser.PREF_BITRATE != -1)
{
//If there is a preferred bitrate set by kaltura, tests all streams to find highest bitrate below the preferred
preferredIndex = 0;
var preferredDistance:Number = Number.MAX_VALUE;
for(var k:int=0; k<items.length; k++)
{
var curItem:DynamicStreamingItem = items[k];
var curDist:Number = items[k].bitrate - HLSManifestParser.PREF_BITRATE;
/// Reject too low or not improved items.
if(curDist < 0 || curDist >= preferredDistance)
continue;
preferredIndex = k;
preferredDistance = curDist;
}
}
else
{
//Sets the preferred index to the middle (or higher of the 2 middle) bitrate streams
preferredIndex = items.length / 2;
}
stream.initialIndex = preferredIndex;
stream.addMetadataValue( HLSMetadataNamespaces.PLAYABLE_RESOURCE_METADATA, true );
var loadedElem:MediaElement = new HLSVideoElement( stream, new M2TSNetLoader() );
LoadFromDocumentLoadTrait( loadTrait ).mediaElement = loadedElem;
if ( parser.subtitlePlayLists.length > 0 )
{
var subtitleTrait:SubtitleTrait = new SubtitleTrait();
subtitleTrait.playLists = parser.subtitlePlayLists;
subtitleTrait.owningMediaElement = loadedElem;
stream.subtitleTrait = subtitleTrait;
}
if ( isDVR )
{
var dvrMetadata:Metadata = new Metadata();
stream.addMetadataValue(MetadataNamespaces.DVR_METADATA, dvrMetadata);
}
updateLoadTrait( loadTrait, LoadState.READY );
}
private function onError(event:ErrorEvent):void
{
manifestLoader.removeEventListener(Event.COMPLETE, onComplete);
manifestLoader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
manifestLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
updateLoadTrait(loadTrait, LoadState.LOAD_ERROR);
loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(0, event.text)));
}
override public function canHandleResource(resource:MediaResourceBase):Boolean
{
var supported:int = MediaTypeUtil.checkMetadataMatchWithResource(resource, new Vector.<String>(), supportedMimeTypes);
if ( supported == MediaTypeUtil.METADATA_MATCH_FOUND )
return true;
if (!(resource is URLResource))
return false;
var url:URL = new URL((resource as URLResource).url);
if (url.extension != "m3u8" && url.extension != "m3u")
return false;
return true;
}
}
}
|
package com.kaltura.hls
{
import com.kaltura.hls.m2ts.M2TSNetLoader;
import com.kaltura.hls.manifest.HLSManifestParser;
import com.kaltura.hls.manifest.HLSManifestPlaylist;
import com.kaltura.hls.manifest.HLSManifestStream;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import org.osmf.elements.VideoElement;
import org.osmf.elements.proxyClasses.LoadFromDocumentLoadTrait;
import org.osmf.events.MediaError;
import org.osmf.events.MediaErrorEvent;
import org.osmf.media.DefaultMediaFactory;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.MediaTypeUtil;
import org.osmf.media.URLResource;
import org.osmf.metadata.Metadata;
import org.osmf.metadata.MetadataNamespaces;
import org.osmf.net.DynamicStreamingItem;
import org.osmf.net.StreamType;
import org.osmf.net.StreamingItem;
import org.osmf.net.StreamingItemType;
import org.osmf.traits.LoadState;
import org.osmf.traits.LoadTrait;
import org.osmf.traits.LoaderBase;
import org.osmf.utils.URL;
public class HLSLoader extends LoaderBase
{
protected var loadTrait:LoadTrait;
protected var manifestLoader:URLLoader;
protected var parser:HLSManifestParser;
protected var factory:DefaultMediaFactory = new DefaultMediaFactory();
private var supportedMimeTypes:Vector.<String> = new Vector.<String>();
public function HLSLoader()
{
super();
supportedMimeTypes.push( "application/x-mpegURL" );
supportedMimeTypes.push( "application/vnd.apple.mpegURL" );
supportedMimeTypes.push( "vnd.apple.mpegURL" );
supportedMimeTypes.push( "video/MP2T" );
}
override protected function executeLoad(loadTrait:LoadTrait):void
{
this.loadTrait = loadTrait;
updateLoadTrait(loadTrait, LoadState.LOADING);
var url:String = URLResource(loadTrait.resource).url;
manifestLoader = new URLLoader(new URLRequest(url));
manifestLoader.addEventListener(Event.COMPLETE, onComplete);
manifestLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
manifestLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
private function onComplete(event:Event):void
{
manifestLoader.removeEventListener(Event.COMPLETE, onComplete);
manifestLoader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
manifestLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
try {
var resourceData:String = String((event.target as URLLoader).data);
var url:String = URLResource(loadTrait.resource).url;
// Start parsing the manifest.
parser = new HLSManifestParser();
parser.addEventListener(Event.COMPLETE, onManifestComplete);
parser.parse(resourceData, url);
}
catch (parseError:Error)
{
updateLoadTrait(loadTrait, LoadState.LOAD_ERROR);
loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(parseError.errorID, parseError.message)));
}
}
protected function onManifestComplete(event:Event):void
{
trace("Manifest is loaded.");
var isDVR:Boolean = false;
// Construct the streaming resource and set it as our resource.
var stream:HLSStreamingResource = new HLSStreamingResource(URLResource(loadTrait.resource).url, "", StreamType.DVR);
stream.manifest = parser;
var item:DynamicStreamingItem;
var items:Vector.<DynamicStreamingItem> = new Vector.<DynamicStreamingItem>();
for(var i:int=0; i<parser.streams.length; i++)
{
var curStream:HLSManifestStream = parser.streams[i];
//If there is more than one streaming quality available, check to see if filtering is required
if (parser.streams.length > 1)
{
//Checks to see if there are min/max bitrate restrictions then throws out the outliers
if(HLSManifestParser.MAX_BITRATE != -1 && curStream.bandwidth > HLSManifestParser.MAX_BITRATE ||
HLSManifestParser.MIN_BITRATE != -1 && curStream.bandwidth < HLSManifestParser.MIN_BITRATE)
{
continue;
}
}
item = new DynamicStreamingItem(curStream.uri, curStream.bandwidth, curStream.width, curStream.height);
curStream.dynamicStream = item;
items.push(item);
if ( !(curStream.manifest ? curStream.manifest.streamEnds : false) ) isDVR = true;
// Create dynamic streaming items for the backup streams
if (!curStream.backupStream)
continue;
var mainStream:HLSManifestStream = curStream;
curStream = curStream.backupStream;
while (curStream != mainStream)
{
curStream.dynamicStream = new DynamicStreamingItem(curStream.uri, curStream.bandwidth, curStream.width, curStream.height);
curStream = curStream.backupStream;
}
}
// Deal with single rate M3Us by stuffing a single stream in.
if(items.length == 0)
{
item = new DynamicStreamingItem(URLResource(loadTrait.resource).url, 0, 0, 0);
items.push(item);
// Also set the DVR state
if ( !stream.manifest.streamEnds ) isDVR = true;
}
var alternateAudioItems:Vector.<StreamingItem> = new <StreamingItem>[];
for ( var j:int = 0; j < parser.playLists.length; j++ )
{
var playList:HLSManifestPlaylist = parser.playLists[ j ];
if ( !playList.manifest ) continue;
var audioItem:StreamingItem = new StreamingItem( StreamingItemType.AUDIO, playList.name, 0, playList );
alternateAudioItems.push( audioItem );
}
stream.streamItems = items;
stream.alternativeAudioStreamItems = alternateAudioItems;
var preferredIndex:int;
//If there is only one stream quality (or less) sets default to first stream
if (items.length <= 1)
{
preferredIndex = 0;
}
else if (HLSManifestParser.PREF_BITRATE != -1)
{
//If there is a preferred bitrate set by kaltura, tests all streams to find highest bitrate below the preferred
preferredIndex = 0;
var preferredDistance:Number = Number.MAX_VALUE;
for(var k:int=0; k<items.length; k++)
{
var curItem:DynamicStreamingItem = items[k];
var curDist:Number = Math.abs(items[k].bitrate - HLSManifestParser.PREF_BITRATE);
/// Reject too low or not improved items.
if(curDist < 0 || curDist >= preferredDistance)
continue;
preferredIndex = k;
preferredDistance = curDist;
}
}
else
{
//Sets the preferred index to the middle (or higher of the 2 middle) bitrate streams
preferredIndex = items.length / 2;
}
stream.initialIndex = preferredIndex;
stream.addMetadataValue( HLSMetadataNamespaces.PLAYABLE_RESOURCE_METADATA, true );
var loadedElem:MediaElement = new HLSVideoElement( stream, new M2TSNetLoader() );
LoadFromDocumentLoadTrait( loadTrait ).mediaElement = loadedElem;
if ( parser.subtitlePlayLists.length > 0 )
{
var subtitleTrait:SubtitleTrait = new SubtitleTrait();
subtitleTrait.playLists = parser.subtitlePlayLists;
subtitleTrait.owningMediaElement = loadedElem;
stream.subtitleTrait = subtitleTrait;
}
if ( isDVR )
{
var dvrMetadata:Metadata = new Metadata();
stream.addMetadataValue(MetadataNamespaces.DVR_METADATA, dvrMetadata);
}
updateLoadTrait( loadTrait, LoadState.READY );
}
private function onError(event:ErrorEvent):void
{
manifestLoader.removeEventListener(Event.COMPLETE, onComplete);
manifestLoader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
manifestLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
updateLoadTrait(loadTrait, LoadState.LOAD_ERROR);
loadTrait.dispatchEvent(new MediaErrorEvent(MediaErrorEvent.MEDIA_ERROR, false, false, new MediaError(0, event.text)));
}
override public function canHandleResource(resource:MediaResourceBase):Boolean
{
var supported:int = MediaTypeUtil.checkMetadataMatchWithResource(resource, new Vector.<String>(), supportedMimeTypes);
if ( supported == MediaTypeUtil.METADATA_MATCH_FOUND )
return true;
if (!(resource is URLResource))
return false;
var url:URL = new URL((resource as URLResource).url);
if (url.extension != "m3u8" && url.extension != "m3u")
return false;
return true;
}
}
}
|
Correct preferred bitrate selection logic to use abs.
|
Correct preferred bitrate selection logic to use abs.
|
ActionScript
|
agpl-3.0
|
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
|
8dacf72454e89461a444d6cc9fa02ba1db95ecbd
|
src/org/swiftsuspenders/typedescriptions/ConstructorInjectionPoint.as
|
src/org/swiftsuspenders/typedescriptions/ConstructorInjectionPoint.as
|
/*
* Copyright (c) 2012 the original author or authors
*
* Permission is hereby granted to use, modify, and distribute this file
* in accordance with the terms of the license agreement accompanying it.
*/
package org.swiftsuspenders.typedescriptions
{
import flash.utils.Dictionary;
import org.swiftsuspenders.Injector;
public class ConstructorInjectionPoint extends MethodInjectionPoint
{
//---------------------- Public Methods ----------------------//
public function ConstructorInjectionPoint(parameters : Array, requiredParameters : uint,
injectParameters : Dictionary)
{
super('ctor', parameters, requiredParameters, false, injectParameters);
}
public function createInstance(type : Class, injector : Injector) : Object
{
var p : Array = gatherParameterValues(type, type, injector);
var result : Object;
//the only way to implement ctor injections, really!
switch (p.length)
{
case 1 : result = new type(p[0]); break;
case 2 : result = new type(p[0], p[1]); break;
case 3 : result = new type(p[0], p[1], p[2]); break;
case 4 : result = new type(p[0], p[1], p[2], p[3]); break;
case 5 : result = new type(p[0], p[1], p[2], p[3], p[4]); break;
case 6 : result = new type(p[0], p[1], p[2], p[3], p[4], p[5]); break;
case 7 : result = new type(p[0], p[1], p[2], p[3], p[4], p[5], p[6]); break;
case 8 : result = new type(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]); break;
case 9 : result = new type(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]); break;
case 10 : result = new type(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9]); break;
}
p.length = 0;
return result;
}
}
}
|
/*
* Copyright (c) 2012 the original author or authors
*
* Permission is hereby granted to use, modify, and distribute this file
* in accordance with the terms of the license agreement accompanying it.
*/
package org.swiftsuspenders.typedescriptions
{
import flash.utils.Dictionary;
import org.swiftsuspenders.Injector;
public class ConstructorInjectionPoint extends MethodInjectionPoint
{
//---------------------- Public Methods ----------------------//
public function ConstructorInjectionPoint(parameters : Array, requiredParameters : uint,
injectParameters : Dictionary)
{
super('ctor', parameters, requiredParameters, false, injectParameters);
}
public function createInstance(type : Class, injector : Injector) : Object
{
var p : Array = gatherParameterValues(type, type, injector);
var result : Object;
//the only way to implement ctor injections, really!
switch (p.length)
{
case 1 : result = new type(p[0]); break;
case 2 : result = new type(p[0], p[1]); break;
case 3 : result = new type(p[0], p[1], p[2]); break;
case 4 : result = new type(p[0], p[1], p[2], p[3]); break;
case 5 : result = new type(p[0], p[1], p[2], p[3], p[4]); break;
case 6 : result = new type(p[0], p[1], p[2], p[3], p[4], p[5]); break;
case 7 : result = new type(p[0], p[1], p[2], p[3], p[4], p[5], p[6]); break;
case 8 : result = new type(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]); break;
case 9 : result = new type(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]); break;
case 10 : result = new type(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9]); break;
default: throw new Error("The constructor for " + type + " has too many arguments, maximum is 10");
}
p.length = 0;
return result;
}
}
}
|
Throw an exception if the class couldn't be instantiated.
|
Throw an exception if the class couldn't be instantiated.
|
ActionScript
|
mit
|
tschneidereit/SwiftSuspenders,rshiue/swiftsuspenders,LordXaoca/SwiftSuspenders,robotlegs/swiftsuspenders,rshiue/swiftsuspenders,robotlegs/swiftsuspenders,tschneidereit/SwiftSuspenders,LordXaoca/SwiftSuspenders
|
287af772c3ca0809a6f87fba2edc3d2225fd48a6
|
as3FlexClient/src/com/kaltura/delegates/WebDelegateBase.as
|
as3FlexClient/src/com/kaltura/delegates/WebDelegateBase.as
|
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {
import com.kaltura.KalturaClient;
import com.kaltura.config.IKalturaConfig;
import com.kaltura.config.KalturaConfig;
import com.kaltura.core.KClassFactory;
import com.kaltura.encryption.MD5;
import com.kaltura.errors.KalturaError;
import com.kaltura.events.KalturaEvent;
import com.kaltura.net.KalturaCall;
import com.kaltura.types.KalturaResponseType;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {
public static var CONNECT_TIME:int = 60000; //60 secs
public static var LOAD_TIME:int = 120000; //120 secs
protected var connectTimer:Timer;
protected var loadTimer:Timer;
protected var _call:KalturaCall;
protected var _config:KalturaConfig;
protected var loader:URLLoader;
protected var fileRef:FileReference;
//Setters & getters
public function get call():KalturaCall {
return _call;
}
public function set call(newVal:KalturaCall):void {
_call = newVal;
}
public function get config():IKalturaConfig {
return _config;
}
public function set config(newVal:IKalturaConfig):void {
_config = newVal as KalturaConfig;
}
public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
this.call = call;
this.config = config;
if (!call)
return; //maybe a multi request
if (call.useTimeout) {
connectTimer = new Timer(CONNECT_TIME, 1);
connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);
loadTimer = new Timer(LOAD_TIME, 1);
loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
}
execute();
}
public function close():void {
try {
loader.close();
}
catch (e:*) {
}
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
}
protected function onConnectTimeout(event:TimerEvent):void {
var kError:KalturaError = new KalturaError();
kError.errorCode = "CONNECTION_TIMEOUT";
kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
loadTimer.stop();
close();
}
protected function onLoadTimeOut(event:TimerEvent):void {
connectTimer.stop();
close();
var kError:KalturaError = new KalturaError();
kError.errorCode = "POST_TIMEOUT";
kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
protected function execute():void {
if (call == null) {
throw new Error('No call defined.');
}
post(); //post the call
}
/**
* Helper function for sending the call straight to the server
*/
protected function post():void {
addOptionalArguments();
formatRequest();
sendRequest();
if (call.useTimeout) {
connectTimer.start();
}
}
protected function formatRequest():void {
//The configuration is stronger then the args
if (_config.partnerId != null && _call.args["partnerId"] == -1)
_call.setRequestArgument("partnerId", _config.partnerId);
if (_config.ks != null)
_call.setRequestArgument("ks", _config.ks);
if (_config.clientTag != null)
_call.setRequestArgument("clientTag", _config.clientTag);
_call.setRequestArgument("ignoreNull", _config.ignoreNull);
_call.setRequestArgument("apiVersion", KalturaClient.API_VERSION);
_call.setRequestArgument("format", KalturaResponseType.RESPONSE_TYPE_XML);
//Create signature hash.
//call.setRequestArgument("kalsig", getMD5Checksum(call));
}
protected function getMD5Checksum(call:KalturaCall):String {
var props:Array = new Array();
for (var arg:String in call.args)
props.push(arg);
props.sort();
var s:String = "";
for each (var prop:String in props) {
if ( call.args[prop] )
s += prop + call.args[prop];
}
return MD5.encrypt(s);
}
protected function sendRequest():void {
//construct the loader
createURLLoader();
//Create signature hash.
var kalsig:String = getMD5Checksum(call);
//create the service request for normal calls
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;
if (_call.method == URLRequestMethod.GET)
url += "&";
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
req.data = call.args;
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(req);
}
protected function createURLLoader():void {
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onDataComplete);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.addEventListener(Event.OPEN, onOpen);
}
protected function onHTTPStatus(event:HTTPStatusEvent):void {
}
protected function onOpen(event:Event):void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.start();
}
}
protected function addOptionalArguments():void {
//add optional args here
}
// Event Handlers
/**
* try to process received data.
* if procesing failed, let call handle the processing error
* @param event load complete event
*/
protected function onDataComplete(event:Event):void {
try {
handleResult(XML(event.target.data));
}
catch (e:Error) {
var kErr:KalturaError = new KalturaError();
kErr.errorCode = String(e.errorID);
kErr.errorMsg = e.message;
_call.handleError(kErr);
}
}
/**
* handle io or security error events from the loader.
* create relevant KalturaError, let the call process it.
* @param event
*/
protected function onError(event:ErrorEvent):void {
clean();
var kError:KalturaError = createKalturaError(event, loader.data);
if (!kError) {
kError = new KalturaError();
kError.errorMsg = event.text;
//kError.errorCode;
}
call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
/**
* parse the server's response and let the call process it.
* @param result server's response
*/
protected function handleResult(result:XML):void {
clean();
var error:KalturaError = validateKalturaResponse(result);
if (error == null) {
var digestedResult:Object = parse(result);
call.handleResult(digestedResult);
}
else {
call.handleError(error);
}
}
/**
* stop timers and clean event listeners
*/
protected function clean():void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
if (loader == null) {
return;
}
loader.removeEventListener(Event.COMPLETE, onDataComplete);
loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.removeEventListener(Event.OPEN, onOpen);
}
/**
* create the correct object and populate it with the given values. if the needed class is not found
* in the file, a generic object is created with attributes matching the XML attributes.
* Override this parssing function in the specific delegate to create the correct object.
* @param result instance attributes
* @return an instance of the class declared by the given XML.
* */
public function parse(result:XML):* {
//by defualt create the response object
var cls:Class;
try {
cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
}
catch (e:Error) {
cls = Object;
}
var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
return obj;
}
/**
* If the result string holds an error, return a KalturaError object with
* relevant values. <br/>
* Overide this to create validation object and fill it.
* @param result the string returned from the server.
* @return matching error object
*/
protected function validateKalturaResponse(result:String):KalturaError {
var kError:KalturaError = null;
var xml:XML = XML(result);
if (xml.result.hasOwnProperty('error')
&& xml.result.error.hasOwnProperty('code')
&& xml.result.error.hasOwnProperty('message')) {
kError = new KalturaError();
kError.errorCode = String(xml.result.error.code);
kError.errorMsg = xml.result.error.message;
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
return kError;
}
/**
* create error object and fill it with relevant details
* @param event
* @param loaderData
* @return detailed KalturaError to be processed
*/
protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
var ke:KalturaError = new KalturaError();
ke.errorMsg = event.text;
return ke;
}
/**
* create the url that is used for serve actions
* @param call the KalturaCall that defines the required parameters
* @return URLRequest with relevant parameters
* */
public function getServeUrl(call:KalturaCall):URLRequest {
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
for (var key:String in call.args) {
url += "&" + key + "=" + call.args[key];
}
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
// req.data = call.args;
return req;
}
}
}
|
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {
import com.kaltura.KalturaClient;
import com.kaltura.config.IKalturaConfig;
import com.kaltura.config.KalturaConfig;
import com.kaltura.core.KClassFactory;
import com.kaltura.encryption.MD5;
import com.kaltura.errors.KalturaError;
import com.kaltura.events.KalturaEvent;
import com.kaltura.net.KalturaCall;
import com.kaltura.types.KalturaResponseType;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {
public static var CONNECT_TIME:int = 60000; //60 secs
public static var LOAD_TIME:int = 120000; //120 secs
protected var connectTimer:Timer;
protected var loadTimer:Timer;
protected var _call:KalturaCall;
protected var _config:KalturaConfig;
protected var loader:URLLoader;
protected var fileRef:FileReference;
//Setters & getters
public function get call():KalturaCall {
return _call;
}
public function set call(newVal:KalturaCall):void {
_call = newVal;
}
public function get config():IKalturaConfig {
return _config;
}
public function set config(newVal:IKalturaConfig):void {
_config = newVal as KalturaConfig;
}
public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
this.call = call;
this.config = config;
if (!call)
return; //maybe a multi request
if (call.useTimeout) {
connectTimer = new Timer(CONNECT_TIME, 1);
connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);
loadTimer = new Timer(LOAD_TIME, 1);
loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
}
execute();
}
public function close():void {
try {
loader.close();
}
catch (e:*) {
}
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
}
protected function onConnectTimeout(event:TimerEvent):void {
var kError:KalturaError = new KalturaError();
kError.errorCode = "CONNECTION_TIMEOUT";
kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
loadTimer.stop();
close();
}
protected function onLoadTimeOut(event:TimerEvent):void {
connectTimer.stop();
close();
var kError:KalturaError = new KalturaError();
kError.errorCode = "POST_TIMEOUT";
kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
protected function execute():void {
if (call == null) {
throw new Error('No call defined.');
}
post(); //post the call
}
/**
* Helper function for sending the call straight to the server
*/
protected function post():void {
addOptionalArguments();
formatRequest();
sendRequest();
if (call.useTimeout) {
connectTimer.start();
}
}
protected function formatRequest():void {
//The configuration is stronger then the args
if (_config.partnerId != null && _call.args["partnerId"] == -1)
_call.setRequestArgument("partnerId", _config.partnerId);
if (_config.ks != null)
_call.setRequestArgument("ks", _config.ks);
if (_config.clientTag != null)
_call.setRequestArgument("clientTag", _config.clientTag);
_call.setRequestArgument("ignoreNull", _config.ignoreNull);
_call.setRequestArgument("apiVersion", KalturaClient.API_VERSION);
//_call.setRequestArgument("format", KalturaResponseType.RESPONSE_TYPE_XML);
//Create signature hash.
//call.setRequestArgument("kalsig", getMD5Checksum(call));
}
protected function getMD5Checksum(call:KalturaCall):String {
var props:Array = new Array();
for (var arg:String in call.args)
props.push(arg);
props.sort();
var s:String = "";
for each (var prop:String in props) {
if ( call.args[prop] )
s += prop + call.args[prop];
}
return MD5.encrypt(s);
}
protected function sendRequest():void {
//construct the loader
createURLLoader();
//Create signature hash.
var kalsig:String = getMD5Checksum(call);
//create the service request for normal calls
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;
if (_call.method == URLRequestMethod.GET)
url += "&";
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
req.data = call.args;
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(req);
}
protected function createURLLoader():void {
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onDataComplete);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.addEventListener(Event.OPEN, onOpen);
}
protected function onHTTPStatus(event:HTTPStatusEvent):void {
}
protected function onOpen(event:Event):void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.start();
}
}
protected function addOptionalArguments():void {
//add optional args here
}
// Event Handlers
/**
* try to process received data.
* if procesing failed, let call handle the processing error
* @param event load complete event
*/
protected function onDataComplete(event:Event):void {
try {
handleResult(XML(event.target.data));
}
catch (e:Error) {
var kErr:KalturaError = new KalturaError();
kErr.errorCode = String(e.errorID);
kErr.errorMsg = e.message;
_call.handleError(kErr);
}
}
/**
* handle io or security error events from the loader.
* create relevant KalturaError, let the call process it.
* @param event
*/
protected function onError(event:ErrorEvent):void {
clean();
var kError:KalturaError = createKalturaError(event, loader.data);
if (!kError) {
kError = new KalturaError();
kError.errorMsg = event.text;
//kError.errorCode;
}
call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
/**
* parse the server's response and let the call process it.
* @param result server's response
*/
protected function handleResult(result:XML):void {
clean();
var error:KalturaError = validateKalturaResponse(result);
if (error == null) {
var digestedResult:Object = parse(result);
call.handleResult(digestedResult);
}
else {
call.handleError(error);
}
}
/**
* stop timers and clean event listeners
*/
protected function clean():void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
if (loader == null) {
return;
}
loader.removeEventListener(Event.COMPLETE, onDataComplete);
loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.removeEventListener(Event.OPEN, onOpen);
}
/**
* create the correct object and populate it with the given values. if the needed class is not found
* in the file, a generic object is created with attributes matching the XML attributes.
* Override this parssing function in the specific delegate to create the correct object.
* @param result instance attributes
* @return an instance of the class declared by the given XML.
* */
public function parse(result:XML):* {
//by defualt create the response object
var cls:Class;
try {
cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
}
catch (e:Error) {
cls = Object;
}
var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
return obj;
}
/**
* If the result string holds an error, return a KalturaError object with
* relevant values. <br/>
* Overide this to create validation object and fill it.
* @param result the string returned from the server.
* @return matching error object
*/
protected function validateKalturaResponse(result:String):KalturaError {
var kError:KalturaError = null;
var xml:XML = XML(result);
if (xml.result.hasOwnProperty('error')
&& xml.result.error.hasOwnProperty('code')
&& xml.result.error.hasOwnProperty('message')) {
kError = new KalturaError();
kError.errorCode = String(xml.result.error.code);
kError.errorMsg = xml.result.error.message;
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
return kError;
}
/**
* create error object and fill it with relevant details
* @param event
* @param loaderData
* @return detailed KalturaError to be processed
*/
protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
var ke:KalturaError = new KalturaError();
ke.errorMsg = event.text;
return ke;
}
/**
* create the url that is used for serve actions
* @param call the KalturaCall that defines the required parameters
* @return URLRequest with relevant parameters
* */
public function getServeUrl(call:KalturaCall):URLRequest {
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
for (var key:String in call.args) {
url += "&" + key + "=" + call.args[key];
}
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
// req.data = call.args;
return req;
}
}
}
|
remove "format" from kalsig calculation
|
remove "format" from kalsig calculation
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp
|
f8d52f790e6d87cec43ad851b66fe958637ef38f
|
plugins/wvPlugin/src/widevinePluginCode.as
|
plugins/wvPlugin/src/widevinePluginCode.as
|
package
{
import com.kaltura.kdpfl.model.LayoutProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.plugin.IPlugin;
import com.kaltura.kdpfl.plugin.KPluginEvent;
import com.kaltura.kdpfl.plugin.WVPluginInfo;
import flash.display.Sprite;
import org.osmf.events.MediaFactoryEvent;
import org.osmf.media.DefaultMediaFactory;
import org.osmf.media.PluginInfoResource;
import org.puremvc.as3.interfaces.IFacade;
public dynamic class widevinePluginCode extends Sprite implements IPlugin
{
protected var _localMediaFactory : DefaultMediaFactory;
//Alerts texts, can be overriden from uiconf XML or flashvars.
public var alert_title:String = "Error";
public var warning_title:String = "Warning";
public var alert_emm_falied:String = "We're sorry, you don’t have a license to play this video.";
public var alert_emm_error:String = "We're sorry, we failed to obtain a license for playing this video.";
public var alert_emm_expired:String = "We're sorry, the license to play this video has expired.";
public var alert_log_error:String = "Message Logging Error (error code: {0})";
public var alert_dcp_stop:String = "Playback is stopping due to detection of an illegal content copying attempt.";
public var alert_dcp_alert:String = "An illegal attempt for content copying was detected.";
public var alert_missing_plugin:String = "Widevine Video Optimizer plugin is needed for enabling video playback in this player.";
public function widevinePluginCode()
{
trace('Widevine plugin v3');
super();
}
public function initializePlugin(facade:IFacade):void
{
_localMediaFactory = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.mediaFactory;
var wvPluginInfo:WVPluginInfo = new WVPluginInfo();
var lp:LayoutProxy = (facade.retrieveProxy(LayoutProxy.NAME) as LayoutProxy);
for each( var i:Object in lp.components)
{
if(i.hasOwnProperty("className") && i.className == "KMediaPlayer" )
{
trace(i.ui.width,i.ui.height );
WVPluginInfo.mediaWidth = i.ui.width;
WVPluginInfo.mediaHeight = i.ui.height;
break;
}
}
_localMediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD, onOSMFPluginLoaded);
_localMediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD_ERROR, onOSMFPluginLoadError);
_localMediaFactory.loadPlugin(new PluginInfoResource(wvPluginInfo) );
var wvm:WvMediator = new WvMediator(this, wvPluginInfo);
facade.registerMediator(wvm);
}
/**
* Listener for the LOAD_COMPLETE event.
* @param e - MediaFactoryEvent
*
*/
protected function onOSMFPluginLoaded (e : MediaFactoryEvent) : void
{
_localMediaFactory.removeEventListener(MediaFactoryEvent.PLUGIN_LOAD, onOSMFPluginLoaded);
dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_COMPLETE) );
}
/**
* Listener for the LOAD_ERROR event.
* @param e - MediaFactoryEvent
*
*/
protected function onOSMFPluginLoadError (e : MediaFactoryEvent) : void
{
_localMediaFactory.removeEventListener(MediaFactoryEvent.PLUGIN_LOAD_ERROR, onOSMFPluginLoadError);
dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_FAILED) );
}
public function setSkin(styleName:String, setSkinSize:Boolean=false):void
{
}
}
}
|
package
{
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.LayoutProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.plugin.IPlugin;
import com.kaltura.kdpfl.plugin.KPluginEvent;
import com.kaltura.kdpfl.plugin.WVPluginInfo;
import flash.display.Sprite;
import org.osmf.events.MediaFactoryEvent;
import org.osmf.media.DefaultMediaFactory;
import org.osmf.media.PluginInfoResource;
import org.puremvc.as3.interfaces.IFacade;
public dynamic class widevinePluginCode extends Sprite implements IPlugin
{
protected var _localMediaFactory : DefaultMediaFactory;
//Alerts texts, can be overriden from uiconf XML or flashvars.
public var alert_title:String = "Error";
public var warning_title:String = "Warning";
public var alert_emm_falied:String = "We're sorry, you don’t have a valid license for this video.";
public var alert_emm_error:String = "We're sorry, a license request for this video failed.";
public var alert_emm_expired:String = "We're sorry, you don’t have a valid license for this video.";
public var alert_log_error:String = "Message logging failed (error code: {0})";
public var alert_dcp_stop:String = "Playback stopped due to the detection of copying attempt.";
public var alert_dcp_alert:String = "A copying attempt was detected.";
public var alert_missing_plugin:String = "Widevine Video Optimizer plugin is needed for enabling video playback in this player.";
public var flavorTags:String;
public function widevinePluginCode()
{
trace('Widevine plugin v3');
super();
}
public function initializePlugin(facade:IFacade):void
{
_localMediaFactory = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.mediaFactory;
var wvPluginInfo:WVPluginInfo = new WVPluginInfo();
var lp:LayoutProxy = (facade.retrieveProxy(LayoutProxy.NAME) as LayoutProxy);
for each( var i:Object in lp.components)
{
if(i.hasOwnProperty("className") && i.className == "KMediaPlayer" )
{
trace(i.ui.width,i.ui.height );
WVPluginInfo.mediaWidth = i.ui.width;
WVPluginInfo.mediaHeight = i.ui.height;
break;
}
}
_localMediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD, onOSMFPluginLoaded);
_localMediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD_ERROR, onOSMFPluginLoadError);
_localMediaFactory.loadPlugin(new PluginInfoResource(wvPluginInfo) );
var wvm:WvMediator = new WvMediator(this, wvPluginInfo);
facade.registerMediator(wvm);
if (flavorTags)
{
(facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy).vo.flashvars.flavorTags = flavorTags;
}
}
/**
* Listener for the LOAD_COMPLETE event.
* @param e - MediaFactoryEvent
*
*/
protected function onOSMFPluginLoaded (e : MediaFactoryEvent) : void
{
_localMediaFactory.removeEventListener(MediaFactoryEvent.PLUGIN_LOAD, onOSMFPluginLoaded);
dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_COMPLETE) );
}
/**
* Listener for the LOAD_ERROR event.
* @param e - MediaFactoryEvent
*
*/
protected function onOSMFPluginLoadError (e : MediaFactoryEvent) : void
{
_localMediaFactory.removeEventListener(MediaFactoryEvent.PLUGIN_LOAD_ERROR, onOSMFPluginLoadError);
dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_FAILED) );
}
public function setSkin(styleName:String, setSkinSize:Boolean=false):void
{
}
}
}
|
fix tests, support flavor tags
|
widevine: fix tests, support flavor tags
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp
|
14f35757cd516fce49c66099c40542d92a3426f5
|
bin/Data/Scripts/Editor/EditorViewDebugIcons.as
|
bin/Data/Scripts/Editor/EditorViewDebugIcons.as
|
// Editor debug icons
// to add new std debug icons just add IconType, IconsTypesMaterials and ComponentTypes items
enum IconsTypes
{
ICON_POINT_LIGHT = 0,
ICON_SPOT_LIGHT,
ICON_DIRECTIONAL_LIGHT,
ICON_CAMERA,
ICON_SOUND_SOURCE,
ICON_SOUND_SOURCE_3D,
ICON_SOUND_LISTENERS,
ICON_ZONE,
ICON_SPLINE_PATH,
ICON_TRIGGER,
ICON_CUSTOM_GEOMETRY,
ICON_PARTICLE_EMITTER,
ICON_COUNT
}
enum IconsColorType
{
ICON_COLOR_DEFAULT = 0,
ICON_COLOR_SPLINE_PATH_BEGIN,
ICON_COLOR_SPLINE_PATH_END
}
Array<Color> debugIconsColors = { Color(1,1,1) , Color(1,1,0), Color(0,1,0) };
Array<String> IconsTypesMaterials = {"DebugIconPointLight.xml",
"DebugIconSpotLight.xml",
"DebugIconLight.xml",
"DebugIconCamera.xml",
"DebugIconSoundSource.xml",
"DebugIconSoundSource.xml",
"DebugIconSoundListener.xml",
"DebugIconZone.xml",
"DebugIconSplinePathPoint.xml",
"DebugIconCollisionTrigger.xml",
"DebugIconCustomGeometry.xml",
"DebugIconParticleEmitter.xml"};
Array<String> ComponentTypes = {"Light",
"Light",
"Light",
"Camera",
"SoundSource",
"SoundSource3D",
"SoundListener",
"Zone",
"SplinePath",
"RigidBody",
"CustomGeometry",
"ParticleEmitter"};
Array<BillboardSet@> debugIconsSet(ICON_COUNT);
Node@ debugIconsNode = null;
int stepDebugIconsUpdate = 100; //ms
int timeToNextDebugIconsUpdate = 0;
int stepDebugIconsUpdateSplinePath = 1000; //ms
int timeToNextDebugIconsUpdateSplinePath = 0;
const int splinePathResolution = 16;
const float splineStep = 1.0f / splinePathResolution;
bool debugIconsShow = true;
Vector2 debugIconsSize = Vector2(0.025, 0.025);
Vector2 debugIconsSizeSmall = debugIconsSize / 1.5;
Vector2 debugIconsSizeBig = debugIconsSize * 1.5;
Vector2 debugIconsMaxSize = debugIconsSize * 50;
VariantMap debugIconsPlacement;
const int debugIconsPlacementIndent = 1.0;
const float debugIconsOrthoDistance = 15.0f;
Vector2 Max(Vector2 a, Vector2 b)
{
return (a.length > b.length ? a : b);
}
Vector2 Clamp(Vector2 a, Vector2 b)
{
return Vector2((a.x > b.x ? b.x : a.x),(a.y > b.y ? b.y : a.y));
}
Vector2 ClampToIconMaxSize(Vector2 a)
{
return Clamp(a, debugIconsMaxSize);
}
void CreateDebugIcons(Node@ tempNode)
{
if (editorScene is null) return;
debugIconsSet.Resize(ICON_COUNT);
for (int i = 0; i < ICON_COUNT; i++)
{
debugIconsSet[i] = tempNode.CreateComponent("BillboardSet");
debugIconsSet[i].material = cache.GetResource("Material", "Materials/Editor/" + IconsTypesMaterials[i]);
debugIconsSet[i].sorted = true;
debugIconsSet[i].temporary = true;
debugIconsSet[i].viewMask = 0x80000000;
}
}
void UpdateViewDebugIcons()
{
if (editorScene is null || timeToNextDebugIconsUpdate > time.systemTime) return;
debugIconsNode = editorScene.GetChild("DebugIconsContainer", true);
if (debugIconsNode is null)
{
debugIconsNode = editorScene.CreateChild("DebugIconsContainer", LOCAL);
debugIconsNode.temporary = true;
}
// Checkout if debugIconsNode do not have any BBS component, add all at once
BillboardSet@ isBSExist = debugIconsNode.GetComponent("BillboardSet");
if (isBSExist is null) CreateDebugIcons(debugIconsNode);
if (debugIconsSet[ICON_POINT_LIGHT] !is null)
{
for(int i=0; i < ICON_COUNT; i++)
debugIconsSet[i].enabled = debugIconsShow;
}
if (debugIconsShow == false) return;
Vector3 camPos = activeViewport.cameraNode.worldPosition;
bool isOrthographic = activeViewport.camera.orthographic;
debugIconsPlacement.Clear();
for(int iconType=0; iconType<ICON_COUNT; iconType++)
{
if(debugIconsSet[iconType] !is null)
{
// SplinePath update resolution
if(iconType == ICON_SPLINE_PATH && timeToNextDebugIconsUpdateSplinePath > time.systemTime) continue;
Array<Node@> nodes = editorScene.GetChildrenWithComponent(ComponentTypes[iconType], true);
// Clear old data
if(iconType == ICON_SPLINE_PATH)
ClearCommit(ICON_SPLINE_PATH, ICON_SPLINE_PATH+1, nodes.length * splinePathResolution);
else
ClearCommit(iconType, iconType+1, nodes.length);
if(nodes.length > 0)
{
// Fill with new data
for(int i=0;i<nodes.length; i++)
{
Component@ component = nodes[i].GetComponent(ComponentTypes[iconType]);
if (component is null) continue;
Billboard@ bb = null;
Color finalIconColor = debugIconsColors[ICON_COLOR_DEFAULT];
float distance = (camPos - nodes[i].worldPosition).length;
if (isOrthographic) distance = debugIconsOrthoDistance;
int iconsOffset = debugIconsPlacement[StringHash(nodes[i].id)].GetInt();
float iconsYPos = 0;
if(iconType==ICON_SPLINE_PATH)
{
SplinePath@ sp = cast<SplinePath>(component);
if(sp !is null)
{
for(int step=0; step < splinePathResolution; step++)
{
int index = (i * splinePathResolution) + step;
Vector3 splinePoint = sp.GetPoint(splineStep * step);
Billboard@ bb = debugIconsSet[ICON_SPLINE_PATH].billboards[index];
float stepDistance = (camPos - splinePoint).length;
if (isOrthographic) stepDistance = debugIconsOrthoDistance;
if(step == 0) // SplinePath start
{
bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_BEGIN];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * stepDistance, debugIconsSize));
bb.position = splinePoint;
}
else if((step+1) >= (splinePathResolution - splineStep)) // SplinePath end
{
bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_END];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * stepDistance, debugIconsSize));
bb.position = splinePoint;
}
else // SplinePath middle points
{
bb.color = finalIconColor;
bb.size = ClampToIconMaxSize(Max(debugIconsSizeSmall * stepDistance, debugIconsSizeSmall));
bb.position = splinePoint;
}
bb.enabled = sp.enabled;
// Blend Icon relatively by distance to it
bb.color = Color(bb.color.r, bb.color.g, bb.color.b, 1.2f - 1.0f / (debugIconsMaxSize.x / bb.size.x));
if (bb.color.a < 0.25f) bb.enabled = false;
}
}
}
else
{
bb = debugIconsSet[iconType].billboards[i];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * distance, debugIconsSize));
if(iconType==ICON_PARTICLE_EMITTER)
{
bb.size = ClampToIconMaxSize(Max(debugIconsSizeBig * distance, debugIconsSizeBig));
}
else if (iconType==ICON_TRIGGER)
{
RigidBody@ rigidbody = cast<RigidBody>(component);
if (rigidbody !is null)
{
if (rigidbody.trigger == false) continue;
}
}
else if (iconType==ICON_POINT_LIGHT || iconType==ICON_SPOT_LIGHT || iconType==ICON_DIRECTIONAL_LIGHT)
{
Light@ light = cast<Light>(component);
if(light !is null)
{
if(light.lightType == LIGHT_POINT)
bb = debugIconsSet[ICON_POINT_LIGHT].billboards[i];
else if(light.lightType == LIGHT_DIRECTIONAL)
bb = debugIconsSet[ICON_DIRECTIONAL_LIGHT].billboards[i];
else if(light.lightType == LIGHT_SPOT)
bb = debugIconsSet[ICON_SPOT_LIGHT].billboards[i];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * distance, debugIconsSize));
finalIconColor = light.effectiveColor;
}
}
bb.position = nodes[i].worldPosition;
// Blend Icon relatively by distance to it
bb.color = Color(finalIconColor.r, finalIconColor.g, finalIconColor.b, 1.2f - 1.0f / (debugIconsMaxSize.x / bb.size.x));
bb.enabled = component.enabled;
// Discard billboard if it almost transparent
if (bb.color.a < 0.25f) bb.enabled = false;
IncrementIconPlacement(bb.enabled, nodes[i], 1 );
}
}
Commit(iconType, iconType+1);
// SplinePath update resolution
if(iconType == ICON_SPLINE_PATH) timeToNextDebugIconsUpdateSplinePath = time.systemTime + stepDebugIconsUpdateSplinePath;
}
}
}
timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate;
}
void ClearCommit(int begin, int end, int newlength)
{
for(int i=begin;i<end;i++)
{
debugIconsSet[i].numBillboards = 0;
debugIconsSet[i].Commit();
debugIconsSet[i].numBillboards = newlength;
}
}
void Commit(int begin, int end)
{
for(int i=begin;i<end;i++)
{
debugIconsSet[i].Commit();
}
}
void IncrementIconPlacement(bool componentEnabled, Node@ node, int offset)
{
if(componentEnabled == true)
{
int oldPlacement = debugIconsPlacement[StringHash(node.id)].GetInt();
debugIconsPlacement[StringHash(node.id)] = Variant(oldPlacement + offset);
}
}
|
// Editor debug icons
// to add new std debug icons just add IconType, IconsTypesMaterials and ComponentTypes items
enum IconsTypes
{
ICON_POINT_LIGHT = 0,
ICON_SPOT_LIGHT,
ICON_DIRECTIONAL_LIGHT,
ICON_CAMERA,
ICON_SOUND_SOURCE,
ICON_SOUND_SOURCE_3D,
ICON_SOUND_LISTENERS,
ICON_ZONE,
ICON_SPLINE_PATH,
ICON_TRIGGER,
ICON_CUSTOM_GEOMETRY,
ICON_PARTICLE_EMITTER,
ICON_COUNT
}
enum IconsColorType
{
ICON_COLOR_DEFAULT = 0,
ICON_COLOR_SPLINE_PATH_BEGIN,
ICON_COLOR_SPLINE_PATH_END
}
Array<Color> debugIconsColors = { Color(1,1,1) , Color(1,1,0), Color(0,1,0) };
Array<String> IconsTypesMaterials = {"DebugIconPointLight.xml",
"DebugIconSpotLight.xml",
"DebugIconLight.xml",
"DebugIconCamera.xml",
"DebugIconSoundSource.xml",
"DebugIconSoundSource.xml",
"DebugIconSoundListener.xml",
"DebugIconZone.xml",
"DebugIconSplinePathPoint.xml",
"DebugIconCollisionTrigger.xml",
"DebugIconCustomGeometry.xml",
"DebugIconParticleEmitter.xml"};
Array<String> ComponentTypes = {"Light",
"Light",
"Light",
"Camera",
"SoundSource",
"SoundSource3D",
"SoundListener",
"Zone",
"SplinePath",
"RigidBody",
"CustomGeometry",
"ParticleEmitter"};
Array<BillboardSet@> debugIconsSet(ICON_COUNT);
Node@ debugIconsNode = null;
int stepDebugIconsUpdate = 100; //ms
int timeToNextDebugIconsUpdate = 0;
int stepDebugIconsUpdateSplinePath = 1000; //ms
int timeToNextDebugIconsUpdateSplinePath = 0;
const int splinePathResolution = 16;
const float splineStep = 1.0f / splinePathResolution;
bool debugIconsShow = true;
Vector2 debugIconsSize = Vector2(0.025, 0.025);
Vector2 debugIconsSizeSmall = debugIconsSize / 1.5;
Vector2 debugIconsSizeBig = debugIconsSize * 1.5;
Vector2 debugIconsMaxSize = debugIconsSize * 50;
VariantMap debugIconsPlacement;
const int debugIconsPlacementIndent = 1.0;
const float debugIconsOrthoDistance = 15.0f;
Vector2 Max(Vector2 a, Vector2 b)
{
return (a.length > b.length ? a : b);
}
Vector2 Clamp(Vector2 a, Vector2 b)
{
return Vector2((a.x > b.x ? b.x : a.x),(a.y > b.y ? b.y : a.y));
}
Vector2 ClampToIconMaxSize(Vector2 a)
{
return Clamp(a, debugIconsMaxSize);
}
void CreateDebugIcons(Node@ tempNode)
{
if (editorScene is null) return;
debugIconsSet.Resize(ICON_COUNT);
for (int i = 0; i < ICON_COUNT; i++)
{
debugIconsSet[i] = tempNode.CreateComponent("BillboardSet");
debugIconsSet[i].material = cache.GetResource("Material", "Materials/Editor/" + IconsTypesMaterials[i]);
debugIconsSet[i].sorted = true;
debugIconsSet[i].temporary = true;
debugIconsSet[i].viewMask = 0x80000000;
}
}
void UpdateViewDebugIcons()
{
if (editorScene is null || timeToNextDebugIconsUpdate > time.systemTime) return;
debugIconsNode = editorScene.GetChild("DebugIconsContainer", true);
if (debugIconsNode is null)
{
debugIconsNode = editorScene.CreateChild("DebugIconsContainer", LOCAL);
debugIconsNode.temporary = true;
}
// Checkout if debugIconsNode do not have any BBS component, add all at once
BillboardSet@ isBSExist = debugIconsNode.GetComponent("BillboardSet");
if (isBSExist is null) CreateDebugIcons(debugIconsNode);
if (debugIconsSet[ICON_POINT_LIGHT] !is null)
{
for(int i=0; i < ICON_COUNT; i++)
debugIconsSet[i].enabled = debugIconsShow;
}
if (debugIconsShow == false) return;
Vector3 camPos = activeViewport.cameraNode.worldPosition;
bool isOrthographic = activeViewport.camera.orthographic;
debugIconsPlacement.Clear();
for(int iconType=0; iconType<ICON_COUNT; iconType++)
{
if(debugIconsSet[iconType] !is null)
{
// SplinePath update resolution
if(iconType == ICON_SPLINE_PATH && timeToNextDebugIconsUpdateSplinePath > time.systemTime) continue;
Array<Node@> nodes = editorScene.GetChildrenWithComponent(ComponentTypes[iconType], true);
// Clear old data
if(iconType == ICON_SPLINE_PATH)
ClearCommit(ICON_SPLINE_PATH, ICON_SPLINE_PATH+1, nodes.length * splinePathResolution);
else
ClearCommit(iconType, iconType+1, nodes.length);
if(nodes.length > 0)
{
// Fill with new data
for(int i=0;i<nodes.length; i++)
{
Component@ component = nodes[i].GetComponent(ComponentTypes[iconType]);
if (component is null) continue;
Billboard@ bb = null;
Color finalIconColor = debugIconsColors[ICON_COLOR_DEFAULT];
float distance = (camPos - nodes[i].worldPosition).length;
if (isOrthographic) distance = debugIconsOrthoDistance;
int iconsOffset = debugIconsPlacement[StringHash(nodes[i].id)].GetInt();
float iconsYPos = 0;
if(iconType==ICON_SPLINE_PATH)
{
SplinePath@ sp = cast<SplinePath>(component);
if(sp !is null)
if(sp.length > 0.01f)
{
for(int step=0; step < splinePathResolution; step++)
{
int index = (i * splinePathResolution) + step;
Vector3 splinePoint = sp.GetPoint(splineStep * step);
Billboard@ bb = debugIconsSet[ICON_SPLINE_PATH].billboards[index];
float stepDistance = (camPos - splinePoint).length;
if (isOrthographic) stepDistance = debugIconsOrthoDistance;
if(step == 0) // SplinePath start
{
bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_BEGIN];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * stepDistance, debugIconsSize));
bb.position = splinePoint;
}
else if((step+1) >= (splinePathResolution - splineStep)) // SplinePath end
{
bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_END];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * stepDistance, debugIconsSize));
bb.position = splinePoint;
}
else // SplinePath middle points
{
bb.color = finalIconColor;
bb.size = ClampToIconMaxSize(Max(debugIconsSizeSmall * stepDistance, debugIconsSizeSmall));
bb.position = splinePoint;
}
bb.enabled = sp.enabled;
// Blend Icon relatively by distance to it
bb.color = Color(bb.color.r, bb.color.g, bb.color.b, 1.2f - 1.0f / (debugIconsMaxSize.x / bb.size.x));
if (bb.color.a < 0.25f) bb.enabled = false;
}
}
}
else
{
bb = debugIconsSet[iconType].billboards[i];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * distance, debugIconsSize));
if(iconType==ICON_PARTICLE_EMITTER)
{
bb.size = ClampToIconMaxSize(Max(debugIconsSizeBig * distance, debugIconsSizeBig));
}
else if (iconType==ICON_TRIGGER)
{
RigidBody@ rigidbody = cast<RigidBody>(component);
if (rigidbody !is null)
{
if (rigidbody.trigger == false) continue;
}
}
else if (iconType==ICON_POINT_LIGHT || iconType==ICON_SPOT_LIGHT || iconType==ICON_DIRECTIONAL_LIGHT)
{
Light@ light = cast<Light>(component);
if(light !is null)
{
if(light.lightType == LIGHT_POINT)
bb = debugIconsSet[ICON_POINT_LIGHT].billboards[i];
else if(light.lightType == LIGHT_DIRECTIONAL)
bb = debugIconsSet[ICON_DIRECTIONAL_LIGHT].billboards[i];
else if(light.lightType == LIGHT_SPOT)
bb = debugIconsSet[ICON_SPOT_LIGHT].billboards[i];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * distance, debugIconsSize));
finalIconColor = light.effectiveColor;
}
}
bb.position = nodes[i].worldPosition;
// Blend Icon relatively by distance to it
bb.color = Color(finalIconColor.r, finalIconColor.g, finalIconColor.b, 1.2f - 1.0f / (debugIconsMaxSize.x / bb.size.x));
bb.enabled = component.enabled;
// Discard billboard if it almost transparent
if (bb.color.a < 0.25f) bb.enabled = false;
IncrementIconPlacement(bb.enabled, nodes[i], 1 );
}
}
Commit(iconType, iconType+1);
// SplinePath update resolution
if(iconType == ICON_SPLINE_PATH) timeToNextDebugIconsUpdateSplinePath = time.systemTime + stepDebugIconsUpdateSplinePath;
}
}
}
timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate;
}
void ClearCommit(int begin, int end, int newlength)
{
for(int i=begin;i<end;i++)
{
debugIconsSet[i].numBillboards = 0;
debugIconsSet[i].Commit();
debugIconsSet[i].numBillboards = newlength;
}
}
void Commit(int begin, int end)
{
for(int i=begin;i<end;i++)
{
debugIconsSet[i].Commit();
}
}
void IncrementIconPlacement(bool componentEnabled, Node@ node, int offset)
{
if(componentEnabled == true)
{
int oldPlacement = debugIconsPlacement[StringHash(node.id)].GetInt();
debugIconsPlacement[StringHash(node.id)] = Variant(oldPlacement + offset);
}
}
|
add SplinePath check for length
|
add SplinePath check for length
|
ActionScript
|
mit
|
iainmerrick/Urho3D,MeshGeometry/Urho3D,henu/Urho3D,tommy3/Urho3D,cosmy1/Urho3D,xiliu98/Urho3D,MonkeyFirst/Urho3D,iainmerrick/Urho3D,iainmerrick/Urho3D,fire/Urho3D-1,PredatorMF/Urho3D,codemon66/Urho3D,MeshGeometry/Urho3D,weitjong/Urho3D,codedash64/Urho3D,299299/Urho3D,tommy3/Urho3D,MonkeyFirst/Urho3D,abdllhbyrktr/Urho3D,fire/Urho3D-1,carnalis/Urho3D,xiliu98/Urho3D,fire/Urho3D-1,iainmerrick/Urho3D,codemon66/Urho3D,victorholt/Urho3D,weitjong/Urho3D,carnalis/Urho3D,helingping/Urho3D,xiliu98/Urho3D,eugeneko/Urho3D,fire/Urho3D-1,MeshGeometry/Urho3D,weitjong/Urho3D,henu/Urho3D,SuperWangKai/Urho3D,bacsmar/Urho3D,PredatorMF/Urho3D,orefkov/Urho3D,victorholt/Urho3D,weitjong/Urho3D,SuperWangKai/Urho3D,SuperWangKai/Urho3D,c4augustus/Urho3D,c4augustus/Urho3D,codedash64/Urho3D,c4augustus/Urho3D,rokups/Urho3D,orefkov/Urho3D,luveti/Urho3D,c4augustus/Urho3D,299299/Urho3D,SirNate0/Urho3D,tommy3/Urho3D,abdllhbyrktr/Urho3D,luveti/Urho3D,eugeneko/Urho3D,helingping/Urho3D,rokups/Urho3D,weitjong/Urho3D,MeshGeometry/Urho3D,victorholt/Urho3D,codedash64/Urho3D,victorholt/Urho3D,kostik1337/Urho3D,henu/Urho3D,rokups/Urho3D,urho3d/Urho3D,rokups/Urho3D,SuperWangKai/Urho3D,codedash64/Urho3D,bacsmar/Urho3D,codedash64/Urho3D,helingping/Urho3D,carnalis/Urho3D,luveti/Urho3D,299299/Urho3D,fire/Urho3D-1,tommy3/Urho3D,MonkeyFirst/Urho3D,henu/Urho3D,tommy3/Urho3D,bacsmar/Urho3D,carnalis/Urho3D,codemon66/Urho3D,urho3d/Urho3D,eugeneko/Urho3D,helingping/Urho3D,codemon66/Urho3D,abdllhbyrktr/Urho3D,urho3d/Urho3D,xiliu98/Urho3D,luveti/Urho3D,kostik1337/Urho3D,SuperWangKai/Urho3D,kostik1337/Urho3D,bacsmar/Urho3D,SirNate0/Urho3D,MonkeyFirst/Urho3D,cosmy1/Urho3D,carnalis/Urho3D,SirNate0/Urho3D,eugeneko/Urho3D,299299/Urho3D,codemon66/Urho3D,victorholt/Urho3D,abdllhbyrktr/Urho3D,iainmerrick/Urho3D,PredatorMF/Urho3D,henu/Urho3D,299299/Urho3D,orefkov/Urho3D,MonkeyFirst/Urho3D,orefkov/Urho3D,cosmy1/Urho3D,PredatorMF/Urho3D,c4augustus/Urho3D,SirNate0/Urho3D,SirNate0/Urho3D,cosmy1/Urho3D,299299/Urho3D,kostik1337/Urho3D,xiliu98/Urho3D,kostik1337/Urho3D,rokups/Urho3D,rokups/Urho3D,abdllhbyrktr/Urho3D,helingping/Urho3D,cosmy1/Urho3D,luveti/Urho3D,MeshGeometry/Urho3D,urho3d/Urho3D
|
5f39b7aa0cd858259376607e54c52f6a2d9e56e4
|
src/aerys/minko/type/enum/TriangleCulling.as
|
src/aerys/minko/type/enum/TriangleCulling.as
|
package aerys.minko.type.enum
{
import aerys.minko.ns.minko_render;
import flash.display.TriangleCulling;
import flash.display3D.Context3DTriangleFace;
public final class TriangleCulling
{
public static const NONE : int = 0;
public static const BACK : int = 1;
public static const FRONT : int = 2;
public static const BOTH : int = 3;
minko_render static const STRINGS : Vector.<String> = new <String>[
Context3DTriangleFace.NONE,
Context3DTriangleFace.FRONT,
Context3DTriangleFace.BACK,
Context3DTriangleFace.FRONT_AND_BACK
];
}
}
|
package aerys.minko.type.enum
{
import aerys.minko.ns.minko_render;
import flash.display.TriangleCulling;
import flash.display3D.Context3DTriangleFace;
public final class TriangleCulling
{
public static const NONE : uint = 0;
public static const BACK : uint = 1;
public static const FRONT : uint = 2;
public static const BOTH : uint = 3;
minko_render static const STRINGS : Vector.<String> = new <String>[
Context3DTriangleFace.NONE,
Context3DTriangleFace.FRONT,
Context3DTriangleFace.BACK,
Context3DTriangleFace.FRONT_AND_BACK
];
}
}
|
use uint for the TriangleCulling enum values
|
use uint for the TriangleCulling enum values
|
ActionScript
|
mit
|
aerys/minko-as3
|
c7a0b2b18336ba007349f1eb66af465da609aa0f
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/Tracker.as
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/Tracker.as
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker
{
import com.snowplowanalytics.snowplow.tracker.emitter.Emitter;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import com.snowplowanalytics.snowplow.tracker.payload.TrackerPayload;
import com.snowplowanalytics.snowplow.tracker.util.Preconditions;
import flash.display.Stage;
import flash.external.ExternalInterface;
import flash.net.LocalConnection;
import flash.net.SharedObject;
import flash.system.Capabilities;
public class Tracker
{
private var base64Encoded:Boolean = true;
private var emitter:Emitter;
private var platform:String;
private var appId:String;
private var namespace:String;
private var trackerVersion:String;
private var subject:Subject;
private var stage:Stage;
private var playerType:String;
private var playerVersion:String;
private var isDebugger:Boolean;
private var hasLocalStorage:Boolean;
private var hasScriptAccess:Boolean;
/**
* @param emitter Emitter to which events will be sent
* @param subject Subject to be tracked
* @param namespace Identifier for the Tracker instance
* @param appId Application ID
* @param stage The flash stage object. used for adding stage info to payload.
* @param base64Encoded Whether JSONs in the payload should be base-64 encoded
*/
function Tracker(emitter:Emitter, namespace:String, appId:String, subject:Subject = null, stage:Stage = null, base64Encoded:Boolean = true) {
this.emitter = emitter;
this.appId = appId;
this.base64Encoded = base64Encoded;
this.namespace = namespace;
this.subject = subject;
this.trackerVersion = Version.TRACKER;
this.platform = DevicePlatform.WEB;
this.stage = stage;
this.playerType = Capabilities.playerType;
this.playerVersion = Capabilities.version;
this.isDebugger = Capabilities.isDebugger;
try
{
SharedObject.getLocal("test");
this.hasLocalStorage = true;
}
catch (e:Error)
{
this.hasLocalStorage = false;
}
this.hasScriptAccess = ExternalInterface.available;
}
/**
* @param payload Payload builder
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
* @return A completed Payload
*/
protected function completePayload(payload:IPayload,
context:Array,
timestamp:Number):IPayload {
payload.add(Parameter.PLATFORM, this.platform);
payload.add(Parameter.APPID, this.appId);
payload.add(Parameter.NAMESPACE, this.namespace);
payload.add(Parameter.TRACKER_VERSION, this.trackerVersion);
payload.add(Parameter.EID, Util.getEventId());
// If timestamp is set to 0, generate one
payload.add(Parameter.TIMESTAMP,
(timestamp == 0 ? Util.getTimestamp() : String(timestamp)));
// Add flash information
if (context == null) {
context = [];
}
var flashData:TrackerPayload = new TrackerPayload();
flashData.add(Parameter.FLASH_PLAYER_TYPE, playerType);
flashData.add(Parameter.FLASH_VERSION, playerVersion);
flashData.add(Parameter.FLASH_IS_DEBUGGER, isDebugger);
flashData.add(Parameter.FLASH_HAS_LOCAL_STORAGE, hasLocalStorage);
flashData.add(Parameter.FLASH_HAS_SCRIPT_ACCESS, hasScriptAccess);
if (stage != null) {
flashData.add(Parameter.FLASH_STAGE_SIZE, { "width": stage.stageWidth, "height": stage.stageHeight});
}
var flashPayload:SchemaPayload = new SchemaPayload();
flashPayload.setSchema(Constants.SCHEMA_FLASH);
flashPayload.setData(flashData.getMap());
context.push(flashPayload);
// Encodes context data
if (context != null && context.length > 0) {
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_CONTEXTS);
// We can do better here, rather than re-iterate through the list
var contextDataList:Array = [];
for each(var schemaPayload:SchemaPayload in context) {
contextDataList.push(schemaPayload.getMap());
}
envelope.setData(contextDataList);
payload.addMap(envelope.getMap(), this.base64Encoded, Parameter.CONTEXT_ENCODED, Parameter.CONTEXT);
}
if (this.subject != null) {
payload.addMap(Util.copyObject(subject.getSubject(), true));
}
return payload;
}
public function setPlatform(platform:String):void {
this.platform = platform;
}
public function getPlatform():String {
return this.platform;
}
protected function setTrackerVersion(version:String):void {
this.trackerVersion = version;
}
private function addTrackerPayload(payload:IPayload):void {
this.emitter.addToBuffer(payload);
}
public function setSubject(subject:Subject):void {
this.subject = subject;
}
public function getSubject():Subject {
return this.subject;
}
/**
* @param pageUrl URL of the viewed page
* @param pageTitle Title of the viewed page
* @param referrer Referrer of the page
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
// public function trackPageView(pageUrl:String, pageTitle:String, referrer:String, context:Array = null, timestamp:Number = 0):void
// {
// // Precondition checks
// Preconditions.checkNotNull(pageUrl);
// Preconditions.checkArgument(!Util.isNullOrEmpty(pageUrl), "pageUrl cannot be empty");
// Preconditions.checkArgument(!Util.isNullOrEmpty(pageTitle), "pageTitle cannot be empty");
// Preconditions.checkArgument(!Util.isNullOrEmpty(referrer), "referrer cannot be empty");
//
// var payload:IPayload = new TrackerPayload();
// payload.add(Parameter.EVENT, Constants.EVENT_PAGE_VIEW);
// payload.add(Parameter.PAGE_URL, pageUrl);
// payload.add(Parameter.PAGE_TITLE, pageTitle);
// payload.add(Parameter.PAGE_REFR, referrer);
//
// completePayload(payload, context, timestamp);
//
// addTrackerPayload(payload);
// }
/**
* @param category Category of the event
* @param action The event itself
* @param label Refer to the object the action is performed on
* @param property Property associated with either the action or the object
* @param value A value associated with the user action
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackStructuredEvent(category:String,
action:String,
label:String,
property:String,
value:int,
context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(label);
Preconditions.checkNotNull(property);
Preconditions.checkArgument(!Util.isNullOrEmpty(label), "label cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(property), "property cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(action), "action cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_STRUCTURED);
payload.add(Parameter.SE_CATEGORY, category);
payload.add(Parameter.SE_ACTION, action);
payload.add(Parameter.SE_LABEL, label);
payload.add(Parameter.SE_PROPERTY, property);
payload.add(Parameter.SE_VALUE, String(value));
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
*
* @param eventData The properties of the event. Has two field:
* A "data" field containing the event properties and
* A "schema" field identifying the schema against which the data is validated
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackUnstructuredEvent(eventData:SchemaPayload, context:Array = null,
timestamp:Number = 0):void
{
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_UNSTRUCT_EVENT);
envelope.setData(eventData.getMap());
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_UNSTRUCTURED);
payload.addMap(envelope.getMap(), base64Encoded,
Parameter.UNSTRUCTURED_ENCODED, Parameter.UNSTRUCTURED);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* This is an internal method called by track_ecommerce_transaction. It is not for public use.
* @param order_id Order ID
* @param sku Item SKU
* @param price Item price
* @param quantity Item quantity
* @param name Item name
* @param category Item category
* @param currency The currency the price is expressed in
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
protected function trackEcommerceTransactionItem(order_id:String, sku:String, price:Number,
quantity:int, name:String, category:String,
currency:String, context:Array,
timestamp:Number):void
{
// Precondition checks
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(category);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(sku), "sku cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(name), "name cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM_ITEM);
payload.add(Parameter.TI_ITEM_ID, order_id);
payload.add(Parameter.TI_ITEM_SKU, sku);
payload.add(Parameter.TI_ITEM_NAME, name);
payload.add(Parameter.TI_ITEM_CATEGORY, category);
payload.add(Parameter.TI_ITEM_PRICE, String(price));
payload.add(Parameter.TI_ITEM_QUANTITY, String(quantity));
payload.add(Parameter.TI_ITEM_CURRENCY, currency);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* @param order_id ID of the eCommerce transaction
* @param total_value Total transaction value
* @param affiliation Transaction affiliation
* @param tax_value Transaction tax value
* @param shipping Delivery cost charged
* @param city Delivery address city
* @param state Delivery address state
* @param country Delivery address country
* @param currency The currency the price is expressed in
* @param items The items in the transaction
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackEcommerceTransaction(order_id:String, total_value:Number, affiliation:String,
tax_value:Number, shipping:Number, city:String,
state:String, country:String, currency:String,
items:Array, context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(affiliation);
Preconditions.checkNotNull(city);
Preconditions.checkNotNull(state);
Preconditions.checkNotNull(country);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(affiliation), "affiliation cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(city), "city cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(state), "state cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(country), "country cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM);
payload.add(Parameter.TR_ID, order_id);
payload.add(Parameter.TR_TOTAL, String(total_value));
payload.add(Parameter.TR_AFFILIATION, affiliation);
payload.add(Parameter.TR_TAX, String(tax_value));
payload.add(Parameter.TR_SHIPPING, String(shipping));
payload.add(Parameter.TR_CITY, city);
payload.add(Parameter.TR_STATE, state);
payload.add(Parameter.TR_COUNTRY, country);
payload.add(Parameter.TR_CURRENCY, currency);
completePayload(payload, context, timestamp);
for each(var item:TransactionItem in items) {
trackEcommerceTransactionItem(
String(item.get(Parameter.TI_ITEM_ID)),
String(item.get(Parameter.TI_ITEM_SKU)),
Number(item.get(Parameter.TI_ITEM_PRICE)),
parseInt(item.get(Parameter.TI_ITEM_QUANTITY)),
String(item.get(Parameter.TI_ITEM_NAME)),
String(item.get(Parameter.TI_ITEM_CATEGORY)),
String(item.get(Parameter.TI_ITEM_CURRENCY)),
item.get(Parameter.CONTEXT),
timestamp);
}
addTrackerPayload(payload);
}
/**
* @param name The name of the screen view event
* @param id Screen view ID
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackScreenView(name:String, id:String, context:Array,
timestamp:Number):void {
Preconditions.checkArgument(name != null || id != null);
var trackerPayload:TrackerPayload = new TrackerPayload();
trackerPayload.add(Parameter.SV_NAME, name);
trackerPayload.add(Parameter.SV_ID, id);
var payload:SchemaPayload = new SchemaPayload();
payload.setSchema(Constants.SCHEMA_SCREEN_VIEW);
payload.setData(trackerPayload);
trackUnstructuredEvent(payload, context, timestamp);
}
}
}
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker
{
import com.adobe.net.URI;
import com.snowplowanalytics.snowplow.tracker.emitter.Emitter;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import com.snowplowanalytics.snowplow.tracker.payload.TrackerPayload;
import com.snowplowanalytics.snowplow.tracker.util.Preconditions;
import flash.display.Stage;
import flash.external.ExternalInterface;
import flash.net.LocalConnection;
import flash.net.SharedObject;
import flash.system.Capabilities;
public class Tracker
{
private var base64Encoded:Boolean = true;
private var emitter:Emitter;
private var platform:String;
private var appId:String;
private var namespace:String;
private var trackerVersion:String;
private var subject:Subject;
private var stage:Stage;
private var playerType:String;
private var playerVersion:String;
private var isDebugger:Boolean;
private var hasLocalStorage:Boolean;
private var hasScriptAccess:Boolean;
private var pageUrl:String = "UNKNOWN";
private var pageTitle:String = "UNKNOWN";
private var referrer:String = "UNKNOWN";
/**
* @param emitter Emitter to which events will be sent
* @param subject Subject to be tracked
* @param namespace Identifier for the Tracker instance
* @param appId Application ID
* @param stage The flash stage object. used for adding stage info to payload.
* @param base64Encoded Whether JSONs in the payload should be base-64 encoded
*/
function Tracker(emitter:Emitter, namespace:String, appId:String, subject:Subject = null, stage:Stage = null, base64Encoded:Boolean = true) {
this.emitter = emitter;
this.appId = appId;
this.base64Encoded = base64Encoded;
this.namespace = namespace;
this.subject = subject;
this.trackerVersion = Version.TRACKER;
this.platform = DevicePlatform.WEB;
this.stage = stage;
this.playerType = Capabilities.playerType;
this.playerVersion = Capabilities.version;
this.isDebugger = Capabilities.isDebugger;
try
{
SharedObject.getLocal("test");
this.hasLocalStorage = true;
}
catch (e:Error)
{
this.hasLocalStorage = false;
}
this.hasScriptAccess = ExternalInterface.available;
if (this.hasScriptAccess) {
try { pageUrl = ExternalInterface.call("function getPageUrl() { return document.location.href; }"); } catch(e:Error) { pageUrl = "UNKNOWN"; }
try { pageTitle = ExternalInterface.call("function getPageTitle() { return document.title; }"); } catch(e:Error) { pageTitle = "UNKNOWN"; }
try { referrer = ExternalInterface.call("function getReferrer() { return document.referrer; }"); } catch(e:Error) { referrer = "UNKNOWN"; }
}
}
/**
* @param payload Payload builder
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
* @return A completed Payload
*/
protected function completePayload(payload:IPayload,
context:Array,
timestamp:Number):IPayload {
payload.add(Parameter.PLATFORM, this.platform);
payload.add(Parameter.APPID, this.appId);
payload.add(Parameter.NAMESPACE, this.namespace);
payload.add(Parameter.TRACKER_VERSION, this.trackerVersion);
payload.add(Parameter.EID, Util.getEventId());
//Add page data
payload.add(Parameter.PAGE_URL, pageUrl);
payload.add(Parameter.PAGE_TITLE, pageTitle);
payload.add(Parameter.PAGE_REFR, referrer);
// If timestamp is set to 0, generate one
payload.add(Parameter.TIMESTAMP,
(timestamp == 0 ? Util.getTimestamp() : String(timestamp)));
// Add flash information
if (context == null) {
context = [];
}
var flashData:TrackerPayload = new TrackerPayload();
flashData.add(Parameter.FLASH_PLAYER_TYPE, playerType);
flashData.add(Parameter.FLASH_VERSION, playerVersion);
flashData.add(Parameter.FLASH_IS_DEBUGGER, isDebugger);
flashData.add(Parameter.FLASH_HAS_LOCAL_STORAGE, hasLocalStorage);
flashData.add(Parameter.FLASH_HAS_SCRIPT_ACCESS, hasScriptAccess);
if (stage != null) {
flashData.add(Parameter.FLASH_STAGE_SIZE, { "width": stage.stageWidth, "height": stage.stageHeight});
}
var flashPayload:SchemaPayload = new SchemaPayload();
flashPayload.setSchema(Constants.SCHEMA_FLASH);
flashPayload.setData(flashData.getMap());
context.push(flashPayload);
// Encodes context data
if (context != null && context.length > 0) {
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_CONTEXTS);
// We can do better here, rather than re-iterate through the list
var contextDataList:Array = [];
for each(var schemaPayload:SchemaPayload in context) {
contextDataList.push(schemaPayload.getMap());
}
envelope.setData(contextDataList);
payload.addMap(envelope.getMap(), this.base64Encoded, Parameter.CONTEXT_ENCODED, Parameter.CONTEXT);
}
if (this.subject != null) {
payload.addMap(Util.copyObject(subject.getSubject(), true));
}
return payload;
}
public function setPlatform(platform:String):void {
this.platform = platform;
}
public function getPlatform():String {
return this.platform;
}
protected function setTrackerVersion(version:String):void {
this.trackerVersion = version;
}
private function addTrackerPayload(payload:IPayload):void {
this.emitter.addToBuffer(payload);
}
public function setSubject(subject:Subject):void {
this.subject = subject;
}
public function getSubject():Subject {
return this.subject;
}
/**
* @param pageUrl URL of the viewed page
* @param pageTitle Title of the viewed page
* @param referrer Referrer of the page
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
// public function trackPageView(pageUrl:String, pageTitle:String, referrer:String, context:Array = null, timestamp:Number = 0):void
// {
// // Precondition checks
// Preconditions.checkNotNull(pageUrl);
// Preconditions.checkArgument(!Util.isNullOrEmpty(pageUrl), "pageUrl cannot be empty");
// Preconditions.checkArgument(!Util.isNullOrEmpty(pageTitle), "pageTitle cannot be empty");
// Preconditions.checkArgument(!Util.isNullOrEmpty(referrer), "referrer cannot be empty");
//
// var payload:IPayload = new TrackerPayload();
// payload.add(Parameter.EVENT, Constants.EVENT_PAGE_VIEW);
// payload.add(Parameter.PAGE_URL, pageUrl);
// payload.add(Parameter.PAGE_TITLE, pageTitle);
// payload.add(Parameter.PAGE_REFR, referrer);
//
// completePayload(payload, context, timestamp);
//
// addTrackerPayload(payload);
// }
/**
* @param category Category of the event
* @param action The event itself
* @param label Refer to the object the action is performed on
* @param property Property associated with either the action or the object
* @param value A value associated with the user action
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackStructuredEvent(category:String,
action:String,
label:String,
property:String,
value:int,
context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(label);
Preconditions.checkNotNull(property);
Preconditions.checkArgument(!Util.isNullOrEmpty(label), "label cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(property), "property cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(action), "action cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_STRUCTURED);
payload.add(Parameter.SE_CATEGORY, category);
payload.add(Parameter.SE_ACTION, action);
payload.add(Parameter.SE_LABEL, label);
payload.add(Parameter.SE_PROPERTY, property);
payload.add(Parameter.SE_VALUE, String(value));
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
*
* @param eventData The properties of the event. Has two field:
* A "data" field containing the event properties and
* A "schema" field identifying the schema against which the data is validated
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackUnstructuredEvent(eventData:SchemaPayload, context:Array = null,
timestamp:Number = 0):void
{
var envelope:SchemaPayload = new SchemaPayload();
envelope.setSchema(Constants.SCHEMA_UNSTRUCT_EVENT);
envelope.setData(eventData.getMap());
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_UNSTRUCTURED);
payload.addMap(envelope.getMap(), base64Encoded,
Parameter.UNSTRUCTURED_ENCODED, Parameter.UNSTRUCTURED);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* This is an internal method called by track_ecommerce_transaction. It is not for public use.
* @param order_id Order ID
* @param sku Item SKU
* @param price Item price
* @param quantity Item quantity
* @param name Item name
* @param category Item category
* @param currency The currency the price is expressed in
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
protected function trackEcommerceTransactionItem(order_id:String, sku:String, price:Number,
quantity:int, name:String, category:String,
currency:String, context:Array,
timestamp:Number):void
{
// Precondition checks
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(category);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(sku), "sku cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(name), "name cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(category), "category cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM_ITEM);
payload.add(Parameter.TI_ITEM_ID, order_id);
payload.add(Parameter.TI_ITEM_SKU, sku);
payload.add(Parameter.TI_ITEM_NAME, name);
payload.add(Parameter.TI_ITEM_CATEGORY, category);
payload.add(Parameter.TI_ITEM_PRICE, String(price));
payload.add(Parameter.TI_ITEM_QUANTITY, String(quantity));
payload.add(Parameter.TI_ITEM_CURRENCY, currency);
completePayload(payload, context, timestamp);
addTrackerPayload(payload);
}
/**
* @param order_id ID of the eCommerce transaction
* @param total_value Total transaction value
* @param affiliation Transaction affiliation
* @param tax_value Transaction tax value
* @param shipping Delivery cost charged
* @param city Delivery address city
* @param state Delivery address state
* @param country Delivery address country
* @param currency The currency the price is expressed in
* @param items The items in the transaction
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackEcommerceTransaction(order_id:String, total_value:Number, affiliation:String,
tax_value:Number, shipping:Number, city:String,
state:String, country:String, currency:String,
items:Array, context:Array = null,
timestamp:Number = 0):void
{
// Precondition checks
Preconditions.checkNotNull(affiliation);
Preconditions.checkNotNull(city);
Preconditions.checkNotNull(state);
Preconditions.checkNotNull(country);
Preconditions.checkNotNull(currency);
Preconditions.checkArgument(!Util.isNullOrEmpty(order_id), "order_id cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(affiliation), "affiliation cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(city), "city cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(state), "state cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(country), "country cannot be empty");
Preconditions.checkArgument(!Util.isNullOrEmpty(currency), "currency cannot be empty");
var payload:IPayload = new TrackerPayload();
payload.add(Parameter.EVENT, Constants.EVENT_ECOMM);
payload.add(Parameter.TR_ID, order_id);
payload.add(Parameter.TR_TOTAL, String(total_value));
payload.add(Parameter.TR_AFFILIATION, affiliation);
payload.add(Parameter.TR_TAX, String(tax_value));
payload.add(Parameter.TR_SHIPPING, String(shipping));
payload.add(Parameter.TR_CITY, city);
payload.add(Parameter.TR_STATE, state);
payload.add(Parameter.TR_COUNTRY, country);
payload.add(Parameter.TR_CURRENCY, currency);
completePayload(payload, context, timestamp);
for each(var item:TransactionItem in items) {
trackEcommerceTransactionItem(
String(item.get(Parameter.TI_ITEM_ID)),
String(item.get(Parameter.TI_ITEM_SKU)),
Number(item.get(Parameter.TI_ITEM_PRICE)),
parseInt(item.get(Parameter.TI_ITEM_QUANTITY)),
String(item.get(Parameter.TI_ITEM_NAME)),
String(item.get(Parameter.TI_ITEM_CATEGORY)),
String(item.get(Parameter.TI_ITEM_CURRENCY)),
item.get(Parameter.CONTEXT),
timestamp);
}
addTrackerPayload(payload);
}
/**
* @param name The name of the screen view event
* @param id Screen view ID
* @param context Custom context for the event
* @param timestamp Optional user-provided timestamp for the event
*/
public function trackScreenView(name:String, id:String, context:Array,
timestamp:Number):void {
Preconditions.checkArgument(name != null || id != null);
var trackerPayload:TrackerPayload = new TrackerPayload();
trackerPayload.add(Parameter.SV_NAME, name);
trackerPayload.add(Parameter.SV_ID, id);
var payload:SchemaPayload = new SchemaPayload();
payload.setSchema(Constants.SCHEMA_SCREEN_VIEW);
payload.setData(trackerPayload);
trackUnstructuredEvent(payload, context, timestamp);
}
}
}
|
Send page URL and refr URL fields with all events, not just page views. resolves #16
|
Send page URL and refr URL fields with all events, not just page views. resolves #16
|
ActionScript
|
apache-2.0
|
snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker
|
dc98d00124b0bd4320a6774716a7e7bde01c0cea
|
src/org/flintparticles/twoD/actions/TweenToCurrentPosition.as
|
src/org/flintparticles/twoD/actions/TweenToCurrentPosition.as
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2011
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.twoD.actions
{
import org.flintparticles.common.actions.ActionBase;
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.common.initializers.Initializer;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.twoD.particles.Particle2D;
import org.flintparticles.twoD.zones.Zone2D;
import flash.geom.Point;
[DefaultProperty("zone")]
/**
* The TweenToCurrentPosition action adjusts the particle's position between two
* locations as it ages. The start location is a random point within the specified
* zone, and the end location is the particle's position when it is created or added
* to the emitter. The current position is relative to the particle's energy,
* which changes as the particle ages in accordance with the energy easing
* function used. This action should be used in conjunction with the Age action.
*/
public class TweenToCurrentPosition extends ActionBase implements Initializer
{
private var _zone : Zone2D;
/**
* The constructor creates a TweenToCurrentPosition action for use by an emitter.
* To add a TweenToCurrentPosition to all particles created by an emitter, use the
* emitter's addAction method.
*
* @see org.flintparticles.common.emitters.Emitter#addAction()
*
* @param zone The zone for the particle's position when its energy is 0.
*/
public function TweenToCurrentPosition( zone : Zone2D )
{
_zone = zone;
priority = -10;
}
/**
* The zone for the particle's position when its energy is 0.
*/
public function get zone() : Zone2D
{
return _zone;
}
public function set zone( value : Zone2D ) : void
{
_zone = value;
}
/**
*
*/
override public function addedToEmitter( emitter : Emitter ) : void
{
if ( !emitter.hasInitializer( this ) )
{
emitter.addInitializer( this );
}
}
override public function removedFromEmitter( emitter : Emitter ) : void
{
emitter.removeInitializer( this );
}
/**
*
*/
public function initialize( emitter : Emitter, particle : Particle ) : void
{
var p : Particle2D = Particle2D( particle );
var pt : Point = _zone.getLocation();
var data : TweenToPositionData = new TweenToPositionData( pt.x, pt.y, p.x, p.y );
p.dictionary[this] = data;
}
/**
* Calculates the current position of the particle based on it's energy.
*
* <p>This method is called by the emitter and need not be called by the
* user.</p>
*
* @param emitter The Emitter that created the particle.
* @param particle The particle to be updated.
* @param time The duration of the frame - used for time based updates.
*
* @see org.flintparticles.common.actions.Action#update()
*/
override public function update( emitter : Emitter, particle : Particle, time : Number ) : void
{
var p : Particle2D = Particle2D( particle );
if ( !p.dictionary[this] )
{
initialize( emitter, particle );
}
var data : TweenToPositionData = p.dictionary[this];
p.x = data.endX + data.diffX * p.energy;
p.y = data.endY + data.diffY * p.energy;
}
}
}
class TweenToPositionData
{
public var diffX : Number;
public var diffY : Number;
public var endX : Number;
public var endY : Number;
public function TweenToPositionData( startX : Number, startY : Number, endX : Number, endY : Number )
{
this.diffX = startX - endX;
this.diffY = startY - endY;
this.endX = endX;
this.endY = endY;
}
}
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2011
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.twoD.actions
{
import org.flintparticles.common.actions.ActionBase;
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.common.initializers.Initializer;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.twoD.particles.Particle2D;
import org.flintparticles.twoD.zones.Zone2D;
import flash.geom.Point;
[DefaultProperty("zone")]
/**
* The TweenToCurrentPosition action adjusts the particle's position between two
* locations as it ages. The start location is a random point within the specified
* zone, and the end location is the particle's position when it is created or added
* to the emitter. The current position is relative to the particle's energy,
* which changes as the particle ages in accordance with the energy easing
* function used. This action should be used in conjunction with the Age action.
*/
public class TweenToCurrentPosition extends ActionBase implements Initializer
{
private var _zone : Zone2D;
/**
* The constructor creates a TweenToCurrentPosition action for use by an emitter.
* To add a TweenToCurrentPosition to all particles created by an emitter, use the
* emitter's addAction method.
*
* @see org.flintparticles.common.emitters.Emitter#addAction()
*
* @param zone The zone for the particle's position when its energy is 0.
*/
public function TweenToCurrentPosition( zone : Zone2D = null )
{
_zone = zone;
priority = -10;
}
/**
* The zone for the particle's position when its energy is 0.
*/
public function get zone() : Zone2D
{
return _zone;
}
public function set zone( value : Zone2D ) : void
{
_zone = value;
}
/**
*
*/
override public function addedToEmitter( emitter : Emitter ) : void
{
if ( !emitter.hasInitializer( this ) )
{
emitter.addInitializer( this );
}
}
override public function removedFromEmitter( emitter : Emitter ) : void
{
emitter.removeInitializer( this );
}
/**
*
*/
public function initialize( emitter : Emitter, particle : Particle ) : void
{
var p : Particle2D = Particle2D( particle );
var pt : Point = _zone.getLocation();
var data : TweenToPositionData = new TweenToPositionData( pt.x, pt.y, p.x, p.y );
p.dictionary[this] = data;
}
/**
* Calculates the current position of the particle based on it's energy.
*
* <p>This method is called by the emitter and need not be called by the
* user.</p>
*
* @param emitter The Emitter that created the particle.
* @param particle The particle to be updated.
* @param time The duration of the frame - used for time based updates.
*
* @see org.flintparticles.common.actions.Action#update()
*/
override public function update( emitter : Emitter, particle : Particle, time : Number ) : void
{
var p : Particle2D = Particle2D( particle );
if ( !p.dictionary[this] )
{
initialize( emitter, particle );
}
var data : TweenToPositionData = p.dictionary[this];
p.x = data.endX + data.diffX * p.energy;
p.y = data.endY + data.diffY * p.energy;
}
}
}
class TweenToPositionData
{
public var diffX : Number;
public var diffY : Number;
public var endX : Number;
public var endY : Number;
public function TweenToPositionData( startX : Number, startY : Number, endX : Number, endY : Number )
{
this.diffX = startX - endX;
this.diffY = startY - endY;
this.endX = endX;
this.endY = endY;
}
}
|
Add default parameter to support MXML.
|
Add default parameter to support MXML.
|
ActionScript
|
mit
|
richardlord/Flint
|
0cba1203c9bc71ff038658aa2e0114b7b6718ae3
|
src/as/com/threerings/util/Line.as
|
src/as/com/threerings/util/Line.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util {
import flash.geom.Point;
import flash.geom.Matrix;
/**
* Merely a typed container for two Points.
*/
public class Line
{
public static const INTERSECTION_NORTH :int = 1;
public static const INTERSECTION_SOUTH :int = 2;
public static const DOES_NOT_INTERSECT :int = 3;
public var start :Point;
public var stop :Point;
public function Line (start :Point, stop :Point)
{
this.start = start;
this.stop = stop;
}
public function isIntersected (line :Line) :Boolean
{
return getIntersectionType(line) != DOES_NOT_INTERSECT;
}
/**
* Tests if the given line intersects this line. This method rotates both lines so that the
* start point of this line is on the left, at (0, 0). If the lines do intersect, it then
* returns INTERSECTION_NORTH if the end point of <code>line</code> is north of this line,
* INTERSECTION_SOUTH otherwise.
*
* Intersections are inclusive. If one or both points lands on this line, interects will not
* return DOES_NOT_INTERSECT.
*/
public function getIntersectionType (line :Line) :int
{
// rotate so that this line is horizontal, with the start on the left, at (0, 0)
var trans :Matrix = new Matrix();
trans.translate(-start.x, -start.y);
trans.rotate(-Math.atan2(stop.y - start.y, stop.x - start.x));
var thisLineStop :Point = trans.transformPoint(stop);
var thatLineStart :Point = trans.transformPoint(line.start);
var thatLineStop :Point = trans.transformPoint(line.stop);
if (thatLineStart.y >= 0 && thatLineStop.y <= 0) {
var interp :Point = Point.interpolate(thatLineStart, thatLineStop, thatLineStop.y /
(thatLineStop.y + (-thatLineStart.y)));
if (interp.x >= 0 && interp.x <= thisLineStop.x) {
return INTERSECTION_NORTH;
} else {
return DOES_NOT_INTERSECT;
}
} else if (thatLineStart.y <= 0 && thatLineStop.y >= 0) {
interp = Point.interpolate(thatLineStop, thatLineStart, thatLineStart.y /
(thatLineStart.y + (-thatLineStop.y)));
if (interp.x >= 0 && interp.x <= thisLineStop.x) {
return INTERSECTION_SOUTH;
} else {
return DOES_NOT_INTERSECT;
}
} else {
return DOES_NOT_INTERSECT;
}
}
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util {
import flash.geom.Point;
import flash.geom.Matrix;
/**
* Merely a typed container for two Points.
*/
public class Line implements Equalable
{
public static const INTERSECTION_NORTH :int = 1;
public static const INTERSECTION_SOUTH :int = 2;
public static const DOES_NOT_INTERSECT :int = 3;
public var start :Point;
public var stop :Point;
public function Line (start :Point, stop :Point)
{
this.start = start;
this.stop = stop;
}
public function isIntersected (line :Line) :Boolean
{
return getIntersectionType(line) != DOES_NOT_INTERSECT;
}
/**
* Tests if the given line intersects this line. This method rotates both lines so that the
* start point of this line is on the left, at (0, 0). If the lines do intersect, it then
* returns INTERSECTION_NORTH if the end point of <code>line</code> is north of this line,
* INTERSECTION_SOUTH otherwise.
*
* Intersections are inclusive. If one or both points lands on this line, interects will not
* return DOES_NOT_INTERSECT.
*/
public function getIntersectionType (line :Line) :int
{
// rotate so that this line is horizontal, with the start on the left, at (0, 0)
var trans :Matrix = new Matrix();
trans.translate(-start.x, -start.y);
trans.rotate(-Math.atan2(stop.y - start.y, stop.x - start.x));
var thisLineStop :Point = trans.transformPoint(stop);
var thatLineStart :Point = trans.transformPoint(line.start);
var thatLineStop :Point = trans.transformPoint(line.stop);
if (thatLineStart.y >= 0 && thatLineStop.y <= 0) {
var interp :Point = Point.interpolate(thatLineStart, thatLineStop, thatLineStop.y /
(thatLineStop.y + (-thatLineStart.y)));
if (interp.x >= 0 && interp.x <= thisLineStop.x) {
return INTERSECTION_NORTH;
} else {
return DOES_NOT_INTERSECT;
}
} else if (thatLineStart.y <= 0 && thatLineStop.y >= 0) {
interp = Point.interpolate(thatLineStop, thatLineStart, thatLineStart.y /
(thatLineStart.y + (-thatLineStop.y)));
if (interp.x >= 0 && interp.x <= thisLineStop.x) {
return INTERSECTION_SOUTH;
} else {
return DOES_NOT_INTERSECT;
}
} else {
return DOES_NOT_INTERSECT;
}
}
// from interface Equalable
public function equals (o :Object) :Boolean
{
var other :Line = o as Line;
if (other == null) {
return false;
}
if (start == null || other.start == null) {
if (start != other.start) {
// not both null
return false;
}
}
if (stop == null || other.stop == null) {
if (stop != other.stop) {
// not both null
return false;
}
}
return (start == null || start.equals(other.start)) &&
(stop == null || stop.equals(other.stop));
}
}
}
|
implement equalable
|
implement equalable
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4700 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
7bbe9bf80e08cc1cbf4693327462c7568d26b412
|
src/aerys/minko/render/DrawCall.as
|
src/aerys/minko/render/DrawCall.as
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.geometry.stream.format.VertexFormat;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.VertexBuffer3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.binding.IBinder;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.ColorMask;
import aerys.minko.type.enum.TriangleCulling;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import flash.display3D.Context3DProgramType;
import flash.utils.Dictionary;
/**
* DrawCall objects contain all the shader constants and buffer settings required
* to perform drawing operations using the Stage3D API.
* @author Jean-Marc Le Roux
*
*/
public final class DrawCall
{
use namespace minko_render;
private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX;
private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT;
private static const NUM_TEXTURES : uint = 8;
private static const NUM_VERTEX_BUFFERS : uint = 8;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true);
private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true);
private var _bindings : Object = null;
private var _vsInputComponents : Vector.<VertexComponent> = null;
private var _vsInputIndices : Vector.<uint> = null;
private var _cpuConstants : Dictionary = null;
private var _vsConstants : Vector.<Number> = null;
private var _fsConstants : Vector.<Number> = null;
private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true);
// states
private var _indexBuffer : IndexBuffer3DResource = null;
private var _firstIndex : int = 0;
private var _numTriangles : int = -1;
private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true);
private var _numVertexComponents: uint = 0;
private var _offsets : Vector.<int> = new Vector.<int>(8, true);
private var _formats : Vector.<String> = new Vector.<String>(8, true);
private var _blending : uint = 0;
private var _blendingSource : String = null;
private var _blendingDest : String = null;
private var _triangleCulling : uint = 0;
private var _triangleCullingStr : String = null;
private var _enabled : Boolean = true;
private var _depth : Number = 0.;
private var _center : Vector4 = null;
private var _invalidDepth : Boolean = false;
private var _localToWorld : Matrix4x4 = null;
private var _worldToScreen : Matrix4x4 = null;
private var _bindingsConsumer : DrawCallBindingsConsumer;
public function get vertexComponents() : Vector.<VertexComponent>
{
return _vsInputComponents;
}
public function get blending() : uint
{
return _blending;
}
public function set blending(value : uint) : void
{
_blending = value;
_blendingSource = Blending.STRINGS[int(value & 0xffff)];
_blendingDest = Blending.STRINGS[int(value >>> 16)]
}
public function get triangleCulling() : uint
{
return _triangleCulling;
}
public function set triangleCulling(value : uint) : void
{
_triangleCulling = value;
_triangleCullingStr = TriangleCulling.STRINGS[value];
}
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
if (_bindingsConsumer)
_bindingsConsumer.enabled = value;
}
public function get depth() : Number
{
if (_invalidDepth && _enabled)
{
_invalidDepth = false;
if (_localToWorld != null && _worldToScreen != null)
{
var worldSpacePosition : Vector4 = _localToWorld.transformVector(
_center, TMP_VECTOR4
);
var screenSpacePosition : Vector4 = _worldToScreen.transformVector(
worldSpacePosition, TMP_VECTOR4
);
_depth = screenSpacePosition.z / screenSpacePosition.w;
}
}
return _depth;
}
public function configure(program : Program3DResource,
geometry : Geometry,
meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
_invalidDepth = computeDepth;
setProgram(program);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
if (_bindingsConsumer != null)
{
meshBindings.removeConsumer(_bindingsConsumer);
sceneBindings.removeConsumer(_bindingsConsumer);
}
if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler))
sceneBindings.removeCallback('worldToScreen', transformChangedHandler);
if (meshBindings.hasCallback('localToWorld', transformChangedHandler))
meshBindings.removeCallback('localToWorld', transformChangedHandler);
_bindingsConsumer = null;
}
private function setProgram(program : Program3DResource) : void
{
_cpuConstants = new Dictionary();
_vsConstants = program._vsConstants.slice();
_fsConstants = program._fsConstants.slice();
_fsTextures = program._fsTextures.slice();
_vsInputComponents = program._vertexInputComponents;
_vsInputIndices = program._vertexInputIndices;
_bindings = program._bindings;
_bindingsConsumer = new DrawCallBindingsConsumer(
_bindings,
_cpuConstants,
_vsConstants,
_fsConstants,
_fsTextures
);
_bindingsConsumer.enabled = _enabled;
triangleCulling = TriangleCulling.FRONT;
blending = Blending.OPAQUE;
}
/**
* Ask geometry to compute additional vertex data if needed for this drawcall.
*/
public function updateGeometry(geometry : Geometry) : void
{
var vertexFormat : VertexFormat = geometry.format;
var hasNormals : Boolean = vertexFormat.hasComponent(VertexComponent.NORMAL);
if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0
&& !vertexFormat.hasComponent(VertexComponent.TANGENT))
{
geometry.computeTangentSpace(!hasNormals);
}
else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !hasNormals)
{
geometry.computeNormals();
}
}
/**
* Obtain a reference to each buffer and offset that apply() may possibly need.
*
*/
public function setGeometry(geometry : Geometry, frame : uint = 0) : void
{
if (!_vsInputComponents)
return ;
updateGeometry(geometry);
_center = geometry.boundingSphere
? geometry.boundingSphere.center
: Vector4.ZERO;
_numVertexComponents = _vsInputComponents.length;
_indexBuffer = geometry.indexStream.resource;
_firstIndex = geometry.firstIndex;
_numTriangles = geometry.numTriangles;
for (var i : uint = 0; i < _numVertexComponents; ++i)
{
var component : VertexComponent = _vsInputComponents[i];
var index : uint = _vsInputIndices[i];
if (component)
{
var vertexStream : IVertexStream = geometry.getVertexStream(index + frame);
var stream : VertexStream = vertexStream.getStreamByComponent(component);
if (stream == null)
{
throw new Error(
'Missing vertex component: \'' + component.toString() + '\'.'
);
}
_vertexBuffers[i] = stream.resource;
_formats[i] = component.nativeFormatString;
_offsets[i] = stream.format.getOffsetForComponent(component);
}
}
}
/**
* @fixme There is a bug here
* @fixme We splitted properties between scene and mesh
* @fixme it should be done on the compiler also to avoid this ugly hack
*/
private function setBindings(meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
meshBindings.addConsumer(_bindingsConsumer);
sceneBindings.addConsumer(_bindingsConsumer);
if (computeDepth)
{
// _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4;
// _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4;
sceneBindings.addCallback('worldToScreen', transformChangedHandler);
meshBindings.addCallback('localToWorld', transformChangedHandler);
_invalidDepth = true;
}
}
public function apply(context : Context3DResource, previous : DrawCall) : uint
{
context.setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants)
.setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants);
var numTextures : uint = _fsTextures.length;
var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES;
var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS;
var i : uint = 0;
// setup textures
for (i = 0; i < numTextures; ++i)
{
context.setTextureAt(
i,
(_fsTextures[i] as ITextureResource).getTexture(context)
);
}
while (i < maxTextures)
context.setTextureAt(i++, null);
// setup buffers
for (i = 0; i < _numVertexComponents; ++i)
{
context.setVertexBufferAt(
i,
(_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context),
_offsets[i],
_formats[i]
);
}
while (i < maxBuffers)
context.setVertexBufferAt(i++, null);
// draw triangles
context.drawTriangles(
_indexBuffer.getIndexBuffer3D(context),
_firstIndex,
_numTriangles
);
return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles;
}
public function setParameter(name : String, value : Object) : void
{
_bindingsConsumer.setProperty(name, value);
}
private function transformChangedHandler(bindings : DataBindings,
property : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
if (property == 'worldToScreen')
_worldToScreen = newValue;
else if (property == 'localToWorld')
_localToWorld = newValue;
_invalidDepth = true;
}
}
}
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.geometry.stream.format.VertexFormat;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.VertexBuffer3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.binding.IBinder;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.ColorMask;
import aerys.minko.type.enum.TriangleCulling;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import flash.display3D.Context3DProgramType;
import flash.utils.Dictionary;
/**
* DrawCall objects contain all the shader constants and buffer settings required
* to perform drawing operations using the Stage3D API.
* @author Jean-Marc Le Roux
*
*/
public final class DrawCall
{
use namespace minko_render;
private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX;
private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT;
private static const NUM_TEXTURES : uint = 8;
private static const NUM_VERTEX_BUFFERS : uint = 8;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true);
private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true);
private var _bindings : Object = null;
private var _vsInputComponents : Vector.<VertexComponent> = null;
private var _vsInputIndices : Vector.<uint> = null;
private var _cpuConstants : Dictionary = null;
private var _vsConstants : Vector.<Number> = null;
private var _fsConstants : Vector.<Number> = null;
private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true);
// states
private var _indexBuffer : IndexBuffer3DResource = null;
private var _firstIndex : int = 0;
private var _numTriangles : int = -1;
private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true);
private var _numVertexComponents: uint = 0;
private var _offsets : Vector.<int> = new Vector.<int>(8, true);
private var _formats : Vector.<String> = new Vector.<String>(8, true);
private var _blending : uint = 0;
private var _blendingSource : String = null;
private var _blendingDest : String = null;
private var _triangleCulling : uint = 0;
private var _triangleCullingStr : String = null;
private var _enabled : Boolean = true;
private var _depth : Number = 0.;
private var _center : Vector4 = null;
private var _invalidDepth : Boolean = false;
private var _localToWorld : Matrix4x4 = null;
private var _worldToScreen : Matrix4x4 = null;
private var _bindingsConsumer : DrawCallBindingsConsumer;
public function get vertexComponents() : Vector.<VertexComponent>
{
return _vsInputComponents;
}
public function get blending() : uint
{
return _blending;
}
public function set blending(value : uint) : void
{
_blending = value;
_blendingSource = Blending.STRINGS[int(value & 0xffff)];
_blendingDest = Blending.STRINGS[int(value >>> 16)]
}
public function get triangleCulling() : uint
{
return _triangleCulling;
}
public function set triangleCulling(value : uint) : void
{
_triangleCulling = value;
_triangleCullingStr = TriangleCulling.STRINGS[value];
}
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
if (_bindingsConsumer)
_bindingsConsumer.enabled = value;
}
public function get depth() : Number
{
if (_invalidDepth && _enabled)
{
_invalidDepth = false;
if (_localToWorld != null && _worldToScreen != null)
{
var worldSpacePosition : Vector4 = _localToWorld.transformVector(
_center, TMP_VECTOR4
);
var screenSpacePosition : Vector4 = _worldToScreen.transformVector(
worldSpacePosition, TMP_VECTOR4
);
_depth = screenSpacePosition.z / screenSpacePosition.w;
}
}
return _depth;
}
public function configure(program : Program3DResource,
geometry : Geometry,
meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
_invalidDepth = computeDepth;
setProgram(program);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
if (_bindingsConsumer != null)
{
meshBindings.removeConsumer(_bindingsConsumer);
sceneBindings.removeConsumer(_bindingsConsumer);
}
if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler))
sceneBindings.removeCallback('worldToScreen', transformChangedHandler);
if (meshBindings.hasCallback('localToWorld', transformChangedHandler))
meshBindings.removeCallback('localToWorld', transformChangedHandler);
_bindingsConsumer = null;
}
private function setProgram(program : Program3DResource) : void
{
_cpuConstants = new Dictionary();
_vsConstants = program._vsConstants.slice();
_fsConstants = program._fsConstants.slice();
_fsTextures = program._fsTextures.slice();
_vsInputComponents = program._vertexInputComponents;
_vsInputIndices = program._vertexInputIndices;
_bindings = program._bindings;
_bindingsConsumer = new DrawCallBindingsConsumer(
_bindings,
_cpuConstants,
_vsConstants,
_fsConstants,
_fsTextures
);
_bindingsConsumer.enabled = _enabled;
triangleCulling = TriangleCulling.FRONT;
blending = Blending.OPAQUE;
}
/**
* Ask geometry to compute additional vertex data if needed for this drawcall.
*/
public function updateGeometry(geometry : Geometry) : void
{
var vertexFormat : VertexFormat = geometry.format;
var hasNormals : Boolean = vertexFormat.hasComponent(VertexComponent.NORMAL);
if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0
&& !vertexFormat.hasComponent(VertexComponent.TANGENT))
{
geometry.computeTangentSpace(!hasNormals);
}
else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !hasNormals)
{
geometry.computeNormals();
}
}
/**
* Obtain a reference to each buffer and offset that apply() may possibly need.
*
*/
public function setGeometry(geometry : Geometry, frame : uint = 0) : void
{
if (!_vsInputComponents)
return ;
updateGeometry(geometry);
_center = geometry.boundingSphere
? geometry.boundingSphere.center
: Vector4.ZERO;
_numVertexComponents = _vsInputComponents.length;
_indexBuffer = geometry.indexStream.resource;
_firstIndex = geometry.firstIndex;
_numTriangles = geometry.numTriangles;
for (var i : uint = 0; i < _numVertexComponents; ++i)
{
var component : VertexComponent = _vsInputComponents[i];
var index : uint = _vsInputIndices[i];
if (component)
{
var vertexStream : IVertexStream = geometry.getVertexStream(index + frame);
var stream : VertexStream = vertexStream.getStreamByComponent(component);
if (stream == null)
{
throw new Error(
'Missing vertex component: \'' + component.toString() + '\'.'
);
}
_vertexBuffers[i] = stream.resource;
_formats[i] = component.nativeFormatString;
_offsets[i] = stream.format.getOffsetForComponent(component);
}
}
}
/**
* @fixme There is a bug here
* @fixme We splitted properties between scene and mesh
* @fixme it should be done on the compiler also to avoid this ugly hack
*/
private function setBindings(meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
meshBindings.addConsumer(_bindingsConsumer);
sceneBindings.addConsumer(_bindingsConsumer);
if (computeDepth)
{
if (sceneBindings.propertyExists('worldToScreen'))
_worldToScreen = sceneBindings.getProperty('worldToScreen');
sceneBindings.addCallback('worldToScreen', transformChangedHandler);
if (meshBindings.propertyExists('localToWorld'))
_localToWorld = meshBindings.getProperty('localToWorld');
meshBindings.addCallback('localToWorld', transformChangedHandler);
_invalidDepth = true;
}
}
public function apply(context : Context3DResource, previous : DrawCall) : uint
{
context.setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants)
.setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants);
var numTextures : uint = _fsTextures.length;
var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES;
var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS;
var i : uint = 0;
// setup textures
for (i = 0; i < numTextures; ++i)
{
context.setTextureAt(
i,
(_fsTextures[i] as ITextureResource).getTexture(context)
);
}
while (i < maxTextures)
context.setTextureAt(i++, null);
// setup buffers
for (i = 0; i < _numVertexComponents; ++i)
{
context.setVertexBufferAt(
i,
(_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context),
_offsets[i],
_formats[i]
);
}
while (i < maxBuffers)
context.setVertexBufferAt(i++, null);
// draw triangles
context.drawTriangles(
_indexBuffer.getIndexBuffer3D(context),
_firstIndex,
_numTriangles
);
return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles;
}
public function setParameter(name : String, value : Object) : void
{
_bindingsConsumer.setProperty(name, value);
}
private function transformChangedHandler(bindings : DataBindings,
property : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
if (property == 'worldToScreen')
_worldToScreen = newValue;
else if (property == 'localToWorld')
_localToWorld = newValue;
_invalidDepth = true;
}
}
}
|
fix DrawCall.depth update by making sure the reference to localToWorld and worldToScreen are init. directly from the bindings if available when DrawCall.setBindings() is called
|
fix DrawCall.depth update by making sure the reference to localToWorld and worldToScreen are init. directly from the bindings if available when DrawCall.setBindings() is called
|
ActionScript
|
mit
|
aerys/minko-as3
|
5d09279b20091193ec65f011673a97a79983a8dc
|
src/org/mangui/hls/HLSSettings.as
|
src/org/mangui/hls/HLSSettings.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // // /////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // // /////////////////////////////////
/**
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 300.
*/
public static var maxBufferLength : Number = 300;
/**
* Defines maximum back buffer length in seconds.
* (0 means infinite back buffering)
*
* Default is 30.
*/
public static var maxBackBufferLength : Number = 30;
/**
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3.
*/
public static var lowBufferLength : Number = 3;
/**
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
* HLSSeekMode.SEGMENT_SEEK - segment based seeking (seek to beginning of segment containing requested seek position)
*
* Default is HLSSeekMode.ACCURATE_SEEK.
*/
public static var seekMode : String = HLSSeekMode.ACCURATE_SEEK;
/** max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var keyLoadMaxRetry : int = -1;
/** keyLoadMaxRetryTimeout
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/** max nb of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var fragmentLoadMaxRetry : int = -1;
/** fragmentLoadMaxRetryTimeout
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var fragmentLoadMaxRetryTimeout : Number = 64000;
/**
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/** max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = -1;
/** manifestLoadMaxRetryTimeout
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*/
public static var startFromBitrate : Number = -1;
/** start level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
*/
public static var startFromLevel : Number = -1;
/** seek level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*/
public static var seekFromLevel : Number = -1;
/** use hardware video decoder :
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*/
public static var useHardwareVideoDecoder : Boolean = false;
/**
* Defines whether INFO level log messages will will appear in the console
* Default is true.
*/
public static var logInfo : Boolean = true;
/**
* Defines whether DEBUG level log messages will will appear in the console
* Default is false.
*/
public static var logDebug : Boolean = false;
/**
* Defines whether DEBUG2 level log messages will will appear in the console
* Default is false.
*/
public static var logDebug2 : Boolean = false;
/**
* Defines whether WARN level log messages will will appear in the console
* Default is true.
*/
public static var logWarn : Boolean = true;
/**
* Defines whether ERROR level log messages will will appear in the console
* Default is true.
*/
public static var logError : Boolean = true;
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // // /////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // // /////////////////////////////////
/**
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 120.
*/
public static var maxBufferLength : Number = 120;
/**
* Defines maximum back buffer length in seconds.
* (0 means infinite back buffering)
*
* Default is 30.
*/
public static var maxBackBufferLength : Number = 30;
/**
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3.
*/
public static var lowBufferLength : Number = 3;
/**
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
* HLSSeekMode.SEGMENT_SEEK - segment based seeking (seek to beginning of segment containing requested seek position)
*
* Default is HLSSeekMode.ACCURATE_SEEK.
*/
public static var seekMode : String = HLSSeekMode.ACCURATE_SEEK;
/** max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var keyLoadMaxRetry : int = -1;
/** keyLoadMaxRetryTimeout
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/** max nb of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var fragmentLoadMaxRetry : int = -1;
/** fragmentLoadMaxRetryTimeout
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var fragmentLoadMaxRetryTimeout : Number = 64000;
/**
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/** max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = -1;
/** manifestLoadMaxRetryTimeout
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*/
public static var startFromBitrate : Number = -1;
/** start level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
*/
public static var startFromLevel : Number = -1;
/** seek level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*/
public static var seekFromLevel : Number = -1;
/** use hardware video decoder :
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*/
public static var useHardwareVideoDecoder : Boolean = false;
/**
* Defines whether INFO level log messages will will appear in the console
* Default is true.
*/
public static var logInfo : Boolean = true;
/**
* Defines whether DEBUG level log messages will will appear in the console
* Default is false.
*/
public static var logDebug : Boolean = false;
/**
* Defines whether DEBUG2 level log messages will will appear in the console
* Default is false.
*/
public static var logDebug2 : Boolean = false;
/**
* Defines whether WARN level log messages will will appear in the console
* Default is true.
*/
public static var logWarn : Boolean = true;
/**
* Defines whether ERROR level log messages will will appear in the console
* Default is true.
*/
public static var logError : Boolean = true;
}
}
|
set max buffer len to 120s
|
set max buffer len to 120s
|
ActionScript
|
mpl-2.0
|
suuhas/flashls,viktorot/flashls,mangui/flashls,suuhas/flashls,Peer5/flashls,dighan/flashls,tedconf/flashls,viktorot/flashls,aevange/flashls,thdtjsdn/flashls,JulianPena/flashls,NicolasSiver/flashls,suuhas/flashls,jlacivita/flashls,Corey600/flashls,JulianPena/flashls,jlacivita/flashls,neilrackett/flashls,Peer5/flashls,viktorot/flashls,dighan/flashls,Peer5/flashls,School-Improvement-Network/flashls,Peer5/flashls,fixedmachine/flashls,hola/flashls,fixedmachine/flashls,Corey600/flashls,thdtjsdn/flashls,suuhas/flashls,vidible/vdb-flashls,loungelogic/flashls,School-Improvement-Network/flashls,vidible/vdb-flashls,School-Improvement-Network/flashls,Boxie5/flashls,clappr/flashls,NicolasSiver/flashls,aevange/flashls,clappr/flashls,mangui/flashls,tedconf/flashls,neilrackett/flashls,loungelogic/flashls,codex-corp/flashls,aevange/flashls,codex-corp/flashls,hola/flashls,Boxie5/flashls,aevange/flashls
|
092eaa653abd275293d6afb49528ba4d33913f1a
|
src/com/esri/viewer/utils/PortalBasemapAppender.as
|
src/com/esri/viewer/utils/PortalBasemapAppender.as
|
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010-2011 Esri. All Rights Reserved.
//
// Licensed 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 com.esri.viewer.utils
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.events.PortalEvent;
import com.esri.ags.portal.Portal;
import com.esri.ags.portal.supportClasses.PortalGroup;
import com.esri.ags.portal.supportClasses.PortalItem;
import com.esri.ags.portal.supportClasses.PortalQueryParameters;
import com.esri.ags.portal.supportClasses.PortalQueryResult;
import com.esri.viewer.AppEvent;
import com.esri.viewer.ConfigData;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.utils.Dictionary;
import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
import mx.utils.ObjectUtil;
public class PortalBasemapAppender extends EventDispatcher
{
private const PORTAL_BASEMAP_APPENDER:String = "PortalBasemapAppender";
private var configData:ConfigData;
private var portalURL:String;
private var portalItemOrder:Array;
private var portalItemToLabel:Dictionary;
private var processedArcGISBasemaps:Array;
private var totalBasemaps:int;
private var totalPossibleArcGISBasemaps:int;
private var comparableDefaultBasemapObjects:Array;
private var defaultBasemapTitle:String;
private var cultureCode:String;
public function PortalBasemapAppender(portalURL:String, configData:ConfigData)
{
this.portalURL = portalURL;
this.configData = configData;
}
public function fetchAndAppendPortalBasemaps():void
{
const idMgrEnabled:Boolean = IdentityManager.instance.enabled;
var portal:Portal = new Portal();
// the Portal constructor enables the IdentityManager so restore it back to what it was
IdentityManager.instance.enabled = idMgrEnabled;
portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);
cultureCode = toCultureCode(ResourceManager.getInstance().localeChain[0]);
portal.load(portalURL, cultureCode);
}
protected function portal_loadHandler(event:PortalEvent):void
{
var portal:Portal = event.target as Portal;
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
comparableDefaultBasemapObjects = getComparableBasemapObjects(portal.info.defaultBasemap);
var queryParams:PortalQueryParameters = PortalQueryParameters.forQuery(portal.info.basemapGalleryGroupQuery);
portal.queryGroups(queryParams, new AsyncResponder(portal_queryGroupsResultHandler, portal_queryGroupsFaultHandler, portal));
}
protected function portal_queryGroupsResultHandler(queryResult:PortalQueryResult, portal:Portal):void
{
if (queryResult.results.length > 0)
{
var portalGroup:PortalGroup = queryResult.results[0];
var queryParams:PortalQueryParameters = PortalQueryParameters.forItemsInGroup(portalGroup.id).withLimit(50).withSortField("name");
portal.queryItems(queryParams, new AsyncResponder(portal_queryItemsResultHandler, portal_queryItemsFaultHandler));
}
else
{
dispatchComplete();
}
}
private function portal_queryItemsResultHandler(queryResult:PortalQueryResult, token:Object = null):void
{
const resultItems:Array = queryResult.results;
totalPossibleArcGISBasemaps = resultItems.length;
portalItemOrder = [];
portalItemToLabel = new Dictionary(true);
processedArcGISBasemaps = [];
totalBasemaps = configData.basemaps.length;
for each (var portalItem:PortalItem in resultItems)
{
portalItemOrder.push(portalItem);
portalItem.getJSONData(new AsyncResponder(portalItem_getJSONDataResultHandler,
portalItem_getJSONDataFaultHandler,
portalItem));
}
}
private function portalItem_getJSONDataResultHandler(itemData:Object, item:PortalItem):void
{
createBasemapLayerObjectFromWebMapItemAndData(item, itemData);
if (isDefaultBasemap(itemData.baseMap))
{
defaultBasemapTitle = itemData.baseMap.title;
}
updateTotalArcGISBasemaps();
}
private function createBasemapLayerObjectFromWebMapItemAndData(item:PortalItem, itemData:Object):void
{
if (!itemData)
{
return;
}
var basemapObject:Object = itemData.baseMap;
var basemapLayerObjects:Array = basemapObject.baseMapLayers;
if (!(basemapObject && basemapLayerObjects))
{
return;
}
var title:String = basemapObject.title;
var iconURL:String = item.thumbnailURL;
var existingBasemapLayerObject:Object = findBasemapLayerObjectById(title);
if (existingBasemapLayerObject)
{
existingBasemapLayerObject.icon = iconURL;
return;
}
portalItemToLabel[item] = title;
var basemapLayerObject:Object = basemapLayerObjects[0];
addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
basemapLayerObject,
iconURL));
var totalBaseMapLayers:int = basemapLayerObjects.length;
if (totalBaseMapLayers > 1)
{
basemapLayerObject = basemapLayerObjects[1];
addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
basemapLayerObject,
iconURL));
}
}
private function isDefaultBasemap(basemapObject:Object):Boolean
{
var comparableBasemapObjects:Array = getComparableBasemapObjects(basemapObject);
return (ObjectUtil.compare(comparableBasemapObjects, comparableDefaultBasemapObjects) == 0);
}
private function getComparableBasemapObjects(basemapObject:Object):Array
{
var basemapLayerObjects:Array = basemapObject.baseMapLayers;
var comparableBasemapObjects:Array = [];
var comparableBasemapLayerObject:Object;
for each (var basemapLayerObject:Object in basemapLayerObjects)
{
comparableBasemapLayerObject = {};
if (basemapLayerObject.url)
{
comparableBasemapLayerObject.url = basemapLayerObject.url;
}
if (basemapLayerObject.type)
{
comparableBasemapLayerObject.type = basemapLayerObject.type;
}
comparableBasemapObjects.push(comparableBasemapLayerObject);
}
return comparableBasemapObjects;
}
private function findBasemapLayerObjectById(id:String):Object
{
var layerObjectResult:Object;
var basemapLayerObjects:Array = configData.basemaps;
for each (var layerObject:Object in basemapLayerObjects)
{
if (layerObject.layer && (layerObject.layer.id == id))
{
layerObjectResult = layerObject;
break;
}
}
return layerObjectResult;
}
private function updateTotalArcGISBasemaps():void
{
totalPossibleArcGISBasemaps--;
if (totalPossibleArcGISBasemaps == 0)
{
addArcGISBasemapsToConfig();
dispatchComplete();
}
}
private function dispatchComplete():void
{
dispatchEvent(new Event(Event.COMPLETE));
}
private function addArcGISBasemapsToConfig():void
{
var hasBasemaps:Boolean = (configData.basemaps.length > 0);
if (!hasBasemaps)
{
if (defaultBasemapTitle)
{
setDefaultBasemapVisible();
}
else
{
setFirstBasemapVisible();
}
}
addBasemapsInOrder();
}
private function setDefaultBasemapVisible():void
{
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (defaultBasemapTitle == layerObject.label)
{
layerObject.visible = true;
}
}
}
private function setFirstBasemapVisible():void
{
if (!portalItemOrder || portalItemOrder.length == 0)
{
return;
}
var firstBasemapLabel:String = portalItemToLabel[portalItemOrder[0]];
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (layerObject.label == firstBasemapLabel)
{
layerObject.visible = true;
}
}
}
private function addBasemapsInOrder():void
{
for each (var portalItem:PortalItem in portalItemOrder)
{
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (layerObject.label == portalItemToLabel[portalItem])
{
configData.basemaps.push(layerObject);
}
}
}
}
private function addBasemapLayerObject(layerXML:XML):void
{
if (layerXML)
{
processedArcGISBasemaps.push(LayerObjectUtil.getLayerObject(layerXML,
totalBasemaps++,
false,
configData.bingKey));
}
}
private function baseMapLayerObjectToLayerXML(title:String, basemapLayerObject:Object, iconURL:String = null):XML
{
var layerXML:XML;
const url:String = basemapLayerObject.url;
const type:String = basemapLayerObject.type;
if (url)
{
layerXML = createLayerXML(title, "tiled", iconURL, url, basemapLayerObject.opacity, false);
}
else if (isNonEsriType(type))
{
layerXML = createNonEsriLayerXML(title, iconURL, basemapLayerObject, false, type);
}
return layerXML;
}
private function createLayerXML(title:String, type:String, iconURL:String, url:String, alpha:Number, visible:Boolean):XML
{
return <layer label={title}
type={type}
icon={iconURL}
url={url}
alpha={alpha}
visible={visible}/>;
}
private function isNonEsriType(type:String):Boolean
{
return type == "OpenStreetMap" ||
(isBingBasemap(type) && hasBingKey());
}
private function createNonEsriLayerXML(title:String, iconURL:String, basemapLayerObject:Object, visible:Boolean, type:String):XML
{
var layerXML:XML = <layer label={title}
icon={iconURL}
type={toViewerNonEsriLayerType(basemapLayerObject.type)}
alpha={basemapLayerObject.opacity}
visible={visible}/>;
if (isBingBasemap(type))
{
layerXML.@style = mapBingStyleFromBasemapType(type);
layerXML.@culture = cultureCode;
}
return layerXML;
}
private function toViewerNonEsriLayerType(type:String):String
{
var viewerType:String;
if (type == "OpenStreetMap")
{
viewerType = "osm";
}
else if (isBingBasemap(type))
{
viewerType = "bing";
}
return viewerType;
}
private function isBingBasemap(type:String):Boolean
{
return type && type.indexOf('BingMaps') > -1;
}
private function hasBingKey():Boolean
{
var bingKey:String = configData.bingKey;
return (bingKey != null && bingKey.length > 0);
}
private function mapBingStyleFromBasemapType(type:String):String
{
if (type == 'BingMapsAerial')
{
return 'aerial';
}
else if (type == 'BingMapsHybrid')
{
return 'aerialWithLabels';
}
else
{
//default - BingMapsRoad
return 'road';
}
}
private function portalItem_getJSONDataFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.dispatch(AppEvent.APP_ERROR,
LocalizationUtil.getDefaultString("couldNotFetchBasemapData",
fault.faultString));
updateTotalArcGISBasemaps();
}
private function portal_queryGroupsFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortal"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function portal_queryItemsFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortalItems"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function portal_faultHandler(event:FaultEvent):void
{
var portal:Portal = event.target as Portal;
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotConnectToPortal"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function toCultureCode(locale:String):String
{
return locale ? locale.replace('_', '-') : locale;
}
}
}
|
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010-2011 Esri. All Rights Reserved.
//
// Licensed 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 com.esri.viewer.utils
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.events.PortalEvent;
import com.esri.ags.portal.Portal;
import com.esri.ags.portal.supportClasses.PortalGroup;
import com.esri.ags.portal.supportClasses.PortalItem;
import com.esri.ags.portal.supportClasses.PortalQueryParameters;
import com.esri.ags.portal.supportClasses.PortalQueryResult;
import com.esri.ags.tasks.JSONTask;
import com.esri.viewer.AppEvent;
import com.esri.viewer.ConfigData;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLVariables;
import flash.utils.Dictionary;
import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
import mx.utils.ObjectUtil;
public class PortalBasemapAppender extends EventDispatcher
{
private const PORTAL_BASEMAP_APPENDER:String = "PortalBasemapAppender";
private var configData:ConfigData;
private var portalURL:String;
private var portalItemOrder:Array;
private var portalItemToLabel:Dictionary;
private var processedArcGISBasemaps:Array;
private var totalBasemaps:int;
private var totalPossibleArcGISBasemaps:int;
private var comparableDefaultBasemapObjects:Array;
private var defaultBasemapTitle:String;
private var cultureCode:String;
public function PortalBasemapAppender(portalURL:String, configData:ConfigData)
{
this.portalURL = portalURL;
this.configData = configData;
}
public function fetchAndAppendPortalBasemaps():void
{
const idMgrEnabled:Boolean = IdentityManager.instance.enabled;
var portal:Portal = new Portal();
// the Portal constructor enables the IdentityManager so restore it back to what it was
IdentityManager.instance.enabled = idMgrEnabled;
portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);
cultureCode = toCultureCode(ResourceManager.getInstance().localeChain[0]);
portal.load(portalURL, cultureCode);
}
protected function portal_loadHandler(event:PortalEvent):void
{
var portal:Portal = event.target as Portal;
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
comparableDefaultBasemapObjects = getComparableBasemapObjects(portal.info.defaultBasemap);
var queryParams:PortalQueryParameters = PortalQueryParameters.forQuery(portal.info.basemapGalleryGroupQuery);
portal.queryGroups(queryParams, new AsyncResponder(portal_queryGroupsResultHandler, portal_queryGroupsFaultHandler, portal));
}
protected function portal_queryGroupsResultHandler(queryResult:PortalQueryResult, portal:Portal):void
{
if (queryResult.results.length > 0)
{
var portalGroup:PortalGroup = queryResult.results[0];
var queryParams:PortalQueryParameters = PortalQueryParameters.forItemsInGroup(portalGroup.id).withLimit(50).withSortField("name");
portal.queryItems(queryParams, new AsyncResponder(portal_queryItemsResultHandler, portal_queryItemsFaultHandler));
}
else
{
dispatchComplete();
}
}
private function portal_queryItemsResultHandler(queryResult:PortalQueryResult, token:Object = null):void
{
const resultItems:Array = queryResult.results;
totalPossibleArcGISBasemaps = resultItems.length;
portalItemOrder = [];
portalItemToLabel = new Dictionary(true);
processedArcGISBasemaps = [];
totalBasemaps = configData.basemaps.length;
for each (var item:PortalItem in resultItems)
{
processPortalItem(item);
}
}
private function processPortalItem(item:PortalItem):void
{
if (item.type == PortalItem.TYPE_WEB_MAP)
{
portalItemOrder.push(item);
processWebMapPortalItem(item);
}
else if (item.type == PortalItem.TYPE_MAP_SERVICE)
{
portalItemOrder.push(item);
processMapServicePortalItem(item);
}
else
{
updateTotalArcGISBasemaps();
}
}
private function processWebMapPortalItem(item:PortalItem):void
{
item.getJSONData(new AsyncResponder(item_getJSONDataResultHandler,
item_getJSONDataFaultHandler,
item));
}
private function item_getJSONDataResultHandler(itemData:Object, item:PortalItem):void
{
createBasemapLayerObjectFromWebMapItemAndData(item, itemData);
if (isDefaultBasemap(itemData.baseMap))
{
defaultBasemapTitle = itemData.baseMap.title;
}
updateTotalArcGISBasemaps();
}
private function createBasemapLayerObjectFromWebMapItemAndData(item:PortalItem, itemData:Object):void
{
if (!itemData)
{
return;
}
var basemapObject:Object = itemData.baseMap;
var basemapLayerObjects:Array = basemapObject.baseMapLayers;
if (!(basemapObject && basemapLayerObjects))
{
return;
}
var title:String = basemapObject.title;
var iconURL:String = item.thumbnailURL;
var existingBasemapLayerObject:Object = findBasemapLayerObjectById(title);
if (existingBasemapLayerObject)
{
existingBasemapLayerObject.icon = iconURL;
return;
}
portalItemToLabel[item] = title;
var basemapLayerObject:Object = basemapLayerObjects[0];
addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
basemapLayerObject,
iconURL));
var totalBaseMapLayers:int = basemapLayerObjects.length;
if (totalBaseMapLayers > 1)
{
basemapLayerObject = basemapLayerObjects[1];
addBasemapLayerObject(baseMapLayerObjectToLayerXML(title,
basemapLayerObject,
iconURL));
}
}
private function isDefaultBasemap(basemapObject:Object):Boolean
{
var comparableBasemapObjects:Array = getComparableBasemapObjects(basemapObject);
return (ObjectUtil.compare(comparableBasemapObjects, comparableDefaultBasemapObjects) == 0);
}
private function getComparableBasemapObjects(basemapObject:Object):Array
{
var basemapLayerObjects:Array = basemapObject.baseMapLayers;
var comparableBasemapObjects:Array = [];
var comparableBasemapLayerObject:Object;
for each (var basemapLayerObject:Object in basemapLayerObjects)
{
comparableBasemapLayerObject = {};
if (basemapLayerObject.url)
{
comparableBasemapLayerObject.url = basemapLayerObject.url;
}
if (basemapLayerObject.type)
{
comparableBasemapLayerObject.type = basemapLayerObject.type;
}
comparableBasemapObjects.push(comparableBasemapLayerObject);
}
return comparableBasemapObjects;
}
private function findBasemapLayerObjectById(id:String):Object
{
var layerObjectResult:Object;
var basemapLayerObjects:Array = configData.basemaps;
for each (var layerObject:Object in basemapLayerObjects)
{
if (layerObject.layer && (layerObject.layer.id == id))
{
layerObjectResult = layerObject;
break;
}
}
return layerObjectResult;
}
private function updateTotalArcGISBasemaps():void
{
totalPossibleArcGISBasemaps--;
if (totalPossibleArcGISBasemaps == 0)
{
addArcGISBasemapsToConfig();
dispatchComplete();
}
}
private function dispatchComplete():void
{
dispatchEvent(new Event(Event.COMPLETE));
}
private function addArcGISBasemapsToConfig():void
{
var hasBasemaps:Boolean = (configData.basemaps.length > 0);
if (!hasBasemaps)
{
if (defaultBasemapTitle)
{
setDefaultBasemapVisible();
}
else
{
setFirstBasemapVisible();
}
}
addBasemapsInOrder();
}
private function setDefaultBasemapVisible():void
{
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (defaultBasemapTitle == layerObject.label)
{
layerObject.visible = true;
}
}
}
private function setFirstBasemapVisible():void
{
if (!portalItemOrder || portalItemOrder.length == 0)
{
return;
}
var firstBasemapLabel:String = portalItemToLabel[portalItemOrder[0]];
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (layerObject.label == firstBasemapLabel)
{
layerObject.visible = true;
}
}
}
private function addBasemapsInOrder():void
{
for each (var portalItem:PortalItem in portalItemOrder)
{
for each (var layerObject:Object in processedArcGISBasemaps)
{
if (layerObject.label == portalItemToLabel[portalItem])
{
configData.basemaps.push(layerObject);
}
}
}
}
private function addBasemapLayerObject(layerXML:XML):void
{
if (layerXML)
{
processedArcGISBasemaps.push(LayerObjectUtil.getLayerObject(layerXML,
totalBasemaps++,
false,
configData.bingKey));
}
}
private function baseMapLayerObjectToLayerXML(title:String, basemapLayerObject:Object, iconURL:String = null):XML
{
var layerXML:XML;
const url:String = basemapLayerObject.url;
const type:String = basemapLayerObject.type;
if (url)
{
layerXML = createLayerXML(title, "tiled", iconURL, url, basemapLayerObject.opacity, false);
}
else if (isNonEsriType(type))
{
layerXML = createNonEsriLayerXML(title, iconURL, basemapLayerObject, false, type);
}
return layerXML;
}
private function createLayerXML(title:String, type:String, iconURL:String, url:String, alpha:Number, visible:Boolean):XML
{
return <layer label={title}
type={type}
icon={iconURL}
url={url}
alpha={alpha}
visible={visible}/>;
}
private function isNonEsriType(type:String):Boolean
{
return type == "OpenStreetMap" ||
(isBingBasemap(type) && hasBingKey());
}
private function createNonEsriLayerXML(title:String, iconURL:String, basemapLayerObject:Object, visible:Boolean, type:String):XML
{
var layerXML:XML = <layer label={title}
icon={iconURL}
type={toViewerNonEsriLayerType(basemapLayerObject.type)}
alpha={basemapLayerObject.opacity}
visible={visible}/>;
if (isBingBasemap(type))
{
layerXML.@style = mapBingStyleFromBasemapType(type);
layerXML.@culture = cultureCode;
}
return layerXML;
}
private function toViewerNonEsriLayerType(type:String):String
{
var viewerType:String;
if (type == "OpenStreetMap")
{
viewerType = "osm";
}
else if (isBingBasemap(type))
{
viewerType = "bing";
}
return viewerType;
}
private function isBingBasemap(type:String):Boolean
{
return type && type.indexOf('BingMaps') > -1;
}
private function hasBingKey():Boolean
{
var bingKey:String = configData.bingKey;
return (bingKey != null && bingKey.length > 0);
}
private function mapBingStyleFromBasemapType(type:String):String
{
if (type == 'BingMapsAerial')
{
return 'aerial';
}
else if (type == 'BingMapsHybrid')
{
return 'aerialWithLabels';
}
else
{
//default - BingMapsRoad
return 'road';
}
}
private function item_getJSONDataFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.dispatch(AppEvent.APP_ERROR,
LocalizationUtil.getDefaultString("couldNotFetchBasemapData",
fault.faultString));
updateTotalArcGISBasemaps();
}
private function processMapServicePortalItem(item:PortalItem):void
{
const urlVars:URLVariables = new URLVariables();
urlVars.f = "json";
var mapServiceMetadataRequest:JSONTask = new JSONTask(item.url);
mapServiceMetadataRequest.execute(
urlVars, new AsyncResponder(mapServiceRequest_resultHandler,
mapServiceRequest_faultHandler,
item));
}
private function mapServiceRequest_resultHandler(serviceMetadata:Object, item:PortalItem):void
{
createBasemapLayerObjectFromMapServiceItemAndData(item, serviceMetadata);
updateTotalArcGISBasemaps();
}
private function createBasemapLayerObjectFromMapServiceItemAndData(item:PortalItem, serviceMetadata:Object):void
{
if (!serviceMetadata)
{
return;
}
var layerType:String = getLayerType(serviceMetadata, item);
if (!layerType)
{
return;
}
var title:String = item.title;
var iconURL:String = item.thumbnailURL;
var existingBasemapLayerObject:Object = findBasemapLayerObjectById(title);
if (existingBasemapLayerObject)
{
existingBasemapLayerObject.icon = iconURL;
return;
}
portalItemToLabel[item] = title;
addBasemapLayerObject(mapServicePortalItemToLayerXML(item, layerType));
}
private function getLayerType(serviceMetadata:Object, item:PortalItem):String
{
var layerType:String;
if (serviceMetadata.singleFusedMapCache)
{
layerType = "tiled";
}
else if (serviceMetadata.bandCount)
{
layerType = "image";
}
else if (isNaN(Number(item.url.charAt(item.url.length - 1))))
{
layerType = "dynamic";
}
else
{
layerType = "feature";
}
return layerType;
}
private function mapServicePortalItemToLayerXML(item:PortalItem, type:String):XML
{
const title:String = item.title;
const iconURL:String = item.thumbnailURL;
const url:String = item.url;
return createLayerXML(title, type, iconURL, url, 1, false);
}
private function mapServiceRequest_faultHandler(fault:Fault, token:Object = null):void
{
if (fault.faultString != "Sign in aborted")
{
AppEvent.dispatch(AppEvent.APP_ERROR,
LocalizationUtil.getDefaultString("couldNotFetchBasemapData",
fault.faultString));
}
updateTotalArcGISBasemaps();
}
private function portal_queryGroupsFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortal"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function portal_queryItemsFaultHandler(fault:Fault, token:Object = null):void
{
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotQueryPortalItems"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function portal_faultHandler(event:FaultEvent):void
{
var portal:Portal = event.target as Portal;
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
AppEvent.showError(LocalizationUtil.getDefaultString("couldNotConnectToPortal"), PORTAL_BASEMAP_APPENDER);
dispatchComplete();
}
private function toCultureCode(locale:String):String
{
return locale ? locale.replace('_', '-') : locale;
}
}
}
|
Support appending basemaps from Portal map-service items.
|
Support appending basemaps from Portal map-service items.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-flex,Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex
|
608ab00bba68c3e6bdeb39d0acf92055062ca188
|
src/org/mangui/osmf/plugins/traits/HLSAlternativeAudioTrait.as
|
src/org/mangui/osmf/plugins/traits/HLSAlternativeAudioTrait.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.osmf.plugins.traits {
import org.mangui.hls.HLS;
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.event.HLSEvent;
import org.osmf.events.AlternativeAudioEvent;
import org.osmf.media.MediaElement;
import org.osmf.net.StreamingItem;
import org.osmf.traits.AlternativeAudioTrait;
import org.osmf.utils.OSMFStrings;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSAlternativeAudioTrait extends AlternativeAudioTrait {
private var _hls : HLS;
private var _media : MediaElement;
private var _audioTrackList : Vector.<AudioTrack>;
private var _numAlternativeAudioStreams : int;
private var _transitionInProgress : Boolean = false;
private var _activeTransitionIndex : int = DEFAULT_TRANSITION_INDEX;
private var _lastTransitionIndex : int = INVALID_TRANSITION_INDEX;
public function HLSAlternativeAudioTrait(hls : HLS, media : MediaElement) {
CONFIG::LOGGING {
Log.debug("HLSAlternativeAudioTrait()");
}
super(0);
_hls = hls;
_audioTrackList = _hls.audioTracks;
_numAlternativeAudioStreams = _audioTrackList.length - 1;
_media = media;
_hls.addEventListener(HLSEvent.AUDIO_TRACK_SWITCH, _audioTrackChangedHandler);
_hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTrackListChangedHandler);
}
override public function dispose() : void {
CONFIG::LOGGING {
Log.debug("HLSAlternativeAudioTrait:dispose");
}
_hls.removeEventListener(HLSEvent.AUDIO_TRACK_SWITCH, _audioTrackChangedHandler);
_hls.removeEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTrackListChangedHandler);
super.dispose();
}
override public function get numAlternativeAudioStreams() : int {
CONFIG::LOGGING {
Log.debug("HLSAlternativeAudioTrait:numAlternativeAudioStreams:" + _numAlternativeAudioStreams);
}
return _numAlternativeAudioStreams;
}
override public function getItemForIndex(index : int) : StreamingItem {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:getItemForIndex(" + index + ")");
}
if (index <= INVALID_TRANSITION_INDEX || index >= numAlternativeAudioStreams) {
throw new RangeError(OSMFStrings.getString(OSMFStrings.ALTERNATIVEAUDIO_INVALID_INDEX));
}
if (index == DEFAULT_TRANSITION_INDEX) {
return null;
}
var name : String = _audioTrackList[index + 1].title;
var streamItem : StreamingItem = new StreamingItem("AUDIO", name);
streamItem.info.label = name;
return streamItem;
}
override protected function endSwitching(index : int) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:endSwitching(" + index + ")");
}
if (switching) {
executeSwitching(_indexToSwitchTo);
}
super.endSwitching(index);
}
protected function executeSwitching(indexToSwitchTo : int) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:executeSwitching(" + indexToSwitchTo + ")");
}
if (_lastTransitionIndex != indexToSwitchTo) {
_activeTransitionIndex = indexToSwitchTo;
_transitionInProgress = true;
_hls.audioTrack = indexToSwitchTo + 1;
}
}
private function _audioTrackChangedHandler(event : HLSEvent) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:_audioTrackChangedHandler");
}
_transitionInProgress = false;
setSwitching(false, _lastTransitionIndex);
}
private function _audioTrackListChangedHandler(event : HLSEvent) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:_audioTrackListChangedHandler");
}
_audioTrackList = _hls.audioTracks;
if (_audioTrackList.length > 0) {
// try to change default Audio Track Title for GrindPlayer ...
if (_audioTrackList[0].title.indexOf("TS/") == -1) {
CONFIG::LOGGING {
Log.debug("default audio track title:" + _audioTrackList[0].title);
}
_media.resource.addMetadataValue("defaultAudioLabel", _audioTrackList[0].title);
}
}
_numAlternativeAudioStreams = _audioTrackList.length - 1;
if (_numAlternativeAudioStreams > 0) {
dispatchEvent(new AlternativeAudioEvent(AlternativeAudioEvent.NUM_ALTERNATIVE_AUDIO_STREAMS_CHANGE, false, false, false));
}
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.osmf.plugins.traits {
import org.mangui.hls.HLS;
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.event.HLSEvent;
import org.osmf.events.AlternativeAudioEvent;
import org.osmf.media.MediaElement;
import org.osmf.net.StreamingItem;
import org.osmf.traits.AlternativeAudioTrait;
import org.osmf.utils.OSMFStrings;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSAlternativeAudioTrait extends AlternativeAudioTrait {
private var _hls : HLS;
private var _media : MediaElement;
private var _audioTrackList : Vector.<AudioTrack>;
private var _numAlternativeAudioStreams : int;
private var _activeTransitionIndex : int = DEFAULT_TRANSITION_INDEX;
private var _lastTransitionIndex : int = INVALID_TRANSITION_INDEX;
public function HLSAlternativeAudioTrait(hls : HLS, media : MediaElement) {
CONFIG::LOGGING {
Log.debug("HLSAlternativeAudioTrait()");
}
_hls = hls;
_audioTrackList = _hls.audioTracks;
_numAlternativeAudioStreams = _audioTrackList.length - 1;
super(_numAlternativeAudioStreams);
_media = media;
_hls.addEventListener(HLSEvent.AUDIO_TRACK_SWITCH, _audioTrackChangedHandler);
_hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTrackListChangedHandler);
}
override public function dispose() : void {
CONFIG::LOGGING {
Log.debug("HLSAlternativeAudioTrait:dispose");
}
_hls.removeEventListener(HLSEvent.AUDIO_TRACK_SWITCH, _audioTrackChangedHandler);
_hls.removeEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTrackListChangedHandler);
super.dispose();
}
override public function get numAlternativeAudioStreams() : int {
CONFIG::LOGGING {
Log.debug("HLSAlternativeAudioTrait:numAlternativeAudioStreams:" + _numAlternativeAudioStreams);
}
return _numAlternativeAudioStreams;
}
override public function getItemForIndex(index : int) : StreamingItem {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:getItemForIndex(" + index + ")");
}
if (index <= INVALID_TRANSITION_INDEX || index >= numAlternativeAudioStreams) {
throw new RangeError(OSMFStrings.getString(OSMFStrings.ALTERNATIVEAUDIO_INVALID_INDEX));
}
if (index == DEFAULT_TRANSITION_INDEX) {
return null;
}
var name : String = _audioTrackList[index + 1].title;
var streamItem : StreamingItem = new StreamingItem("AUDIO", name);
streamItem.info.label = name;
return streamItem;
}
override protected function endSwitching(index : int) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:endSwitching(" + index + ")");
}
if (switching) {
executeSwitching(_indexToSwitchTo);
}
super.endSwitching(index);
}
protected function executeSwitching(indexToSwitchTo : int) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:executeSwitching(" + indexToSwitchTo + ")");
}
if (_lastTransitionIndex != indexToSwitchTo) {
_activeTransitionIndex = indexToSwitchTo;
_hls.audioTrack = indexToSwitchTo + 1;
}
}
private function _audioTrackChangedHandler(event : HLSEvent) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:_audioTrackChangedHandler");
}
setSwitching(false, _activeTransitionIndex);
_lastTransitionIndex = _activeTransitionIndex;
}
private function _audioTrackListChangedHandler(event : HLSEvent) : void {
CONFIG::LOGGING {
Log.debug("HLSDynamicStreamTrait:_audioTrackListChangedHandler");
}
_audioTrackList = _hls.audioTracks;
if (_audioTrackList.length > 0) {
// try to change default Audio Track Title for GrindPlayer ...
if (_audioTrackList[0].title.indexOf("TS/") == -1) {
CONFIG::LOGGING {
Log.debug("default audio track title:" + _audioTrackList[0].title);
}
_media.resource.addMetadataValue("defaultAudioLabel", _audioTrackList[0].title);
}
}
_numAlternativeAudioStreams = _audioTrackList.length - 1;
if (_numAlternativeAudioStreams > 0) {
dispatchEvent(new AlternativeAudioEvent(AlternativeAudioEvent.NUM_ALTERNATIVE_AUDIO_STREAMS_CHANGE, false, false, false));
}
}
}
}
|
fix AlternativeAudioTrait reporting invalid stream index related to #6
|
flashlsOSMF: fix AlternativeAudioTrait reporting invalid stream index
related to #6
|
ActionScript
|
mpl-2.0
|
Corey600/flashls,NicolasSiver/flashls,hola/flashls,suuhas/flashls,clappr/flashls,thdtjsdn/flashls,Peer5/flashls,aevange/flashls,Corey600/flashls,mangui/flashls,jlacivita/flashls,codex-corp/flashls,tedconf/flashls,aevange/flashls,JulianPena/flashls,NicolasSiver/flashls,suuhas/flashls,JulianPena/flashls,Peer5/flashls,vidible/vdb-flashls,aevange/flashls,aevange/flashls,suuhas/flashls,hola/flashls,codex-corp/flashls,dighan/flashls,dighan/flashls,fixedmachine/flashls,neilrackett/flashls,Boxie5/flashls,Peer5/flashls,neilrackett/flashls,loungelogic/flashls,thdtjsdn/flashls,vidible/vdb-flashls,loungelogic/flashls,jlacivita/flashls,Peer5/flashls,clappr/flashls,suuhas/flashls,Boxie5/flashls,tedconf/flashls,mangui/flashls,fixedmachine/flashls
|
948040a323126de9ad3494601ade4ff74ef4bc70
|
krew-framework/krewfw/builtin_actor/system/KrewStateMachine.as
|
krew-framework/krewfw/builtin_actor/system/KrewStateMachine.as
|
package krewfw.builtin_actor.system {
import flash.utils.Dictionary;
import krewfw.core.KrewActor;
/**
* Hierarchical Finite State Machine for krewFramework.
*
* [Note] 後から動的に登録 State を変えるような使い方は想定していない。
* addState はあるが removeState のインタフェースは用意していない。
*
* また、現状 KrewStateMachine に addState を行った後の state に
* sub state を足すような書き方にも対応していない。
* KrewStateMachine のコンストラクタで一度に定義してしまうことを推奨する。
*/
//------------------------------------------------------------
public class KrewStateMachine extends KrewActor {
/** If trace log is annoying you, set it false. */
public static var VERBOSE:Boolean = true;
// key : state id
// value: KrewState instance
private var _states:Dictionary = new Dictionary();
// States with constructor argument order. Used for default 'next' settings.
private var _rootStateList:Vector.<KrewState> = new Vector.<KrewState>();
private var _currentState:KrewState;
private var _listenMap:Dictionary = new Dictionary();
//------------------------------------------------------------
/**
* Usage:
* <pre>
* var fsm:KrewStateMachine = new KrewStateMachine([
* {
* id: "state_1", // First element will be an initial state.
* enter: onEnterFunc,
* next: "state_2" // Default next state is next element of this Array.
* },
*
* new YourCustomState(), // Instead of Object, KrewState instance is OK.
*
* {
* id: "state_2",
* children: [ // State can contain sub States.
* { id: "state_2_a" },
* { id: "state_2_b" },
* {
* id : "state_2_c",
* listen: {event: "event_1", to: "state_4"},
* guard : guardFunc
* },
* {
* id: "state_2_d",
* listen: [ // Array is also OK.
* {event: "event_2", to: "state_1"},
* {event: "event_3", to: "state_2"}
* ]
* }
* ]
* },
* {
* id: "state_3",
* listen: {event: "event_1", to: "state_4"}
* },
* ...
* ]);
* </pre>
*
* @param stateDefList Array of KrewState instances or definition objects.
* @param funcOwner If you speciify functions with name string, pass function-owner object.
*/
public function KrewStateMachine(stateDefList:Array=null, funcOwner:Object=null) {
displayable = false;
_initStates(stateDefList, funcOwner);
}
private function _initStates(stateDefList:Array, funcOwner:Object=null):void {
// guard
if (stateDefList == null) { return; }
if (!(stateDefList is Array)) {
throw new Error("[KrewFSM] Constructor argument must be Array.");
}
if (stateDefList.length == 0) { return; }
// do init
addInitializer(function():void {
for each (var stateDef:* in stateDefList) {
addState(stateDef, funcOwner);
}
_setDefaultNextStates(_rootStateList);
_setInitialState(stateDefList);
});
}
private function _setInitialState(stateDefList:Array):void {
var firstDef:* = stateDefList[0];
var initStateId:String;
if (firstDef is KrewState) {
initStateId = firstDef.stateId;
}
else if (firstDef is Object) {
initStateId = firstDef.id;
}
else {
throw new Error("[KrewFSM] Invalid first stateDef.");
}
changeState(initStateId);
}
/**
* next が指定されていない state について、コンストラクタで渡した定義で
* 上から下になぞるように next を設定していく。
* この関数は再帰で、ツリーの末端の子 state を返す
*/
private function _setDefaultNextStates(stateList:Vector.<KrewState>):KrewState {
if (stateList.length == 0) { return null; }
for (var i:int = 0; i < stateList.length; ++i) {
var state:KrewState = stateList[i];
if (state.nextStateId == null) {
if (state.hasChildren()) {
state.nextStateId = state.childStates[0].stateId;
}
else if (i + 1 <= stateList.length - 1) {
state.nextStateId = stateList[i + 1].stateId;
}
}
if (state.hasChildren()) {
var edgeState:KrewState = _setDefaultNextStates(state.childStates);
if (edgeState.nextStateId == null) {
if (i + 1 <= stateList.length - 1) {
edgeState.nextStateId = stateList[i + 1].stateId;
} else {
return edgeState;
}
}
}
}
var edgeState:KrewState = krew.last(stateList);
if (!edgeState.hasParent()) { return null; }
return edgeState;
}
protected override function onDispose():void {
for each (var state:KrewState in _states) {
state.eachChild(function(childState:KrewState):void {
childState.dispose();
});
}
_states = null;
_rootStateList = null;
_currentState = null;
_listenMap = null;
}
//------------------------------------------------------------
// public
//------------------------------------------------------------
/**
* @see KrewState.addState
*/
public function addState(stateDef:*, funcOwner:Object=null):void {
var state:KrewState = KrewState.makeState(stateDef, funcOwner);
_registerStateTree(state);
_rootStateList.push(state);
}
public function changeState(stateId:String):void {
if (!_states[stateId]) {
throw new Error("[KrewFSM] stateId not registered: " + stateId);
}
var oldStateId:String = "null";
var oldState:KrewState = _currentState;
var newState:KrewState = _states[stateId];
// Good bye old state
if (_currentState != null) {
oldStateId = _currentState.stateId;
oldState.exit();
oldState.end(newState);
}
_log("[Info] [KrewFSM] SWITCHED: " + newState.stateId + " <- " + oldStateId);
// Hello new state
_currentState = newState;
newState.begin(oldState);
newState.enter();
}
/**
* If given state is current state OR parent of current state, return true.
* For example, when current state is "A-sub", and it is child state of "A",
* both isState("A-sub") and isState("A") returns true.
*
* 現在の state が指定したものか、指定したものの子 state なら true を返す。
* 例えば現在の state "A-sub" が "A" の子 state であるとき、isState("A-sub") でも
* isState("A") でも true が返る。
*/
public function isState(stateName:String):Boolean {
if (_currentState.stateId == stateName) { return true; }
var stateIter:KrewState = _currentState;
while (stateIter.hasParent()) {
stateIter = stateIter.parentState;
if (stateIter.stateId == stateName) { return true; }
}
return false;
}
public function getState(stateId:String):KrewState {
if (!_states[stateId]) {
throw new Error("[KrewFSM] stateId not registered: " + stateId);
}
return _states[stateId];
}
public function get currentState():KrewState {
return _currentState;
}
//------------------------------------------------------------
// called by KrewState
//------------------------------------------------------------
public function listenToStateEvent(event:String):void {
if (_listenMap[event]) { return; } // already listening by other state
listen(event, function(args:Object):void {
_onEvent(args, event);
})
_listenMap[event] = true;
}
public function stopListeningToStateEvent(event:String):void {
if (!_listenMap[event]) { return; } // already stopped by other state
stopListening(event);
_listenMap[event] = false;
}
//------------------------------------------------------------
// called by krewFramework
//------------------------------------------------------------
public override function onUpdate(passedTime:Number):void {
if (_currentState == null) { return; }
_currentState.eachParent(function(state:KrewState):void {
if (state.onUpdateHandler == null) { return; }
state.onUpdateHandler(state, passedTime);
});
}
//------------------------------------------------------------
// private
//------------------------------------------------------------
private function _onEvent(args:Object, event:String):void {
_currentState.onEvent(args, event);
}
/**
* State を、子を含めて全て Dictionary に保持
* (State は Composite Pattern で sub state を子に持てる)
*/
private function _registerStateTree(state:KrewState):void {
state.eachChild(function(aState:KrewState):void {
_registerState(aState);
});
}
// State 1 個ぶんを Dictionary に保持
private function _registerState(state:KrewState):void {
if (_states[state.stateId]) {
throw new Error("[KrewFSM] stateId already registered: " + state.stateId);
}
_states[state.stateId] = state;
state.stateMachine = this;
}
//------------------------------------------------------------
// debug method
//------------------------------------------------------------
private function _log(text:String):void {
if (!VERBOSE) { return; }
krew.fwlog(text);
}
public function dumpDictionary():void {
krew.log(krew.str.repeat("-", 50));
krew.log(" KrewStateMachine state dictionary dump");
krew.log(krew.str.repeat("-", 50));
for each(var state:KrewState in _states) {
krew.log(" - " + state.stateId);
}
krew.log(krew.str.repeat("^", 50));
}
public function dumpDictionaryVerbose():void {
krew.log(krew.str.repeat("-", 50));
krew.log(" KrewStateMachine state dictionary dump -v");
krew.log(krew.str.repeat("-", 50));
for each(var state:KrewState in _states) {
state.dump();
}
}
public function dumpState(stateId:String):void {
_states[stateId].dump();
}
public function dumpStateTree():void {
krew.log(krew.str.repeat("-", 50));
krew.log(" KrewStateMachine state tree dump");
krew.log(krew.str.repeat("-", 50));
for each(var state:KrewState in _rootStateList) {
state.dumpTree();
}
krew.log(krew.str.repeat("^", 50));
}
}
}
|
package krewfw.builtin_actor.system {
import flash.utils.Dictionary;
import krewfw.core.KrewActor;
/**
* Hierarchical Finite State Machine for krewFramework.
*
* [Note] 後から動的に登録 State を変えるような使い方は想定していない。
* addState はあるが removeState のインタフェースは用意していない。
*
* また、現状 KrewStateMachine に addState を行った後の state に
* sub state を足すような書き方にも対応していない。
* KrewStateMachine のコンストラクタで一度に定義してしまうことを推奨する。
*/
//------------------------------------------------------------
public class KrewStateMachine extends KrewActor {
/** If trace log is annoying you, set it false. */
public static var VERBOSE:Boolean = true;
// key : state id
// value: KrewState instance
private var _states:Dictionary = new Dictionary();
// States with constructor argument order. Used for default 'next' settings.
private var _rootStateList:Vector.<KrewState> = new Vector.<KrewState>();
private var _currentState:KrewState;
private var _listenMap:Dictionary = new Dictionary();
//------------------------------------------------------------
/**
* Usage:
* <pre>
* var fsm:KrewStateMachine = new KrewStateMachine([
* {
* id: "state_1", // First element will be an initial state.
* enter: onEnterFunc,
* next: "state_2" // Default next state is next element of this Array.
* },
*
* new YourCustomState(), // Instead of Object, KrewState instance is OK.
*
* {
* id: "state_2",
* children: [ // State can contain sub States.
* { id: "state_2_a" },
* { id: "state_2_b" },
* {
* id : "state_2_c",
* listen: {event: "event_1", to: "state_4"},
* guard : guardFunc
* },
* {
* id: "state_2_d",
* listen: [ // Array is also OK.
* {event: "event_2", to: "state_1"},
* {event: "event_3", to: "state_2"}
* ]
* }
* ]
* },
* {
* id: "state_3",
* listen: {event: "event_1", to: "state_4"}
* },
* ...
* ]);
* </pre>
*
* @param stateDefList Array of KrewState instances or definition objects.
* @param funcOwner If you speciify functions with name string, pass function-owner object.
*/
public function KrewStateMachine(stateDefList:Array=null, funcOwner:Object=null) {
displayable = false;
_initStates(stateDefList, funcOwner);
}
private function _initStates(stateDefList:Array, funcOwner:Object=null):void {
// guard
if (stateDefList == null) { return; }
if (!(stateDefList is Array)) {
throw new Error("[KrewFSM] Constructor argument must be Array.");
}
if (stateDefList.length == 0) { return; }
// do init
addInitializer(function():void {
for each (var stateDef:* in stateDefList) {
addState(stateDef, funcOwner);
}
_setDefaultNextStates(_rootStateList);
_setInitialState(stateDefList);
});
}
private function _setInitialState(stateDefList:Array):void {
var firstDef:* = stateDefList[0];
var initStateId:String;
if (firstDef is KrewState) {
initStateId = firstDef.stateId;
}
else if (firstDef is Object) {
initStateId = firstDef.id;
}
else {
throw new Error("[KrewFSM] Invalid first stateDef.");
}
changeState(initStateId);
}
/**
* next が指定されていない state について、コンストラクタで渡した定義で
* 上から下になぞるように next を設定していく。
* この関数は再帰で、ツリーの末端の子 state を返す
*/
private function _setDefaultNextStates(stateList:Vector.<KrewState>):KrewState {
if (stateList.length == 0) { return null; }
for (var i:int = 0; i < stateList.length; ++i) {
var state:KrewState = stateList[i];
if (state.nextStateId == null) {
if (state.hasChildren()) {
state.nextStateId = state.childStates[0].stateId;
}
else if (i + 1 <= stateList.length - 1) {
state.nextStateId = stateList[i + 1].stateId;
}
}
if (state.hasChildren()) {
var edgeState:KrewState = _setDefaultNextStates(state.childStates);
if (edgeState.nextStateId == null) {
if (i + 1 <= stateList.length - 1) {
edgeState.nextStateId = stateList[i + 1].stateId;
} else {
return edgeState;
}
}
}
}
var edgeState:KrewState = krew.last(stateList);
if (!edgeState.hasParent()) { return null; }
return edgeState;
}
protected override function onDispose():void {
for each (var state:KrewState in _states) {
state.eachChild(function(childState:KrewState):void {
childState.dispose();
});
}
_states = null;
_rootStateList = null;
_currentState = null;
_listenMap = null;
}
//------------------------------------------------------------
// public
//------------------------------------------------------------
/**
* @see KrewState.addState
*/
public function addState(stateDef:*, funcOwner:Object=null):void {
var state:KrewState = KrewState.makeState(stateDef, funcOwner);
_registerStateTree(state);
_rootStateList.push(state);
}
public function changeState(stateId:String):void {
if (!_states[stateId]) {
throw new Error("[KrewFSM] stateId not registered: " + stateId);
}
var oldStateId:String = "null";
var oldState:KrewState = _currentState;
var newState:KrewState = _states[stateId];
// Good bye old state
if (_currentState != null) {
oldStateId = _currentState.stateId;
oldState.exit();
oldState.end(newState);
}
_log("[Info] [KrewFSM] SWITCHED: " + newState.stateId + " <- " + oldStateId);
// Hello new state
_currentState = newState;
newState.begin(oldState);
newState.enter();
}
/**
* If given state is current state OR parent of current state, return true.
* For example, when current state is "A-sub", and it is child state of "A",
* both isState("A-sub") and isState("A") returns true.
*
* 現在の state が指定したものか、指定したものの子 state なら true を返す。
* 例えば現在の state "A-sub" が "A" の子 state であるとき、isState("A-sub") でも
* isState("A") でも true が返る。
*/
public function isState(stateName:String):Boolean {
if (_currentState.stateId == stateName) { return true; }
var stateIter:KrewState = _currentState;
while (stateIter.hasParent()) {
stateIter = stateIter.parentState;
if (stateIter.stateId == stateName) { return true; }
}
return false;
}
public function getState(stateId:String):KrewState {
if (!_states[stateId]) {
throw new Error("[KrewFSM] stateId not registered: " + stateId);
}
return _states[stateId];
}
public function get currentState():KrewState {
return _currentState;
}
//------------------------------------------------------------
// called by KrewState
//------------------------------------------------------------
public function listenToStateEvent(event:String):void {
if (_listenMap[event]) { return; } // already listening by other state
listen(event, function(args:Object):void {
_onEvent(args, event);
})
_listenMap[event] = true;
}
public function stopListeningToStateEvent(event:String):void {
if (!_listenMap[event]) { return; } // already stopped by other state
stopListening(event);
_listenMap[event] = false;
}
//------------------------------------------------------------
// called by krewFramework
//------------------------------------------------------------
public override function onUpdate(passedTime:Number):void {
if (_currentState == null) { return; }
_currentState.eachParent(function(state:KrewState):void {
if (state.onUpdateHandler == null) { return; }
state.onUpdateHandler(state, passedTime);
});
}
//------------------------------------------------------------
// private
//------------------------------------------------------------
private function _onEvent(args:Object, event:String):void {
_log("[Info] [KrewFSM] EVENT: " + event);
_currentState.onEvent(args, event);
}
/**
* State を、子を含めて全て Dictionary に保持
* (State は Composite Pattern で sub state を子に持てる)
*/
private function _registerStateTree(state:KrewState):void {
state.eachChild(function(aState:KrewState):void {
_registerState(aState);
});
}
// State 1 個ぶんを Dictionary に保持
private function _registerState(state:KrewState):void {
if (_states[state.stateId]) {
throw new Error("[KrewFSM] stateId already registered: " + state.stateId);
}
_states[state.stateId] = state;
state.stateMachine = this;
}
//------------------------------------------------------------
// debug method
//------------------------------------------------------------
private function _log(text:String):void {
if (!VERBOSE) { return; }
krew.fwlog(text);
}
public function dumpDictionary():void {
krew.log(krew.str.repeat("-", 50));
krew.log(" KrewStateMachine state dictionary dump");
krew.log(krew.str.repeat("-", 50));
for each(var state:KrewState in _states) {
krew.log(" - " + state.stateId);
}
krew.log(krew.str.repeat("^", 50));
}
public function dumpDictionaryVerbose():void {
krew.log(krew.str.repeat("-", 50));
krew.log(" KrewStateMachine state dictionary dump -v");
krew.log(krew.str.repeat("-", 50));
for each(var state:KrewState in _states) {
state.dump();
}
}
public function dumpState(stateId:String):void {
_states[stateId].dump();
}
public function dumpStateTree():void {
krew.log(krew.str.repeat("-", 50));
krew.log(" KrewStateMachine state tree dump");
krew.log(krew.str.repeat("-", 50));
for each(var state:KrewState in _rootStateList) {
state.dumpTree();
}
krew.log(krew.str.repeat("^", 50));
}
}
}
|
Add log to KrewStateMachine
|
Add log to KrewStateMachine
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
0436015ac7394c49edaba9f25dbf30ac220e56b8
|
frameworks/projects/mobiletheme/src/spark/skins/ios7/supportClasses/CalloutArrow.as
|
frameworks/projects/mobiletheme/src/spark/skins/ios7/supportClasses/CalloutArrow.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.skins.ios7.supportClasses
{
import flash.display.BlendMode;
import flash.display.GradientType;
import flash.display.Graphics;
import flash.display.GraphicsPathCommand;
import flash.display.Sprite;
import mx.core.DPIClassification;
import mx.core.FlexGlobals;
import mx.core.IVisualElement;
import mx.core.UIComponent;
import mx.core.mx_internal;
import mx.utils.ColorUtil;
import spark.components.Application;
import spark.components.ArrowDirection;
import spark.components.Callout;
import spark.skins.ios7.CalloutSkin;
import spark.skins.mobile.supportClasses.MobileSkin;
use namespace mx_internal;
/**
* The arrow skin part for CalloutSkin.
*
* @see spark.skin.mobile.CalloutSkin
*
* @langversion 3.0
* @playerversion AIR 3
* @productversion Flex 4.6
*/
public class CalloutArrow extends UIComponent
{
public function CalloutArrow()
{
super();
useBackgroundGradient = true;
var applicationDPI:Number = DPIClassification.DPI_160;
if (FlexGlobals.topLevelApplication is Application)
{
applicationDPI = Application(FlexGlobals.topLevelApplication).applicationDPI;
}
// Copy DPI-specific values from CalloutSkin
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
// Note provisional may need changes
gap = 32;
backgroundGradientHeight = 440;
highlightWeight = 4;
break;
}
case DPIClassification.DPI_480:
{
// Note provisional may need changes
gap = 24;
backgroundGradientHeight = 330;
highlightWeight = 3;
break;
}
case DPIClassification.DPI_320:
{
gap = 16;
backgroundGradientHeight = 220;
highlightWeight = 2;
break;
}
case DPIClassification.DPI_240:
{
gap = 12;
backgroundGradientHeight = 165;
highlightWeight = 1;
break;
}
case DPIClassification.DPI_120:
{
// Note provisional may need changes
gap = 6;
backgroundGradientHeight = 83;
highlightWeight = 1;
break;
}
default:
{
// default DPI_160
gap = 8;
backgroundGradientHeight = 110;
highlightWeight = 1;
break;
}
}
}
/**
* A gap on the frame-adjacent side of the arrow graphic to avoid
* drawing past the CalloutSkin backgroundCornerRadius.
*
* <p>The default implementation matches the gap value with the
* <code>backgroundCornerRadius</code> value in <code>CalloutSkin</code>.</p>
*
* @see spark.skins.mobile.CalloutSkin#backgroundCornerRadius
*
* @langversion 3.0
* @playerversion AIR 3
* @productversion Flex 4.6
*/
protected var gap:Number;
/**
* @copy spark.skins.mobile.CalloutSkin#backgroundGradientHeight
*/
protected var backgroundGradientHeight:Number;
/**
* @copy spark.skins.mobile.CalloutSkin#highlightWeight
*/
private var highlightWeight:Number;
/**
* @copy spark.skins.mobile.CalloutSkin#useBackgroundGradient
*/
protected var useBackgroundGradient:Boolean;
/**
* @copy spark.skins.mobile.CalloutSkin#borderColor
*/
protected var borderColor:Number = -1; // if not set
/**
* @copy spark.skins.mobile.CalloutSkin#borderThickness
*/
protected var borderThickness:Number = -1 ; // marker that borderThickness was not set directly
/**
* @private
* A sibling of the arrow used to erase the drop shadow in CalloutSkin
*/
private var eraseFill:Sprite;
/* helper private accessors */
/* returns borderThickness from style if member is -1, or borderThickness. Returns 0 if NaN */
private function get actualBorderThickness():Number
{
return calloutSkin.actualBorderThickness;
}
private function get actualBorderColor():uint
{
return calloutSkin.actualBorderColor;
}
protected function get calloutSkin():CalloutSkin
{
return parent as CalloutSkin ;
}
protected function get calloutHostComponent():Callout {
return calloutSkin.hostComponent;
}
/**
* @private
*/
override protected function createChildren():void
{
super.createChildren();
// eraseFill has the same position and arrow shape in order to erase
// the drop shadow under the arrow when backgroundAlpha < 1
eraseFill = new Sprite();
eraseFill.blendMode = BlendMode.ERASE;
// layer eraseFill below the arrow
parent.addChildAt(eraseFill, parent.getChildIndex(this));
}
/**
* @private
*/
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
graphics.clear();
eraseFill.graphics.clear();
var hostComponent: Callout = calloutHostComponent;
var arrowDirection:String = hostComponent.arrowDirection;
if (arrowDirection == ArrowDirection.NONE)
return;
// when drawing the arrow, compensate for cornerRadius via padding
var arrowGraphics:Graphics = this.graphics;
var eraseGraphics:Graphics = eraseFill.graphics;
var arrowWidth:Number = unscaledWidth;
var arrowHeight:Number = unscaledHeight;
var arrowX:Number = 0;
var arrowY:Number = 0;
var arrowTipX:Number = 0;
var arrowTipY:Number = 0;
var arrowEndX:Number = 0;
var arrowEndY:Number = 0;
var borderWeight:Number = actualBorderThickness;
var showBorder:Boolean = borderWeight > 0;
var borderHalf:Number = borderWeight / 2;
var isHorizontal:Boolean = false;
if ((arrowDirection == ArrowDirection.LEFT) ||
(arrowDirection == ArrowDirection.RIGHT))
{
isHorizontal = true;
arrowX = -borderHalf;
arrowY = gap;
arrowHeight = arrowHeight - (gap * 2);
arrowTipX = arrowWidth - borderHalf;
arrowTipY = arrowY + (arrowHeight / 2);
arrowEndX = arrowX;
arrowEndY = arrowY + arrowHeight;
// flip coordinates to point left
if (arrowDirection == ArrowDirection.LEFT)
{
arrowX = arrowWidth - arrowX;
arrowTipX = arrowWidth - arrowTipX;
arrowEndX = arrowWidth - arrowEndX;
}
}
else
{
arrowX = gap;
arrowY = -borderHalf;
arrowWidth = arrowWidth - (gap * 2);
arrowTipX = arrowX + (arrowWidth / 2);
arrowTipY = arrowHeight - borderHalf;
arrowEndX = arrowX + arrowWidth;
arrowEndY = arrowY;
// flip coordinates to point up
if (hostComponent.arrowDirection == ArrowDirection.UP)
{
arrowY = arrowHeight - arrowY;
arrowTipY = arrowHeight - arrowTipY;
arrowEndY = arrowHeight - arrowEndY;
}
}
var commands:Vector.<int> = new Vector.<int>(3, true);
commands[0] = GraphicsPathCommand.MOVE_TO;
commands[1] = GraphicsPathCommand.LINE_TO;
commands[2] = GraphicsPathCommand.LINE_TO;
var coords:Vector.<Number> = new Vector.<Number>(6, true);
coords[0] = arrowX;
coords[1] = arrowY;
coords[2] = arrowTipX
coords[3] = arrowTipY;
coords[4] = arrowEndX
coords[5] = arrowEndY;
var backgroundColor:Number = getStyle("backgroundColor");
var backgroundAlpha:Number = getStyle("backgroundAlpha");
if (useBackgroundGradient)
{
var backgroundColorTop:Number = ColorUtil.adjustBrightness2(backgroundColor,
CalloutSkin.BACKGROUND_GRADIENT_BRIGHTNESS_TOP);
var backgroundColorBottom:Number = ColorUtil.adjustBrightness2(backgroundColor,
CalloutSkin.BACKGROUND_GRADIENT_BRIGHTNESS_BOTTOM);
// translate the gradient based on the arrow position
MobileSkin.colorMatrix.createGradientBox(unscaledWidth,
backgroundGradientHeight, Math.PI / 2, 0, -getLayoutBoundsY());
arrowGraphics.beginGradientFill(GradientType.LINEAR,
[backgroundColorTop, backgroundColorBottom],
[backgroundAlpha, backgroundAlpha],
[0, 255],
MobileSkin.colorMatrix);
}
else
{
arrowGraphics.beginFill(backgroundColor, backgroundAlpha);
}
// cover the adjacent border from the callout frame
if (showBorder)
{
var coverX:Number = 0;
var coverY:Number = 0;
var coverWidth:Number = 0;
var coverHeight:Number = 0;
switch (arrowDirection)
{
case ArrowDirection.UP:
{
coverX = arrowX;
coverY = arrowY;
coverWidth = arrowWidth;
coverHeight = borderWeight;
break;
}
case ArrowDirection.DOWN:
{
coverX = arrowX;
coverY = -borderWeight;
coverWidth = arrowWidth;
coverHeight = borderWeight;
break;
}
case ArrowDirection.LEFT:
{
coverX = arrowX;
coverY = arrowY;
coverWidth = borderWeight;
coverHeight = arrowHeight;
break;
}
case ArrowDirection.RIGHT:
{
coverX = -borderWeight;
coverY = arrowY;
coverWidth = borderWeight;
coverHeight = arrowHeight;
break;
}
}
arrowGraphics.drawRect(coverX, coverY, coverWidth, coverHeight);
}
// erase the drop shadow from the CalloutSkin
if (backgroundAlpha < 1)
{
// move eraseFill to the same position as the arrow
eraseFill.x = getLayoutBoundsX()
eraseFill.y = getLayoutBoundsY();
// draw the arrow shape
eraseGraphics.beginFill(0, 1);
eraseGraphics.drawPath(commands, coords);
eraseGraphics.endFill();
}
// draw arrow path
if (showBorder)
arrowGraphics.lineStyle(borderWeight, actualBorderColor, 1, true);
arrowGraphics.drawPath(commands, coords);
arrowGraphics.endFill();
// adjust the highlight position to the origin of the callout
var isArrowUp:Boolean = (arrowDirection == ArrowDirection.UP);
var offsetY:Number = (isArrowUp) ? unscaledHeight : -getLayoutBoundsY();
// highlight starts after the backgroundCornerRadius
var highlightX:Number = gap - getLayoutBoundsX();
// highlight Y position is based on the stroke weight
var highlightOffset:Number = (highlightWeight * 1.5);
var highlightY:Number = highlightOffset + offsetY;
// highlight width spans the callout width minus the corner radius
var highlightWidth:Number = IVisualElement(calloutSkin).getLayoutBoundsWidth() - (gap * 2);
if (isHorizontal)
{
highlightWidth -= arrowWidth;
if (arrowDirection == ArrowDirection.LEFT)
highlightX += arrowWidth;
}
// highlight on the top edge is drawn in the arrow only in the UP direction
if (useBackgroundGradient)
{
if (isArrowUp)
{
// highlight follows the top edge, including the arrow
var rightWidth:Number = highlightWidth - arrowWidth;
// highlight style
arrowGraphics.lineStyle(highlightWeight, 0xFFFFFF, 0.2 * backgroundAlpha);
// in the arrow coordinate space, the highlightX must be less than 0
if (highlightX < 0)
{
arrowGraphics.moveTo(highlightX, highlightY);
arrowGraphics.lineTo(arrowX, highlightY);
// compute the remaining highlight
rightWidth -= (arrowX - highlightX);
}
// arrow highlight (adjust Y downward)
coords[1] = arrowY + highlightOffset;
coords[3] = arrowTipY + highlightOffset;
coords[5] = arrowEndY + highlightOffset;
arrowGraphics.drawPath(commands, coords);
// right side
if (rightWidth > 0)
{
arrowGraphics.moveTo(arrowEndX, highlightY);
arrowGraphics.lineTo(arrowEndX + rightWidth, highlightY);
}
}
else
{
// straight line across the top
arrowGraphics.lineStyle(highlightWeight, 0xFFFFFF, 0.2 * backgroundAlpha);
arrowGraphics.moveTo(highlightX, highlightY);
arrowGraphics.lineTo(highlightX + highlightWidth, highlightY);
}
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.skins.ios7.supportClasses
{
import flash.display.BlendMode;
import flash.display.GradientType;
import flash.display.Graphics;
import flash.display.GraphicsPathCommand;
import flash.display.Sprite;
import mx.core.DPIClassification;
import mx.core.FlexGlobals;
import mx.core.IVisualElement;
import mx.core.UIComponent;
import mx.core.mx_internal;
import mx.utils.ColorUtil;
import spark.components.Application;
import spark.components.ArrowDirection;
import spark.components.Callout;
import spark.skins.ios7.CalloutSkin;
import spark.skins.mobile.supportClasses.MobileSkin;
use namespace mx_internal;
/**
* The arrow skin part for CalloutSkin.
*
* @see spark.skin.mobile.CalloutSkin
*
* @langversion 3.0
* @playerversion AIR 3
* @productversion Flex 4.6
*/
public class CalloutArrow extends UIComponent
{
public function CalloutArrow()
{
super();
useBackgroundGradient = false;
var applicationDPI:Number = DPIClassification.DPI_160;
if (FlexGlobals.topLevelApplication is Application)
{
applicationDPI = Application(FlexGlobals.topLevelApplication).applicationDPI;
}
// Copy DPI-specific values from CalloutSkin
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
// Note provisional may need changes
gap = 32;
backgroundGradientHeight = 440;
highlightWeight = 4;
arrowTipCurveAnchorDistance = 12;
break;
}
case DPIClassification.DPI_480:
{
// Note provisional may need changes
gap = 24;
backgroundGradientHeight = 330;
highlightWeight = 3;
arrowTipCurveAnchorDistance = 8;
break;
}
case DPIClassification.DPI_320:
{
gap = 16;
backgroundGradientHeight = 220;
highlightWeight = 2;
arrowTipCurveAnchorDistance = 6;
break;
}
case DPIClassification.DPI_240:
{
gap = 12;
backgroundGradientHeight = 165;
highlightWeight = 1;
arrowTipCurveAnchorDistance = 4;
break;
}
case DPIClassification.DPI_120:
{
// Note provisional may need changes
gap = 6;
backgroundGradientHeight = 83;
highlightWeight = 1;
arrowTipCurveAnchorDistance = 2;
break;
}
default:
{
// default DPI_160
gap = 8;
backgroundGradientHeight = 110;
highlightWeight = 1;
arrowTipCurveAnchorDistance = 3;
break;
}
}
}
/**
* A gap on the frame-adjacent side of the arrow graphic to avoid
* drawing past the CalloutSkin backgroundCornerRadius.
*
* <p>The default implementation matches the gap value with the
* <code>backgroundCornerRadius</code> value in <code>CalloutSkin</code>.</p>
*
* @see spark.skins.mobile.CalloutSkin#backgroundCornerRadius
*
* @langversion 3.0
* @playerversion AIR 3
* @productversion Flex 4.6
*/
protected var gap:Number;
/**
* @copy spark.skins.mobile.CalloutSkin#backgroundGradientHeight
*/
protected var backgroundGradientHeight:Number;
/**
* @copy spark.skins.mobile.CalloutSkin#highlightWeight
*/
private var highlightWeight:Number;
/**
* @copy spark.skins.mobile.CalloutSkin#useBackgroundGradient
*/
protected var useBackgroundGradient:Boolean;
/**
* @copy spark.skins.mobile.CalloutSkin#borderColor
*/
protected var borderColor:Number = -1; // if not set
/**
* @copy spark.skins.mobile.CalloutSkin#borderThickness
*/
protected var borderThickness:Number = -1 ; // marker that borderThickness was not set directly
/**
* @private
* A sibling of the arrow used to erase the drop shadow in CalloutSkin
*/
private var eraseFill:Sprite;
/**
* The distance of the arrow tip's curve's anchor point from arrow tip
*/
private var arrowTipCurveAnchorDistance:Number;
/* helper private accessors */
/* returns borderThickness from style if member is -1, or borderThickness. Returns 0 if NaN */
private function get actualBorderThickness():Number
{
return calloutSkin.actualBorderThickness;
}
private function get actualBorderColor():uint
{
return calloutSkin.actualBorderColor;
}
protected function get calloutSkin():CalloutSkin
{
return parent as CalloutSkin ;
}
protected function get calloutHostComponent():Callout {
return calloutSkin.hostComponent;
}
/**
* @private
*/
override protected function createChildren():void
{
super.createChildren();
// eraseFill has the same position and arrow shape in order to erase
// the drop shadow under the arrow when backgroundAlpha < 1
eraseFill = new Sprite();
eraseFill.blendMode = BlendMode.ERASE;
// layer eraseFill below the arrow
parent.addChildAt(eraseFill, parent.getChildIndex(this));
}
/**
* @private
*/
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
graphics.clear();
eraseFill.graphics.clear();
var hostComponent: Callout = calloutHostComponent;
var arrowDirection:String = hostComponent.arrowDirection;
if (arrowDirection == ArrowDirection.NONE)
return;
// when drawing the arrow, compensate for cornerRadius via padding
var arrowGraphics:Graphics = this.graphics;
var eraseGraphics:Graphics = eraseFill.graphics;
var arrowWidth:Number = unscaledWidth;
var arrowHeight:Number = unscaledHeight;
var arrowX:Number = 0;
var arrowY:Number = 0;
var arrowTipX:Number = 0;
var arrowTipY:Number = 0;
var arrowEndX:Number = 0;
var arrowEndY:Number = 0;
var borderWeight:Number = actualBorderThickness;
var showBorder:Boolean = borderWeight > 0;
var borderHalf:Number = borderWeight / 2;
var isHorizontal:Boolean = false;
var commands:Vector.<int> = new Vector.<int>(4, true);
var coords:Vector.<Number> = new Vector.<Number>(10, true);
commands[0] = GraphicsPathCommand.MOVE_TO;
commands[1] = GraphicsPathCommand.LINE_TO;
commands[2] = GraphicsPathCommand.CURVE_TO;
commands[3] = GraphicsPathCommand.LINE_TO;
if ((arrowDirection == ArrowDirection.LEFT) ||
(arrowDirection == ArrowDirection.RIGHT))
{
isHorizontal = true;
arrowX = -borderHalf;
arrowY = gap;
arrowHeight = arrowHeight - (gap * 2);
arrowTipX = arrowWidth - borderHalf;
arrowTipY = arrowY + (arrowHeight / 2);
arrowEndX = arrowX;
arrowEndY = arrowY + arrowHeight;
// flip coordinates to point left
if (arrowDirection == ArrowDirection.LEFT)
{
arrowX = arrowWidth - arrowX;
arrowTipX = arrowWidth - arrowTipX;
arrowEndX = arrowWidth - arrowEndX;
}
coords[0] = arrowX;
coords[1] = arrowY;
coords[2] = arrowTipX + arrowTipCurveAnchorDistance;
coords[3] = arrowTipY - arrowTipCurveAnchorDistance;
if (arrowDirection == ArrowDirection.LEFT)
{
coords[4] = arrowTipX - arrowTipCurveAnchorDistance * 2;
}
else
{
coords[4] = arrowTipX + arrowTipCurveAnchorDistance * 2;
}
coords[5] = arrowTipY;
coords[6] = arrowTipX + arrowTipCurveAnchorDistance;
coords[7] = arrowTipY + arrowTipCurveAnchorDistance;
coords[8] = arrowEndX
coords[9] = arrowEndY;
}
else
{
arrowX = gap;
arrowY = -borderHalf;
arrowWidth = arrowWidth - (gap * 2);
arrowTipX = arrowX + (arrowWidth / 2);
arrowTipY = arrowHeight - borderHalf;
arrowEndX = arrowX + arrowWidth;
arrowEndY = arrowY;
// flip coordinates to point up
if (hostComponent.arrowDirection == ArrowDirection.UP)
{
arrowY = arrowHeight - arrowY;
arrowTipY = arrowHeight - arrowTipY;
arrowEndY = arrowHeight - arrowEndY;
}
coords[0] = arrowX;
coords[1] = arrowY;
coords[2] = arrowTipX - arrowTipCurveAnchorDistance;
coords[3] = arrowTipY - arrowTipCurveAnchorDistance;
coords[4] = arrowTipX;
if (hostComponent.arrowDirection == ArrowDirection.UP)
{
coords[5] = arrowTipY - arrowTipCurveAnchorDistance * 2;
}
else
{
coords[5] = arrowTipY + arrowTipCurveAnchorDistance * 2;
}
coords[6] = arrowTipX + arrowTipCurveAnchorDistance;
coords[7] = arrowTipY - arrowTipCurveAnchorDistance;
coords[8] = arrowEndX
coords[9] = arrowEndY;
}
var backgroundColor:Number = getStyle("backgroundColor");
var backgroundAlpha:Number = getStyle("backgroundAlpha");
if (useBackgroundGradient)
{
var backgroundColorTop:Number = ColorUtil.adjustBrightness2(backgroundColor,
CalloutSkin.BACKGROUND_GRADIENT_BRIGHTNESS_TOP);
var backgroundColorBottom:Number = ColorUtil.adjustBrightness2(backgroundColor,
CalloutSkin.BACKGROUND_GRADIENT_BRIGHTNESS_BOTTOM);
// translate the gradient based on the arrow position
MobileSkin.colorMatrix.createGradientBox(unscaledWidth,
backgroundGradientHeight, Math.PI / 2, 0, -getLayoutBoundsY());
arrowGraphics.beginGradientFill(GradientType.LINEAR,
[backgroundColorTop, backgroundColorBottom],
[backgroundAlpha, backgroundAlpha],
[0, 255],
MobileSkin.colorMatrix);
}
else
{
arrowGraphics.beginFill(backgroundColor, backgroundAlpha);
}
// cover the adjacent border from the callout frame
if (showBorder)
{
var coverX:Number = 0;
var coverY:Number = 0;
var coverWidth:Number = 0;
var coverHeight:Number = 0;
switch (arrowDirection)
{
case ArrowDirection.UP:
{
coverX = arrowX;
coverY = arrowY;
coverWidth = arrowWidth;
coverHeight = borderWeight;
break;
}
case ArrowDirection.DOWN:
{
coverX = arrowX;
coverY = -borderWeight;
coverWidth = arrowWidth;
coverHeight = borderWeight;
break;
}
case ArrowDirection.LEFT:
{
coverX = arrowX;
coverY = arrowY;
coverWidth = borderWeight;
coverHeight = arrowHeight;
break;
}
case ArrowDirection.RIGHT:
{
coverX = -borderWeight;
coverY = arrowY;
coverWidth = borderWeight;
coverHeight = arrowHeight;
break;
}
}
arrowGraphics.drawRect(coverX, coverY, coverWidth, coverHeight);
}
// erase the drop shadow from the CalloutSkin
if (backgroundAlpha < 1)
{
// move eraseFill to the same position as the arrow
eraseFill.x = getLayoutBoundsX()
eraseFill.y = getLayoutBoundsY();
// draw the arrow shape
eraseGraphics.beginFill(0, 1);
eraseGraphics.drawPath(commands, coords);
eraseGraphics.endFill();
}
// draw arrow path
if (showBorder)
arrowGraphics.lineStyle(borderWeight, actualBorderColor, 1, true);
arrowGraphics.drawPath(commands, coords);
arrowGraphics.endFill();
// adjust the highlight position to the origin of the callout
var isArrowUp:Boolean = (arrowDirection == ArrowDirection.UP);
var offsetY:Number = (isArrowUp) ? unscaledHeight : -getLayoutBoundsY();
// highlight starts after the backgroundCornerRadius
var highlightX:Number = gap - getLayoutBoundsX();
// highlight Y position is based on the stroke weight
var highlightOffset:Number = (highlightWeight * 1.5);
var highlightY:Number = highlightOffset + offsetY;
// highlight width spans the callout width minus the corner radius
var highlightWidth:Number = IVisualElement(calloutSkin).getLayoutBoundsWidth() - (gap * 2);
if (isHorizontal)
{
highlightWidth -= arrowWidth;
if (arrowDirection == ArrowDirection.LEFT)
highlightX += arrowWidth;
}
// highlight on the top edge is drawn in the arrow only in the UP direction
if (useBackgroundGradient)
{
if (isArrowUp)
{
// highlight follows the top edge, including the arrow
var rightWidth:Number = highlightWidth - arrowWidth;
// highlight style
arrowGraphics.lineStyle(highlightWeight, 0xFFFFFF, 0.2 * backgroundAlpha);
// in the arrow coordinate space, the highlightX must be less than 0
if (highlightX < 0)
{
arrowGraphics.moveTo(highlightX, highlightY);
arrowGraphics.lineTo(arrowX, highlightY);
// compute the remaining highlight
rightWidth -= (arrowX - highlightX);
}
// arrow highlight (adjust Y downward)
coords[1] = arrowY + highlightOffset;
coords[3] = arrowTipY + highlightOffset;
coords[5] = arrowEndY + highlightOffset;
arrowGraphics.drawPath(commands, coords);
// right side
if (rightWidth > 0)
{
arrowGraphics.moveTo(arrowEndX, highlightY);
arrowGraphics.lineTo(arrowEndX + rightWidth, highlightY);
}
}
else
{
// straight line across the top
arrowGraphics.lineStyle(highlightWeight, 0xFFFFFF, 0.2 * backgroundAlpha);
arrowGraphics.moveTo(highlightX, highlightY);
arrowGraphics.lineTo(highlightX + highlightWidth, highlightY);
}
}
}
}
}
|
Tweak CalloutSkin. The arrow tip has a curve.
|
Tweak CalloutSkin. The arrow tip has a curve.
|
ActionScript
|
apache-2.0
|
shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk
|
e22f71cdc5dd90b50678137c4686bde99d567e3d
|
exporter/src/main/as/flump/export/Exporter.as
|
exporter/src/main/as/flump/export/Exporter.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import flash.desktop.NativeApplication;
import flash.display.NativeMenu;
import flash.display.NativeMenuItem;
import flash.display.NativeWindow;
import flash.display.Stage;
import flash.display.StageQuality;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filesystem.File;
import flash.net.SharedObject;
import flash.utils.IDataOutput;
import flump.executor.Executor;
import flump.executor.Future;
import flump.export.Ternary;
import flump.xfl.ParseError;
import flump.xfl.XflLibrary;
import mx.collections.ArrayList;
import mx.events.CollectionEvent;
import mx.events.PropertyChangeEvent;
import spark.components.DataGrid;
import spark.components.DropDownList;
import spark.components.List;
import spark.components.Window;
import spark.events.GridSelectionEvent;
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.StringUtil;
import starling.display.Sprite;
public class Exporter
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
public function Exporter (win :ExporterWindow) {
Log.setLevel("", Log.INFO);
_win = win;
_errors = _win.errors;
_libraries = _win.libraries;
function updatePreviewAndExport (..._) :void {
_win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 &&
_libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean {
return status.isValid;
});
var status :DocStatus = _libraries.selectedItem as DocStatus;
_win.preview.enabled = status != null && status.isValid;
if (_exportChooser.dir == null) return;
_conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true);
}
var fileMenuItem :NativeMenuItem;
if (NativeApplication.supportsMenu) {
// Grab the existing menu on macs. Use an index to get it as it's not going to be
// 'File' in all languages
fileMenuItem = NA.menu.getItemAt(1);
// Add a separator before the existing close command
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 0);
} else {
_win.nativeWindow.menu = new NativeMenu();
fileMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File");
}
// Add save and save as by index to work with the existing items on Mac
// Mac menus have an existing "Close" item, so everything we add should go ahead of that
var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New"), 0);
newMenuItem.keyEquivalent = "n";
newMenuItem.addEventListener(Event.SELECT, function (..._) :void {
_confFile = null;
_conf = new FlumpConf();
updatePublisher();
});
var openMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open..."), 1);
openMenuItem.keyEquivalent = "o";
openMenuItem.addEventListener(Event.SELECT, function (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
_confFile = file;
openConf();
updatePublisher();
});
file.browseForOpen("Open Flump Configuration");
});
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2);
const saveMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save"), 3);
saveMenuItem.keyEquivalent = "s";
function saveConf () :void {
Files.write(_confFile, function (out :IDataOutput) :void {
// Set directories relative to where this file is being saved. Fall back to absolute
// paths if relative paths aren't possible.
if (_importChooser.dir != null) {
_conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true);
if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath;
}
if (_exportChooser.dir != null) {
_conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true);
if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath;
}
out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2));
});
};
function saveAs (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
_confFile = file;
trace("Conf file is now " + _confFile.nativePath);
_settings.data["CONF_FILE"] = _confFile.nativePath;
_settings.flush();
saveConf();
});
file.browseForSave("Save Flump Configuration");
};
saveMenuItem.addEventListener(Event.SELECT, function (..._) :void {
if (_confFile == null) saveAs();
else saveConf();
});
function openConf () :void {
try {
_conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile));
_win.title = _confFile.name;
var dir :String = _confFile.parent.resolvePath(_conf.importDir).nativePath;
setImport(new File(dir));
} catch (e :Error) {
log.warning("Unable to parse conf", e);
_errors.dataProvider.addItem(new ParseError(_confFile.nativePath,
ParseError.CRIT, "Unable to read configuration"));
_confFile = null;
}
};
const saveAsMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save As..."), 4);
saveAsMenuItem.keyEquivalent = "S";
saveAsMenuItem.addEventListener(Event.SELECT, saveAs);
if (_settings.data.hasOwnProperty("CONF_FILE")) {
_confFile = new File(_settings.data["CONF_FILE"]);
openConf();
}
var curSelection :DocStatus = null;
_libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
log.info("Changed", "selected", _libraries.selectedIndices);
updatePreviewAndExport();
if (curSelection != null) {
curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
var newSelection :DocStatus = _libraries.selectedItem as DocStatus;
if (newSelection != null) {
newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
curSelection = newSelection;
});
_win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void {
setImport(_importChooser.dir);
updatePreviewAndExport();
});
_win.export.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var status :DocStatus in _libraries.selectedItems) {
exportFlashDocument(status);
}
});
_win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void {
showPreviewWindow(_libraries.selectedItem.lib);
});
_importChooser = new DirChooser(null, _win.importRoot, _win.browseImport);
_importChooser.changed.add(setImport);
_exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport);
_exportChooser.changed.add(updatePreviewAndExport);
function updatePublisher (..._) :void {
if (_confFile != null) {
_importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null;
_exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null;
} else {
_importChooser.dir = null;
_exportChooser.dir = null;
}
if (_exportChooser.dir == null || _conf.exports.length == 0) _publisher = null;
else _publisher = new Publisher(_exportChooser.dir, Vector.<ExportConf>(_conf.exports));
var formatNames :Array = [];
for each (var export :ExportConf in _conf.exports) formatNames.push(export.name);
_win.formatOverview.text = formatNames.join(", ");
};
var editFormats :EditFormatsWindow;
_win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void {
if (editFormats == null || editFormats.closed) {
editFormats = new EditFormatsWindow();
editFormats.open();
} else editFormats.orderToFront();
var dataProvider :ArrayList = new ArrayList(_conf.exports);
dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, updatePublisher);
editFormats.exports.dataProvider = dataProvider;
editFormats.buttonAdd.addEventListener(MouseEvent.CLICK, function (..._) :void {
var export :ExportConf = new ExportConf();
export.name = "format" + (_conf.exports.length+1);
if (_conf.exports.length > 0) {
export.format = _conf.exports[0].format;
}
dataProvider.addItem(export);
});
editFormats.exports.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
editFormats.buttonRemove.enabled = (editFormats.exports.selectedItem != null);
});
editFormats.buttonRemove.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var export :ExportConf in editFormats.exports.selectedItems) {
dataProvider.removeItem(export);
}
});
});
updatePublisher();
_win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); });
}
protected function setImport (root :File) :void {
_libraries.dataProvider.removeAll();
_errors.dataProvider.removeAll();
if (root == null) return;
_rootLen = root.nativePath.length + 1;
if (_docFinder != null) _docFinder.shutdownNow();
_docFinder = new Executor();
findFlashDocuments(root, _docFinder, true);
_win.reload.enabled = true;
}
protected function showPreviewWindow (lib :XflLibrary) :void {
if (_previewController == null || _previewWindow.closed || _previewControls.closed) {
_previewWindow = new PreviewWindow();
_previewControls = new PreviewControlsWindow();
_previewWindow.started = function (container :Sprite) :void {
_previewController = new PreviewController(lib, container, _previewWindow,
_previewControls);
}
_previewWindow.open();
_previewControls.open();
preventWindowClose(_previewWindow.nativeWindow);
preventWindowClose(_previewControls.nativeWindow);
} else {
_previewController.lib = lib;
_previewWindow.nativeWindow.visible = true;
_previewControls.nativeWindow.visible = true;
}
_previewWindow.orderToFront();
_previewControls.orderToFront();
}
// Causes a window to be hidden, rather than closed, when its close box is clicked
protected static function preventWindowClose (window :NativeWindow) :void {
window.addEventListener(Event.CLOSING, function (e :Event) :void {
e.preventDefault();
window.visible = false;
});
}
protected var _previewController :PreviewController;
protected var _previewWindow :PreviewWindow;
protected var _previewControls :PreviewControlsWindow;
protected function findFlashDocuments (base :File, exec :Executor,
ignoreXflAtBase :Boolean = false) :void {
Files.list(base, exec).succeeded.add(function (files :Array) :void {
if (exec.isShutdown) return;
for each (var file :File in files) {
if (Files.hasExtension(file, "xfl")) {
if (ignoreXflAtBase) {
_errors.dataProvider.addItem(new ParseError(base.nativePath,
ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " +
base.parent.nativePath + "?"));
} else addFlashDocument(file);
return;
}
}
for each (file in files) {
if (StringUtil.startsWith(file.name, ".", "RECOVER_")) {
continue; // Ignore hidden VCS directories, and recovered backups created by Flash
}
if (file.isDirectory) findFlashDocuments(file, exec);
else addFlashDocument(file);
}
});
}
protected function exportFlashDocument (status :DocStatus) :void {
const stage :Stage = NA.activeWindow.stage;
const prevQuality :String = stage.quality;
stage.quality = StageQuality.BEST;
_publisher.publish(status.lib);
stage.quality = prevQuality;
status.updateModified(Ternary.FALSE);
}
protected function addFlashDocument (file :File) :void {
var name :String = file.nativePath.substring(_rootLen).replace(
new RegExp("\\" + File.separator, "g"), "/");
var load :Future;
switch (Files.getExtension(file)) {
case "xfl":
name = name.substr(0, name.lastIndexOf("/"));
load = new XflLoader().load(name, file.parent);
break;
case "fla":
name = name.substr(0, name.lastIndexOf("."));
load = new FlaLoader().load(name, file);
break;
default:
// Unsupported file type, ignore
return;
}
const status :DocStatus = new DocStatus(name, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null);
_libraries.dataProvider.addItem(status);
load.succeeded.add(function (lib :XflLibrary) :void {
status.lib = lib;
status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib)));
for each (var err :ParseError in lib.getErrors()) _errors.dataProvider.addItem(err);
status.updateValid(Ternary.of(lib.valid));
});
load.failed.add(function (error :Error) :void {
trace("Failed to load " + file.nativePath + ": " + error);
status.updateValid(Ternary.FALSE);
throw error;
});
}
protected var _rootLen :int;
protected var _publisher :Publisher;
protected var _docFinder :Executor;
protected var _win :ExporterWindow;
protected var _libraries :DataGrid;
protected var _errors :DataGrid;
protected var _exportChooser :DirChooser;
protected var _importChooser :DirChooser;
protected var _authoredResolution :DropDownList;
protected var _conf :FlumpConf = new FlumpConf();
protected var _confFile :File;
protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter");
private static const log :Log = Log.getLog(Exporter);
}
}
import flash.events.EventDispatcher;
import flump.export.Ternary;
import flump.xfl.XflLibrary;
import mx.core.IPropertyChangeNotifier;
import mx.events.PropertyChangeEvent;
class DocStatus extends EventDispatcher implements IPropertyChangeNotifier {
public var path :String;
public var modified :String;
public var valid :String = QUESTION;
public var lib :XflLibrary;
public function DocStatus (path :String, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) {
this.lib = lib;
this.path = path;
_uid = path;
updateModified(modified);
updateValid(valid);
}
public function updateValid (newValid :Ternary) :void {
changeField("valid", function (..._) :void {
if (newValid == Ternary.TRUE) valid = CHECK;
else if (newValid == Ternary.FALSE) valid = FROWN;
else valid = QUESTION;
});
}
public function get isValid () :Boolean { return valid == CHECK; }
public function updateModified (newModified :Ternary) :void {
changeField("modified", function (..._) :void {
if (newModified == Ternary.TRUE) modified = CHECK;
else if (newModified == Ternary.FALSE) modified = " ";
else modified = QUESTION;
});
}
protected function changeField(fieldName :String, modifier :Function) :void {
const oldValue :Object = this[fieldName];
modifier();
const newValue :Object = this[fieldName];
dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue));
}
public function get uid () :String { return _uid; }
public function set uid (uid :String) :void { _uid = uid; }
protected var _uid :String;
protected static const QUESTION :String = "?";
protected static const FROWN :String = "☹";
protected static const CHECK :String = "✓";
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import flash.desktop.NativeApplication;
import flash.display.NativeMenu;
import flash.display.NativeMenuItem;
import flash.display.NativeWindow;
import flash.display.Stage;
import flash.display.StageQuality;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filesystem.File;
import flash.net.SharedObject;
import flash.utils.IDataOutput;
import flump.executor.Executor;
import flump.executor.Future;
import flump.export.Ternary;
import flump.xfl.ParseError;
import flump.xfl.XflLibrary;
import mx.collections.ArrayList;
import mx.events.CollectionEvent;
import mx.events.PropertyChangeEvent;
import spark.components.DataGrid;
import spark.components.DropDownList;
import spark.components.List;
import spark.components.Window;
import spark.events.GridSelectionEvent;
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.StringUtil;
import starling.display.Sprite;
public class Exporter
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
public function Exporter (win :ExporterWindow) {
Log.setLevel("", Log.INFO);
_win = win;
_errors = _win.errors;
_libraries = _win.libraries;
function updatePreviewAndExport (..._) :void {
_win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 &&
_libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean {
return status.isValid;
});
var status :DocStatus = _libraries.selectedItem as DocStatus;
_win.preview.enabled = status != null && status.isValid;
if (_exportChooser.dir == null) return;
_conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true);
}
var fileMenuItem :NativeMenuItem;
if (NativeApplication.supportsMenu) {
// Grab the existing menu on macs. Use an index to get it as it's not going to be
// 'File' in all languages
fileMenuItem = NA.menu.getItemAt(1);
// Add a separator before the existing close command
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 0);
} else {
_win.nativeWindow.menu = new NativeMenu();
fileMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File");
}
// Add save and save as by index to work with the existing items on Mac
// Mac menus have an existing "Close" item, so everything we add should go ahead of that
var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New"), 0);
newMenuItem.keyEquivalent = "n";
newMenuItem.addEventListener(Event.SELECT, function (..._) :void {
_confFile = null;
_conf = new FlumpConf();
setImport(null);
updatePublisher();
});
var openMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open..."), 1);
openMenuItem.keyEquivalent = "o";
openMenuItem.addEventListener(Event.SELECT, function (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
_confFile = file;
openConf();
updatePublisher();
});
file.browseForOpen("Open Flump Configuration");
});
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2);
const saveMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save"), 3);
saveMenuItem.keyEquivalent = "s";
function saveConf () :void {
Files.write(_confFile, function (out :IDataOutput) :void {
// Set directories relative to where this file is being saved. Fall back to absolute
// paths if relative paths aren't possible.
if (_importChooser.dir != null) {
_conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true);
if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath;
}
if (_exportChooser.dir != null) {
_conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true);
if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath;
}
out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2));
});
};
function saveAs (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
_confFile = file;
trace("Conf file is now " + _confFile.nativePath);
_settings.data["CONF_FILE"] = _confFile.nativePath;
_settings.flush();
saveConf();
});
file.browseForSave("Save Flump Configuration");
};
saveMenuItem.addEventListener(Event.SELECT, function (..._) :void {
if (_confFile == null) saveAs();
else saveConf();
});
function openConf () :void {
try {
_conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile));
_win.title = _confFile.name;
var dir :String = _confFile.parent.resolvePath(_conf.importDir).nativePath;
setImport(new File(dir));
} catch (e :Error) {
log.warning("Unable to parse conf", e);
_errors.dataProvider.addItem(new ParseError(_confFile.nativePath,
ParseError.CRIT, "Unable to read configuration"));
_confFile = null;
}
};
const saveAsMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save As..."), 4);
saveAsMenuItem.keyEquivalent = "S";
saveAsMenuItem.addEventListener(Event.SELECT, saveAs);
if (_settings.data.hasOwnProperty("CONF_FILE")) {
_confFile = new File(_settings.data["CONF_FILE"]);
openConf();
}
var curSelection :DocStatus = null;
_libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
log.info("Changed", "selected", _libraries.selectedIndices);
updatePreviewAndExport();
if (curSelection != null) {
curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
var newSelection :DocStatus = _libraries.selectedItem as DocStatus;
if (newSelection != null) {
newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
curSelection = newSelection;
});
_win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void {
setImport(_importChooser.dir);
updatePreviewAndExport();
});
_win.export.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var status :DocStatus in _libraries.selectedItems) {
exportFlashDocument(status);
}
});
_win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void {
showPreviewWindow(_libraries.selectedItem.lib);
});
_importChooser = new DirChooser(null, _win.importRoot, _win.browseImport);
_importChooser.changed.add(setImport);
_exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport);
_exportChooser.changed.add(updatePreviewAndExport);
function updatePublisher (..._) :void {
if (_confFile != null) {
_importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null;
_exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null;
} else {
_importChooser.dir = null;
_exportChooser.dir = null;
}
if (_exportChooser.dir == null || _conf.exports.length == 0) _publisher = null;
else _publisher = new Publisher(_exportChooser.dir, Vector.<ExportConf>(_conf.exports));
var formatNames :Array = [];
for each (var export :ExportConf in _conf.exports) formatNames.push(export.name);
_win.formatOverview.text = formatNames.join(", ");
};
var editFormats :EditFormatsWindow;
_win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void {
if (editFormats == null || editFormats.closed) {
editFormats = new EditFormatsWindow();
editFormats.open();
} else editFormats.orderToFront();
var dataProvider :ArrayList = new ArrayList(_conf.exports);
dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, updatePublisher);
editFormats.exports.dataProvider = dataProvider;
editFormats.buttonAdd.addEventListener(MouseEvent.CLICK, function (..._) :void {
var export :ExportConf = new ExportConf();
export.name = "format" + (_conf.exports.length+1);
if (_conf.exports.length > 0) {
export.format = _conf.exports[0].format;
}
dataProvider.addItem(export);
});
editFormats.exports.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
editFormats.buttonRemove.enabled = (editFormats.exports.selectedItem != null);
});
editFormats.buttonRemove.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var export :ExportConf in editFormats.exports.selectedItems) {
dataProvider.removeItem(export);
}
});
});
updatePublisher();
_win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); });
}
protected function setImport (root :File) :void {
_libraries.dataProvider.removeAll();
_errors.dataProvider.removeAll();
if (root == null) return;
_rootLen = root.nativePath.length + 1;
if (_docFinder != null) _docFinder.shutdownNow();
_docFinder = new Executor();
findFlashDocuments(root, _docFinder, true);
_win.reload.enabled = true;
}
protected function showPreviewWindow (lib :XflLibrary) :void {
if (_previewController == null || _previewWindow.closed || _previewControls.closed) {
_previewWindow = new PreviewWindow();
_previewControls = new PreviewControlsWindow();
_previewWindow.started = function (container :Sprite) :void {
_previewController = new PreviewController(lib, container, _previewWindow,
_previewControls);
}
_previewWindow.open();
_previewControls.open();
preventWindowClose(_previewWindow.nativeWindow);
preventWindowClose(_previewControls.nativeWindow);
} else {
_previewController.lib = lib;
_previewWindow.nativeWindow.visible = true;
_previewControls.nativeWindow.visible = true;
}
_previewWindow.orderToFront();
_previewControls.orderToFront();
}
// Causes a window to be hidden, rather than closed, when its close box is clicked
protected static function preventWindowClose (window :NativeWindow) :void {
window.addEventListener(Event.CLOSING, function (e :Event) :void {
e.preventDefault();
window.visible = false;
});
}
protected var _previewController :PreviewController;
protected var _previewWindow :PreviewWindow;
protected var _previewControls :PreviewControlsWindow;
protected function findFlashDocuments (base :File, exec :Executor,
ignoreXflAtBase :Boolean = false) :void {
Files.list(base, exec).succeeded.add(function (files :Array) :void {
if (exec.isShutdown) return;
for each (var file :File in files) {
if (Files.hasExtension(file, "xfl")) {
if (ignoreXflAtBase) {
_errors.dataProvider.addItem(new ParseError(base.nativePath,
ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " +
base.parent.nativePath + "?"));
} else addFlashDocument(file);
return;
}
}
for each (file in files) {
if (StringUtil.startsWith(file.name, ".", "RECOVER_")) {
continue; // Ignore hidden VCS directories, and recovered backups created by Flash
}
if (file.isDirectory) findFlashDocuments(file, exec);
else addFlashDocument(file);
}
});
}
protected function exportFlashDocument (status :DocStatus) :void {
const stage :Stage = NA.activeWindow.stage;
const prevQuality :String = stage.quality;
stage.quality = StageQuality.BEST;
_publisher.publish(status.lib);
stage.quality = prevQuality;
status.updateModified(Ternary.FALSE);
}
protected function addFlashDocument (file :File) :void {
var name :String = file.nativePath.substring(_rootLen).replace(
new RegExp("\\" + File.separator, "g"), "/");
var load :Future;
switch (Files.getExtension(file)) {
case "xfl":
name = name.substr(0, name.lastIndexOf("/"));
load = new XflLoader().load(name, file.parent);
break;
case "fla":
name = name.substr(0, name.lastIndexOf("."));
load = new FlaLoader().load(name, file);
break;
default:
// Unsupported file type, ignore
return;
}
const status :DocStatus = new DocStatus(name, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null);
_libraries.dataProvider.addItem(status);
load.succeeded.add(function (lib :XflLibrary) :void {
status.lib = lib;
status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib)));
for each (var err :ParseError in lib.getErrors()) _errors.dataProvider.addItem(err);
status.updateValid(Ternary.of(lib.valid));
});
load.failed.add(function (error :Error) :void {
trace("Failed to load " + file.nativePath + ": " + error);
status.updateValid(Ternary.FALSE);
throw error;
});
}
protected var _rootLen :int;
protected var _publisher :Publisher;
protected var _docFinder :Executor;
protected var _win :ExporterWindow;
protected var _libraries :DataGrid;
protected var _errors :DataGrid;
protected var _exportChooser :DirChooser;
protected var _importChooser :DirChooser;
protected var _authoredResolution :DropDownList;
protected var _conf :FlumpConf = new FlumpConf();
protected var _confFile :File;
protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter");
private static const log :Log = Log.getLog(Exporter);
}
}
import flash.events.EventDispatcher;
import flump.export.Ternary;
import flump.xfl.XflLibrary;
import mx.core.IPropertyChangeNotifier;
import mx.events.PropertyChangeEvent;
class DocStatus extends EventDispatcher implements IPropertyChangeNotifier {
public var path :String;
public var modified :String;
public var valid :String = QUESTION;
public var lib :XflLibrary;
public function DocStatus (path :String, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) {
this.lib = lib;
this.path = path;
_uid = path;
updateModified(modified);
updateValid(valid);
}
public function updateValid (newValid :Ternary) :void {
changeField("valid", function (..._) :void {
if (newValid == Ternary.TRUE) valid = CHECK;
else if (newValid == Ternary.FALSE) valid = FROWN;
else valid = QUESTION;
});
}
public function get isValid () :Boolean { return valid == CHECK; }
public function updateModified (newModified :Ternary) :void {
changeField("modified", function (..._) :void {
if (newModified == Ternary.TRUE) modified = CHECK;
else if (newModified == Ternary.FALSE) modified = " ";
else modified = QUESTION;
});
}
protected function changeField(fieldName :String, modifier :Function) :void {
const oldValue :Object = this[fieldName];
modifier();
const newValue :Object = this[fieldName];
dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue));
}
public function get uid () :String { return _uid; }
public function set uid (uid :String) :void { _uid = uid; }
protected var _uid :String;
protected static const QUESTION :String = "?";
protected static const FROWN :String = "☹";
protected static const CHECK :String = "✓";
}
|
Clear out the file list when a new config is started.
|
Clear out the file list when a new config is started.
|
ActionScript
|
mit
|
mathieuanthoine/flump,tconkling/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump
|
a1e9e36a07b5b816b0ee67cf73f4d4d21b4fb826
|
WEB-INF/lps/lfc/kernel/swf/LzSoundMC.as
|
WEB-INF/lps/lfc/kernel/swf/LzSoundMC.as
|
/**
* LzSoundMC.as
*
* @copyright Copyright 2001-2007 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
/**
* Wraps the streaming MP3 loader in a movieclip-like API.
* Used for proxyless mp3 audio loading.
*
* @access private
*/
var SoundMC = function(mc) {
this.init(mc);
this._playdel = new LzDelegate( this , "testPlay" );
}
SoundMC.prototype = new MovieClip();
SoundMC.prototype._currentframe = 0;
SoundMC.prototype._framesloaded = 0;
SoundMC.prototype._totalframes = 0;
SoundMC.prototype._fps = 30;
SoundMC.prototype.isaudio = true;
SoundMC.prototype.loadstate = 0;
/**
* @access private
*/
SoundMC.prototype.play = function() {
var t = this._currentframe / this._fps;
if (t < 0) t = 0;
this._sound.stop();
this._sound.start(t)
//Debug.write('play mp3', t);
this._playdel.unregisterAll();
this._playdel.register( LzIdle, "onidle" );
}
/**
* @access private
*/
SoundMC.prototype.gotoAndPlay = function(f) {
this._currentframe = f;
this.play();
}
/**
* @access private
*/
SoundMC.prototype.stop = function() {
this._sound.stop();
this._playdel.unregisterAll();
this.testPlay();
}
/**
* @access private
*/
SoundMC.prototype.gotoAndStop = function(f) {
this.stop();
this._currentframe = f;
}
/**
* @access private
*/
SoundMC.prototype.loadMovie = function( reqstr ) {
//Debug.warn('SoundMC loading mp3 %w', reqstr);
this.init();
this._sound.loadSound(reqstr, true);
this.loadstate = 1;
//this._playdel.unregisterAll();
//this._playdel.register( LzIdle, "onidle" );
}
/**
* @access private
*/
SoundMC.prototype.getBytesLoaded = function( ) {
//Debug.warn('getBytesLoaded %w', this._sound.getBytesLoaded());
this.testPlay();
return this._sound.getBytesLoaded();
}
/**
* @access private
*/
SoundMC.prototype.getBytesTotal = function( ) {
//Debug.warn('getBytesTotal %w', this._sound.getBytesTotal());
this.testPlay();
return this._sound.getBytesTotal();
}
/**
* @access private
*/
SoundMC.prototype.unload = function( ) {
//Debug.warn('unload %w', this._sound.getBytesTotal());
this.stop();
delete this._sound;
this.loadstate = 0;
}
/**
* @access private
*/
SoundMC.prototype.testPlay = function() {
this._totalframes = Math.floor(this._sound.duration * .001 * this._fps);
this._currentframe = Math.floor(this._sound.position * .001 * this._fps);
this._framesloaded = Math.floor((this._sound.getBytesLoaded() / this._sound.getBytesTotal()) * this._totalframes)
//Debug.write('testPlay ', this._currentframe, this._totalframes, this._framesloaded);
}
/**
* @access private
*/
SoundMC.prototype.setPan = function(p) {
//Debug.write('setPan', p);
this._sound.setPan(p);
}
/**
* @access private
*/
SoundMC.prototype.setVolume = function(v) {
//Debug.write('setVolume', v);
this._sound.setVolume(v);
}
/**
* @access private
*/
SoundMC.prototype.getPan = function(p) {
return this._sound.getPan(p);
}
/**
* @access private
*/
SoundMC.prototype.getVolume = function(v) {
return this._sound.getVolume(v);
}
/**
* @access private
*/
SoundMC.prototype.loadDone = function(success) {
if (success != true) {
if ($debug) {
Debug.warn("failed to load %w", this.reqobj.url);
}
} else {
//this.testPlay();
//Debug.write('done loading');
this.loadstate = 2;
this._playdel.unregisterAll();
this._playdel.register( LzIdle, "onidle" );
}
}
/**
* @access private
*/
SoundMC.prototype.init = function(mc) {
this._sound.stop();
delete this._sound;
if (mc != null) {
this._sound = new Sound(mc);
} else {
this._sound = new Sound();
}
this._sound.checkPolicyFile = true;
this._sound.mc = this;
/** @access private */
this._sound.onLoad = function(success) {
this.mc.loadDone(success);
}
/** @access private */
this._sound.onSoundDone = function() {
this.mc.testPlay();
}
this._playdel.unregisterAll();
this._currentframe = 0;
this._totalframes = 0;
this._framesloaded = 0;
this.loadstate = 0;
}
/**
* @access private
*/
SoundMC.prototype.getTotalTime = function() {
return this._sound.duration * .001;
}
/**
* @access private
*/
SoundMC.prototype.getCurrentTime = function() {
return this._sound.position * .001;
}
/**
* @access private
*/
SoundMC.prototype.seek = function(secs, playing) {
//Debug.write('seek', secs, playing);
this._sound.stop();
this._sound.start(this.getCurrentTime() + secs);
if (playing != true) this._sound.stop();
}
/**
* @access private
*/
SoundMC.prototype.getID3 = function() {
//Debug.write('getID3', this._sound);
return this._sound.id3;
}
|
/**
* LzSoundMC.as
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
/**
* Wraps the streaming MP3 loader in a movieclip-like API.
* Used for proxyless mp3 audio loading.
*
* @access private
*/
var SoundMC = function(mc) {
this.init(mc);
this._playdel = new LzDelegate( this , "testPlay" );
}
SoundMC.prototype = new MovieClip();
SoundMC.prototype._currentframe = 0;
SoundMC.prototype._framesloaded = 0;
SoundMC.prototype._totalframes = 0;
SoundMC.prototype._fps = 30;
SoundMC.prototype.isaudio = true;
SoundMC.prototype.loadstate = 0;
/**
* @access private
*/
SoundMC.prototype.play = function() {
var t = this._currentframe / this._fps;
if (t < 0) t = 0;
this._sound.stop();
this._sound.start(t)
//Debug.write('play mp3', t);
this._playdel.unregisterAll();
this._playdel.register( LzIdle, "onidle" );
}
/**
* @access private
*/
SoundMC.prototype.gotoAndPlay = function(f) {
this._currentframe = f;
this.play();
}
/**
* @access private
*/
SoundMC.prototype.stop = function() {
this._sound.stop();
this._playdel.unregisterAll();
this.testPlay();
}
/**
* @access private
*/
SoundMC.prototype.gotoAndStop = function(f) {
this.stop();
this._currentframe = f;
}
/**
* @access private
*/
SoundMC.prototype.loadMovie = function( reqstr ) {
//Debug.warn('SoundMC loading mp3 %w', reqstr);
this.init();
this._sound.loadSound(reqstr, true);
this.loadstate = 1;
//this._playdel.unregisterAll();
//this._playdel.register( LzIdle, "onidle" );
}
/**
* @access private
*/
SoundMC.prototype.getBytesLoaded = function( ) {
//Debug.warn('getBytesLoaded %w', this._sound.getBytesLoaded());
this.testPlay();
return this._sound.getBytesLoaded();
}
/**
* @access private
*/
SoundMC.prototype.getBytesTotal = function( ) {
//Debug.warn('getBytesTotal %w', this._sound.getBytesTotal());
this.testPlay();
return this._sound.getBytesTotal();
}
/**
* @access private
*/
SoundMC.prototype.unload = function( ) {
//Debug.warn('unload %w', this._sound.getBytesTotal());
this.stop();
delete this._sound;
this.loadstate = 0;
}
/**
* @access private
*/
SoundMC.prototype.testPlay = function() {
this._totalframes = Math.floor(this._sound.duration * .001 * this._fps);
this._currentframe = Math.floor(this._sound.position * .001 * this._fps);
this._framesloaded = Math.floor((this._sound.getBytesLoaded() / this._sound.getBytesTotal()) * this._totalframes)
//Debug.write('testPlay ', this._currentframe, this._totalframes, this._framesloaded);
}
/**
* @access private
*/
SoundMC.prototype.setPan = function(p) {
//Debug.write('setPan', p);
this._sound.setPan(p);
}
/**
* @access private
*/
SoundMC.prototype.setVolume = function(v) {
//Debug.write('setVolume', v);
this._sound.setVolume(v);
}
/**
* @access private
*/
SoundMC.prototype.getPan = function(p) {
return this._sound.getPan(p);
}
/**
* @access private
*/
SoundMC.prototype.getVolume = function(v) {
return this._sound.getVolume(v);
}
/**
* @access private
*/
SoundMC.prototype.loadDone = function(success) {
if (success != true) {
this.loader.owner.owner.resourceloaderror();
if ($debug) {
Debug.warn("failed to load %w", this.reqobj.url);
}
} else {
//this.testPlay();
//Debug.write('done loading');
this.loadstate = 2;
this._playdel.unregisterAll();
this._playdel.register( LzIdle, "onidle" );
}
}
/**
* @access private
*/
SoundMC.prototype.init = function(mc) {
this._sound.stop();
delete this._sound;
if (mc != null) {
this._sound = new Sound(mc);
} else {
this._sound = new Sound();
}
this._sound.checkPolicyFile = true;
this._sound.mc = this;
/** @access private */
this._sound.onLoad = function(success) {
this.mc.loadDone(success);
}
/** @access private */
this._sound.onSoundDone = function() {
this.mc.testPlay();
}
this._playdel.unregisterAll();
this._currentframe = 0;
this._totalframes = 0;
this._framesloaded = 0;
this.loadstate = 0;
}
/**
* @access private
*/
SoundMC.prototype.getTotalTime = function() {
return this._sound.duration * .001;
}
/**
* @access private
*/
SoundMC.prototype.getCurrentTime = function() {
return this._sound.position * .001;
}
/**
* @access private
*/
SoundMC.prototype.seek = function(secs, playing) {
//Debug.write('seek', secs, playing);
this._sound.stop();
this._sound.start(this.getCurrentTime() + secs);
if (playing != true) this._sound.stop();
}
/**
* @access private
*/
SoundMC.prototype.getID3 = function() {
//Debug.write('getID3', this._sound);
return this._sound.id3;
}
|
Change 20080220-maxcarlson-O by [email protected] on 2008-02-20 14:33:48 PST in /Users/maxcarlson/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20080220-maxcarlson-O by [email protected] on 2008-02-20 14:33:48 PST
in /Users/maxcarlson/openlaszlo/trunk
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: Send onerror event for failed streaming mp3 loads in swf`
New Features:
Bugs Fixed: LPP-5445 - SoundMC does not send onerror-event
Technical Reviewer: promanik`
QA Reviewer: [email protected]
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details: Send onerror event when load fails.
Tests: See LPP-5445
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@8129 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.