code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
var searchData=
[
['memoryshard_2ehpp',['memoryshard.hpp',['../memoryshard_8hpp.html',1,'']]],
['metrics_2ehpp',['metrics.hpp',['../metrics_8hpp.html',1,'']]],
['mongcpp_2eh',['mongcpp.h',['../mongcpp_8h.html',1,'']]]
];
| JavaScript |
var searchData=
[
['vcallback',['VCallback',['../classgraphchi_1_1_v_callback.html',1,'graphchi']]],
['vcallback_3c_20latentvec_5ft_20_3e',['VCallback< latentvec_t >',['../classgraphchi_1_1_v_callback.html',1,'graphchi']]],
['vec',['vec',['../structvec.html',1,'']]],
['vertex_5fdata',['vertex_data',['../structvertex__data.html',1,'']]],
['vertex_5fdata_5fstore',['vertex_data_store',['../classgraphchi_1_1vertex__data__store.html',1,'graphchi']]],
['vertex_5fdegree',['vertex_degree',['../structgraphchi_1_1vertex__degree.html',1,'graphchi']]],
['vertex_5finfo',['vertex_info',['../structgraphchi_1_1vertex__info.html',1,'graphchi']]],
['vertex_5fvalue',['vertex_value',['../structgraphchi_1_1vertex__value.html',1,'graphchi']]],
['vertexdatachecker',['VertexDataChecker',['../class_vertex_data_checker.html',1,'']]]
];
| JavaScript |
var searchData=
[
['labelcount_5ftt',['labelcount_tt',['../structlabelcount__tt.html',1,'']]],
['latentvec_5ft',['latentvec_t',['../structlatentvec__t.html',1,'']]],
['log_5fdispatch',['log_dispatch',['../structlog__dispatch.html',1,'']]],
['log_5fdispatch_3c_20false_20_3e',['log_dispatch< false >',['../structlog__dispatch_3_01false_01_4.html',1,'']]],
['log_5fdispatch_3c_20true_20_3e',['log_dispatch< true >',['../structlog__dispatch_3_01true_01_4.html',1,'']]],
['log_5fstream_5fdispatch',['log_stream_dispatch',['../structlog__stream__dispatch.html',1,'']]],
['log_5fstream_5fdispatch_3c_20false_20_3e',['log_stream_dispatch< false >',['../structlog__stream__dispatch_3_01false_01_4.html',1,'']]],
['log_5fstream_5fdispatch_3c_20true_20_3e',['log_stream_dispatch< true >',['../structlog__stream__dispatch_3_01true_01_4.html',1,'']]]
];
| JavaScript |
var searchData=
[
['obs',['obs',['../structedge__data.html#a1fc50f971f9fdbb4c9c90e33bda1c758',1,'edge_data']]]
];
| JavaScript |
var searchData=
[
['degree_5fdata_2ehpp',['degree_data.hpp',['../degree__data_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['tolerance',['TOLERANCE',['../classals__vertex__program.html#a4d3fe82f9b913c88361646fecea3e181',1,'als_vertex_program']]]
];
| JavaScript |
var searchData=
[
['support_5fdeletions',['SUPPORT_DELETIONS',['../trianglecounting_8cpp.html#a5e44d0ac338ca3ad77ad74a8e17d763d',1,'trianglecounting.cpp']]]
];
| JavaScript |
var searchData=
[
['parse',['parse',['../namespacegraphchi.html#ace1ff5b8c766b05e4d3a74cc21038a6b',1,'graphchi']]],
['pinned_5fsession',['pinned_session',['../classgraphchi_1_1stripedio.html#ab84bcc570151709fba172c3159125d54',1,'graphchi::stripedio']]],
['post_5fdelta',['post_delta',['../classgraphlab_1_1icontext.html#a9c85c9b34ae08d72a28ca5e698a34482',1,'graphlab::icontext']]],
['preprocessed_5ffile_5fexists',['preprocessed_file_exists',['../classgraphchi_1_1sharder.html#a9473263ad2cfc83c11100e7cf253e10c',1,'graphchi::sharder']]],
['preprocessing_5fadd_5fedge',['preprocessing_add_edge',['../classgraphchi_1_1sharder.html#ad902ff8fdee18b7eb5193fabd25d8d49',1,'graphchi::sharder']]],
['procid',['procid',['../classgraphlab_1_1icontext.html#ab57348d56fb08bd10f3edbccc4137cb1',1,'graphlab::icontext']]]
];
| JavaScript |
var searchData=
[
['vertex_5fdata',['vertex_data',['../structvertex__data.html#a7f177e8488c52777a14aef50256dd489',1,'vertex_data']]],
['vertex_5fid',['vertex_id',['../classgraphchi_1_1graphchi__edge.html#a5d55d4d82a58faa5858dfb898f2258d6',1,'graphchi::graphchi_edge']]]
];
| JavaScript |
var searchData=
[
['cgi_5fenv_5fblock',['cgi_env_block',['../structcgi__env__block.html',1,'']]],
['communitydetectionprogram',['CommunityDetectionProgram',['../struct_community_detection_program.html',1,'']]],
['conditional',['conditional',['../classgraphchi_1_1conditional.html',1,'graphchi']]],
['connectedcomponentsprogram',['ConnectedComponentsProgram',['../struct_connected_components_program.html',1,'']]],
['connection',['Connection',['../classmongoose_1_1_connection.html',1,'mongoose']]],
['created_5fedge',['created_edge',['../structgraphchi_1_1created__edge.html',1,'graphchi']]]
];
| JavaScript |
var searchData=
[
['edge',['edge',['../structedge.html',1,'']]],
['edge_5fbuffer_5fflat',['edge_buffer_flat',['../classgraphchi_1_1edge__buffer__flat.html',1,'graphchi']]],
['edge_5fdata',['edge_data',['../structedge__data.html',1,'']]],
['edge_5fwith_5fvalue',['edge_with_value',['../structgraphchi_1_1edge__with__value.html',1,'graphchi']]],
['empty',['empty',['../structgraphlab_1_1empty.html',1,'graphlab']]],
['error_5faggregator',['error_aggregator',['../structerror__aggregator.html',1,'']]]
];
| JavaScript |
var searchData=
[
['vertex_5faggregator_2ehpp',['vertex_aggregator.hpp',['../vertex__aggregator_8hpp.html',1,'']]],
['vertex_5fdata_2ehpp',['vertex_data.hpp',['../vertex__data_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['imetrics_5freporter_2ehpp',['imetrics_reporter.hpp',['../imetrics__reporter_8hpp.html',1,'']]],
['ioutil_2ehpp',['ioutil.hpp',['../ioutil_8hpp.html',1,'']]],
['ischeduler_2ehpp',['ischeduler.hpp',['../ischeduler_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['gather_5ftype',['gather_type',['../classgraphlab_1_1icontext.html#ae1699cad574dda8cdb91d639a9c82d9e',1,'graphlab::icontext']]],
['graph_5ftype',['graph_type',['../classgraphlab_1_1icontext.html#adeea37e06c012067a2ec57cd0d14cbac',1,'graphlab::icontext::graph_type()'],['../als__vertex__program_8hpp.html#ab9cfd2cad1698282b6c7fd7f7e7fd459',1,'graph_type(): als_vertex_program.hpp']]]
];
| JavaScript |
var searchData=
[
['data_5frole_5ftype',['data_role_type',['../structedge__data.html#a058121c45cac9d350dd70939a023b55d',1,'edge_data']]]
];
| JavaScript |
var searchData=
[
['file_5flogger',['file_logger',['../classfile__logger.html#a97b486960a56b3ca3bc657cfa9645cc9',1,'file_logger']]],
['first_5fvertex_5fid',['first_vertex_id',['../classgraphchi_1_1degree__data.html#a25034df5dabb2bf19a753c8ecf8e3c18',1,'graphchi::degree_data::first_vertex_id()'],['../classgraphchi_1_1vertex__data__store.html#a548b5d8cf0b7c1fdc358397b06fa315c',1,'graphchi::vertex_data_store::first_vertex_id()']]],
['flush',['flush',['../classgraphchi_1_1sliding__shard.html#a34320af733a89ca6a80d0375c86f70d2',1,'graphchi::sliding_shard']]]
];
| JavaScript |
var searchData=
[
['chifilenames_2ehpp',['chifilenames.hpp',['../chifilenames_8hpp.html',1,'']]],
['cmdopts_2ehpp',['cmdopts.hpp',['../cmdopts_8hpp.html',1,'']]],
['communitydetection_2ecpp',['communitydetection.cpp',['../communitydetection_8cpp.html',1,'']]],
['configfile_2ehpp',['configfile.hpp',['../configfile_8hpp.html',1,'']]],
['connectedcomponents_2ecpp',['connectedcomponents.cpp',['../connectedcomponents_8cpp.html',1,'']]],
['conversions_2ehpp',['conversions.hpp',['../conversions_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['managed_5fpwritea_5fasync',['managed_pwritea_async',['../classgraphchi_1_1stripedio.html#a8fa21b2d669bd4ae553dffe483932fa9',1,'graphchi::stripedio']]],
['metrics_5freport',['metrics_report',['../namespacegraphchi.html#ac96bf710c0bf6795fde16808d06aec61',1,'graphchi']]]
];
| JavaScript |
var searchData=
[
['highmask',['HIGHMASK',['../graph__objects_8hpp.html#af358993266b0a9eb7aabdf5abe2c7f67',1,'graph_objects.hpp']]],
['html_5freporter',['html_reporter',['../classgraphchi_1_1html__reporter.html',1,'graphchi']]],
['html_5freporter_2ehpp',['html_reporter.hpp',['../reps_2html__reporter_8hpp.html',1,'']]],
['html_5freporter_2ehpp',['html_reporter.hpp',['../reporters_2html__reporter_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['coloroutput',['COLOROUTPUT',['../logger_8hpp.html#a407629ed2d44412adc1a9fd1bf8fc35b',1,'logger.hpp']]]
];
| JavaScript |
var searchData=
[
['factor',['factor',['../structvertex__data.html#a652e9543fe205c866ff39a09fda2ff13',1,'vertex_data']]]
];
| JavaScript |
var searchData=
[
['message_5ftype',['message_type',['../classgraphlab_1_1icontext.html#a64f23efbbf13a9421b8efada6966643b',1,'graphlab::icontext']]]
];
| JavaScript |
var searchData=
[
['de',['de',['../structde.html',1,'']]],
['degree',['degree',['../structgraphchi_1_1degree.html',1,'graphchi']]],
['degree_5fdata',['degree_data',['../classgraphchi_1_1degree__data.html',1,'graphchi']]],
['dense_5fadj',['dense_adj',['../structdense__adj.html',1,'']]],
['dense_5fbitset',['dense_bitset',['../classgraphchi_1_1dense__bitset.html',1,'graphchi']]],
['distributed_5fgraph',['distributed_graph',['../structgraphlab_1_1distributed__graph.html',1,'graphlab']]]
];
| JavaScript |
var searchData=
[
['basic_5fdynamicengine_5fsmoketest_2ecpp',['basic_dynamicengine_smoketest.cpp',['../basic__dynamicengine__smoketest_8cpp.html',1,'']]],
['basic_5fdynamicengine_5fsmoketest2_2ecpp',['basic_dynamicengine_smoketest2.cpp',['../basic__dynamicengine__smoketest2_8cpp.html',1,'']]],
['basic_5freporter_2ehpp',['basic_reporter.hpp',['../reporters_2basic__reporter_8hpp.html',1,'']]],
['basic_5freporter_2ehpp',['basic_reporter.hpp',['../reps_2basic__reporter_8hpp.html',1,'']]],
['basic_5fsmoketest_2ecpp',['basic_smoketest.cpp',['../basic__smoketest_8cpp.html',1,'']]],
['bitset_5fscheduler_2ehpp',['bitset_scheduler.hpp',['../bitset__scheduler_8hpp.html',1,'']]],
['bulksync_5ffunctional_5ftest_2ecpp',['bulksync_functional_test.cpp',['../bulksync__functional__test_8cpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['spinlock',['spinlock',['../namespacegraphchi.html#a86d970062f7c0596b53faaabd29cf9a8',1,'graphchi']]]
];
| JavaScript |
var searchData=
[
['file_5flogger',['file_logger',['../classfile__logger.html',1,'']]],
['file_5freporter',['file_reporter',['../classgraphchi_1_1file__reporter.html',1,'graphchi']]],
['functional_5fengine',['functional_engine',['../classgraphchi_1_1functional__engine.html',1,'graphchi']]],
['functional_5fkernel',['functional_kernel',['../structgraphchi_1_1functional__kernel.html',1,'graphchi']]],
['functional_5fkernel_3c_20float_2c_20float_20_3e',['functional_kernel< float, float >',['../structgraphchi_1_1functional__kernel.html',1,'graphchi']]],
['functional_5fkernel_3c_20int_2c_20int_20_3e',['functional_kernel< int, int >',['../structgraphchi_1_1functional__kernel.html',1,'graphchi']]],
['functional_5fvertex_5funweighted_5fbulksync',['functional_vertex_unweighted_bulksync',['../classgraphchi_1_1functional__vertex__unweighted__bulksync.html',1,'graphchi']]],
['functional_5fvertex_5funweighted_5fsemisync',['functional_vertex_unweighted_semisync',['../classgraphchi_1_1functional__vertex__unweighted__semisync.html',1,'graphchi']]],
['functionalprogramproxybulksync',['FunctionalProgramProxyBulkSync',['../classgraphchi_1_1_functional_program_proxy_bulk_sync.html',1,'graphchi']]],
['functionalprogramproxysemisync',['FunctionalProgramProxySemisync',['../classgraphchi_1_1_functional_program_proxy_semisync.html',1,'graphchi']]]
];
| JavaScript |
var searchData=
[
['operator_2b_3d',['operator+=',['../classgather__type.html#a672f8aac3ab0b1bb48e857b77307f621',1,'gather_type']]]
];
| JavaScript |
var searchData=
[
['highmask',['HIGHMASK',['../graph__objects_8hpp.html#af358993266b0a9eb7aabdf5abe2c7f67',1,'graph_objects.hpp']]]
];
| JavaScript |
var searchData=
[
['sblock',['sblock',['../structgraphchi_1_1sblock.html',1,'graphchi']]],
['semaphore',['semaphore',['../classgraphchi_1_1semaphore.html',1,'graphchi']]],
['session',['session',['../structsession.html',1,'']]],
['sharder',['sharder',['../classgraphchi_1_1sharder.html',1,'graphchi']]],
['sharderpreprocessor',['SharderPreprocessor',['../classgraphchi_1_1_sharder_preprocessor.html',1,'graphchi']]],
['sliding_5fshard',['sliding_shard',['../classgraphchi_1_1sliding__shard.html',1,'graphchi']]],
['smoketest_5fprogram',['smoketest_program',['../structsmoketest__program.html',1,'']]],
['smoketestprogram',['SmokeTestProgram',['../struct_smoke_test_program.html',1,'']]],
['smoketestprogram2',['SmokeTestProgram2',['../struct_smoke_test_program2.html',1,'']]],
['socket',['socket',['../structsocket.html',1,'']]],
['spinrwlock',['spinrwlock',['../classgraphchi_1_1spinrwlock.html',1,'graphchi']]],
['ssl_5ffunc',['ssl_func',['../structssl__func.html',1,'']]],
['streambuff_5ftls_5fentry',['streambuff_tls_entry',['../structlogger__impl_1_1streambuff__tls__entry.html',1,'logger_impl']]],
['streaming_5ftask',['streaming_task',['../structgraphchi_1_1streaming__task.html',1,'graphchi']]],
['stripe_5fchunk',['stripe_chunk',['../structgraphchi_1_1stripe__chunk.html',1,'graphchi']]],
['stripedio',['stripedio',['../classgraphchi_1_1stripedio.html',1,'graphchi']]],
['sum_5fpriority',['sum_priority',['../structgraphlab_1_1messages_1_1sum__priority.html',1,'graphlab::messages']]],
['sumcallback',['SumCallback',['../classgraphchi_1_1_sum_callback.html',1,'graphchi']]],
['synchronized_5fqueue',['synchronized_queue',['../classgraphchi_1_1synchronized__queue.html',1,'graphchi']]],
['synchronized_5fqueue_3c_20iotask_20_3e',['synchronized_queue< iotask >',['../classgraphchi_1_1synchronized__queue.html',1,'graphchi']]]
];
| JavaScript |
var searchData=
[
['als_2ehpp',['als.hpp',['../als_8hpp.html',1,'']]],
['als_5fedgefactors_2ecpp',['als_edgefactors.cpp',['../als__edgefactors_8cpp.html',1,'']]],
['als_5fgraphlab_2ecpp',['als_graphlab.cpp',['../als__graphlab_8cpp.html',1,'']]],
['als_5fvertex_5fprogram_2ehpp',['als_vertex_program.hpp',['../als__vertex__program_8hpp.html',1,'']]],
['als_5fvertices_5finmem_2ecpp',['als_vertices_inmem.cpp',['../als__vertices__inmem_8cpp.html',1,'']]],
['application_5ftemplate_2ecpp',['application_template.cpp',['../application__template_8cpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['_5f_5fdel_5f_5f',['__del__',['../classmongoose_1_1_mongoose.html#adc0deac4be72ac03798b1c1f37302b75',1,'mongoose::Mongoose']]]
];
| JavaScript |
var searchData=
[
['testmongoserver',['TestMongoServer',['../class_test_mongo_server.html',1,'']]],
['thrinfo',['thrinfo',['../structgraphchi_1_1thrinfo.html',1,'graphchi']]],
['trianglecountingprogram',['TriangleCountingProgram',['../struct_triangle_counting_program.html',1,'']]]
];
| JavaScript |
var searchData=
[
['pagerank_2ecpp',['pagerank.cpp',['../pagerank_8cpp.html',1,'']]],
['pagerank_5ffunctional_2ecpp',['pagerank_functional.cpp',['../pagerank__functional_8cpp.html',1,'']]],
['pagerank_5fkernel',['pagerank_kernel',['../structpagerank__kernel.html',1,'']]],
['pagerankprogram',['PagerankProgram',['../struct_pagerank_program.html',1,'']]],
['paircontainer',['PairContainer',['../structgraphchi_1_1_pair_container.html',1,'graphchi']]],
['paircontainer_3c_20kernel_3a_3aedgedatatype_20_3e',['PairContainer< KERNEL::EdgeDataType >',['../structgraphchi_1_1_pair_container.html',1,'graphchi']]],
['parse',['parse',['../namespacegraphchi.html#ace1ff5b8c766b05e4d3a74cc21038a6b',1,'graphchi']]],
['pinned_5ffile',['pinned_file',['../structgraphchi_1_1pinned__file.html',1,'graphchi']]],
['pinned_5fsession',['pinned_session',['../classgraphchi_1_1stripedio.html#ab84bcc570151709fba172c3159125d54',1,'graphchi::stripedio']]],
['plotter_2ehpp',['plotter.hpp',['../plotter_8hpp.html',1,'']]],
['post_5fdelta',['post_delta',['../classgraphlab_1_1icontext.html#a9c85c9b34ae08d72a28ca5e698a34482',1,'graphlab::icontext']]],
['prediction_5fsaver',['prediction_saver',['../structprediction__saver.html',1,'']]],
['preprocessed_5ffile_5fexists',['preprocessed_file_exists',['../classgraphchi_1_1sharder.html#a9473263ad2cfc83c11100e7cf253e10c',1,'graphchi::sharder']]],
['preprocessing_5fadd_5fedge',['preprocessing_add_edge',['../classgraphchi_1_1sharder.html#ad902ff8fdee18b7eb5193fabd25d8d49',1,'graphchi::sharder']]],
['procid',['procid',['../classgraphlab_1_1icontext.html#ab57348d56fb08bd10f3edbccc4137cb1',1,'graphlab::icontext']]],
['program',['Program',['../class_program.html',1,'']]],
['pthread_5ftools_2ehpp',['pthread_tools.hpp',['../pthread__tools_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['target',['target',['../structgraphlab_1_1_graph_lab_edge_wrapper.html#a6c4d5eaded1d40e10775707ff7189dc7',1,'graphlab::GraphLabEdgeWrapper']]]
];
| JavaScript |
var searchData=
[
['html_5freporter',['html_reporter',['../classgraphchi_1_1html__reporter.html',1,'graphchi']]]
];
| JavaScript |
var searchData=
[
['barrier',['barrier',['../classgraphchi_1_1barrier.html',1,'graphchi']]],
['basic_5freporter',['basic_reporter',['../classgraphchi_1_1basic__reporter.html',1,'graphchi']]],
['bidirectional_5flabel',['bidirectional_label',['../structbidirectional__label.html',1,'']]],
['bitset_5fscheduler',['bitset_scheduler',['../classgraphchi_1_1bitset__scheduler.html',1,'graphchi']]]
];
| JavaScript |
var searchData=
[
['id',['id',['../structgraphlab_1_1_graph_lab_vertex_wrapper.html#abcc164070e228a8133c627703c1917f0',1,'graphlab::GraphLabVertexWrapper']]],
['init',['init',['../structgraphlab_1_1ivertex__program.html#ad371b64021ac80eaae332319dec41723',1,'graphlab::ivertex_program']]],
['initialize_5fsliding_5fshards',['initialize_sliding_shards',['../classgraphchi_1_1graphchi__dynamicgraph__engine.html#a193d7e29b40c29be2e9bdaab14834fe9',1,'graphchi::graphchi_dynamicgraph_engine']]],
['intersection_5fsize',['intersection_size',['../classadjlist__container.html#aa9956e2b1bdbd885ec58037d84febef6',1,'adjlist_container']]],
['is_5fany_5fvertex_5fscheduled',['is_any_vertex_scheduled',['../classgraphchi_1_1graphchi__engine.html#a56a595a75cb53c418ce810b9423d2b6b',1,'graphchi::graphchi_engine']]],
['iteration',['iteration',['../classgraphlab_1_1icontext.html#a29496c1e0434d716726ac2a703c81f32',1,'graphlab::icontext']]]
];
| JavaScript |
var searchData=
[
['edgebuffers_2ehpp',['edgebuffers.hpp',['../edgebuffers_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['toplist_2ehpp',['toplist.hpp',['../toplist_8hpp.html',1,'']]],
['trianglecounting_2ecpp',['trianglecounting.cpp',['../trianglecounting_8cpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['graph_5fobjects_2ehpp',['graph_objects.hpp',['../graph__objects_8hpp.html',1,'']]],
['graphchi_5fbasic_5fincludes_2ehpp',['graphchi_basic_includes.hpp',['../graphchi__basic__includes_8hpp.html',1,'']]],
['graphchi_5fcontext_2ehpp',['graphchi_context.hpp',['../graphchi__context_8hpp.html',1,'']]],
['graphchi_5fdynamicgraph_5fengine_2ehpp',['graphchi_dynamicgraph_engine.hpp',['../graphchi__dynamicgraph__engine_8hpp.html',1,'']]],
['graphchi_5fengine_2ehpp',['graphchi_engine.hpp',['../graphchi__engine_8hpp.html',1,'']]],
['graphchi_5fgraphlabv2_5f1_2ehpp',['graphchi_graphlabv2_1.hpp',['../graphchi__graphlabv2__1_8hpp.html',1,'']]],
['graphchi_5fprogram_2ehpp',['graphchi_program.hpp',['../graphchi__program_8hpp.html',1,'']]],
['graphlab_2ehpp',['graphlab.hpp',['../graphlab_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['variable_5fis_5fnot_5fused',['VARIABLE_IS_NOT_USED',['../graph__objects_8hpp.html#a374bd2d6076b95bff33ea625a1e25e09',1,'VARIABLE_IS_NOT_USED(): graph_objects.hpp'],['../conversions_8hpp.html#a374bd2d6076b95bff33ea625a1e25e09',1,'VARIABLE_IS_NOT_USED(): conversions.hpp'],['../cmdopts_8hpp.html#a374bd2d6076b95bff33ea625a1e25e09',1,'VARIABLE_IS_NOT_USED(): cmdopts.hpp']]]
];
| JavaScript |
var searchData=
[
['_7eicontext',['~icontext',['../classgraphlab_1_1icontext.html#a8939d5bec338e978f8892ec8d4e1d7eb',1,'graphlab::icontext']]]
];
| JavaScript |
var searchData=
[
['orderbydegree',['OrderByDegree',['../classgraphchi_1_1_order_by_degree.html',1,'graphchi']]]
];
| JavaScript |
var searchData=
[
['edge',['edge',['../structedge.html',1,'edge'],['../classgraphchi_1_1graphchi__vertex.html#a79aebd315e4f333e8ba0e756c265883a',1,'graphchi::graphchi_vertex::edge()']]],
['edge_5fbuffer_5fflat',['edge_buffer_flat',['../classgraphchi_1_1edge__buffer__flat.html',1,'graphchi']]],
['edge_5fdata',['edge_data',['../structedge__data.html',1,'edge_data'],['../structedge__data.html#a98967d7ad71e7ef996e6b9727e97949c',1,'edge_data::edge_data()']]],
['edge_5fwith_5fvalue',['edge_with_value',['../structgraphchi_1_1edge__with__value.html',1,'graphchi']]],
['edgebuffers_2ehpp',['edgebuffers.hpp',['../edgebuffers_8hpp.html',1,'']]],
['elapsed_5fseconds',['elapsed_seconds',['../classgraphlab_1_1icontext.html#a863010fd33f3721162d253af3583f8bb',1,'graphlab::icontext']]],
['empty',['empty',['../structgraphlab_1_1empty.html',1,'graphlab']]],
['end_5fpreprocessing',['end_preprocessing',['../classgraphchi_1_1sharder.html#aebb6e75ba00e4f4016b9559e45254142',1,'graphchi::sharder']]],
['error_5faggregator',['error_aggregator',['../structerror__aggregator.html',1,'']]],
['execute_5fsharding',['execute_sharding',['../classgraphchi_1_1sharder.html#a8c1af4eca3037578aa7bd5b7cc431c8c',1,'graphchi::sharder']]],
['extend_5fpivotrange',['extend_pivotrange',['../classadjlist__container.html#ac43be3ce9e2e0f19cc1d52e13f766e28',1,'adjlist_container']]],
['extract_5fl2_5ferror',['extract_l2_error',['../als__vertex__program_8hpp.html#afb0b8a4655197699932baa2bac0cc465',1,'als_vertex_program.hpp']]]
];
| JavaScript |
var searchData=
[
['max_5fpriority',['max_priority',['../structgraphlab_1_1messages_1_1max__priority.html',1,'graphlab::messages']]],
['md5context',['MD5Context',['../struct_m_d5_context.html',1,'']]],
['memory_5fshard',['memory_shard',['../classgraphchi_1_1memory__shard.html',1,'graphchi']]],
['message',['message',['../structmessage.html',1,'']]],
['metrics',['metrics',['../classgraphchi_1_1metrics.html',1,'graphchi']]],
['metrics_5fentry',['metrics_entry',['../structgraphchi_1_1metrics__entry.html',1,'graphchi']]],
['mg_5fauth_5fheader',['mg_auth_header',['../structmg__auth__header.html',1,'']]],
['mg_5fconnection',['mg_connection',['../structmg__connection.html',1,'']]],
['mg_5fcontext',['mg_context',['../structmg__context.html',1,'']]],
['mg_5fheader',['mg_header',['../structmg__request__info_1_1mg__header.html',1,'mg_request_info']]],
['mg_5fheader',['mg_header',['../classmongoose_1_1mg__header.html',1,'mongoose']]],
['mg_5frequest_5finfo',['mg_request_info',['../classmongoose_1_1mg__request__info.html',1,'mongoose']]],
['mg_5frequest_5finfo',['mg_request_info',['../structmg__request__info.html',1,'']]],
['mgstat',['mgstat',['../structmgstat.html',1,'']]],
['mmoutputter',['MMOutputter',['../struct_m_m_outputter.html',1,'']]],
['mongoose',['Mongoose',['../class_mongoose.html',1,'']]],
['mongoose',['Mongoose',['../classmongoose_1_1_mongoose.html',1,'mongoose']]],
['mongooseconnection',['MongooseConnection',['../class_mongoose_connection.html',1,'']]],
['mongooseconnection',['MongooseConnection',['../classmongoose_1_1_mongoose_connection.html',1,'mongoose']]],
['mongooseheader',['MongooseHeader',['../struct_mongoose_header.html',1,'']]],
['mongooserequest',['MongooseRequest',['../classmongoose_1_1_mongoose_request.html',1,'mongoose']]],
['mongooserequestinfo',['MongooseRequestInfo',['../struct_mongoose_request_info.html',1,'']]],
['mongooseresponse',['MongooseResponse',['../classmongoose_1_1_mongoose_response.html',1,'mongoose']]],
['mongooseserver',['MongooseServer',['../classmongoose_1_1_mongoose_server.html',1,'mongoose']]],
['mutex',['mutex',['../classgraphchi_1_1mutex.html',1,'graphchi']]],
['mygraphchiprogram',['MyGraphChiProgram',['../struct_my_graph_chi_program.html',1,'']]]
];
| JavaScript |
var searchData=
[
['null_5freporter_2ehpp',['null_reporter.hpp',['../reporters_2null__reporter_8hpp.html',1,'']]],
['null_5freporter_2ehpp',['null_reporter.hpp',['../reps_2null__reporter_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['html_5freporter_2ehpp',['html_reporter.hpp',['../reporters_2html__reporter_8hpp.html',1,'']]],
['html_5freporter_2ehpp',['html_reporter.hpp',['../reps_2html__reporter_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['sharder_2ehpp',['sharder.hpp',['../sharder_8hpp.html',1,'']]],
['sharder_5fbasic_2ecpp',['sharder_basic.cpp',['../sharder__basic_8cpp.html',1,'']]],
['slidingshard_2ehpp',['slidingshard.hpp',['../slidingshard_8hpp.html',1,'']]],
['streaming_5fpagerank_2ecpp',['streaming_pagerank.cpp',['../streaming__pagerank_8cpp.html',1,'']]],
['stripedio_2ehpp',['stripedio.hpp',['../stripedio_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['file_5freporter_2ehpp',['file_reporter.hpp',['../reporters_2file__reporter_8hpp.html',1,'']]],
['file_5freporter_2ehpp',['file_reporter.hpp',['../reps_2file__reporter_8hpp.html',1,'']]],
['functional_5fapi_2ehpp',['functional_api.hpp',['../functional__api_8hpp.html',1,'']]],
['functional_5fbulksync_2ehpp',['functional_bulksync.hpp',['../functional__bulksync_8hpp.html',1,'']]],
['functional_5fdefs_2ehpp',['functional_defs.hpp',['../functional__defs_8hpp.html',1,'']]],
['functional_5fengine_2ehpp',['functional_engine.hpp',['../functional__engine_8hpp.html',1,'']]],
['functional_5fsemisync_2ehpp',['functional_semisync.hpp',['../functional__semisync_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['new_5fedge_5fbuffers',['new_edge_buffers',['../classgraphchi_1_1graphchi__dynamicgraph__engine.html#a202412dee4896fd29c90de6b7bb85d5a',1,'graphchi::graphchi_dynamicgraph_engine']]],
['nlatent',['NLATENT',['../structvertex__data.html#adeae9fb728f92ce36bdf7daf6c1110ac',1,'vertex_data']]],
['nupdates',['nupdates',['../structvertex__data.html#a0992af23f5489f13f07bc924d68e6379',1,'vertex_data']]]
];
| JavaScript |
var searchData=
[
['_7eicontext',['~icontext',['../classgraphlab_1_1icontext.html#a8939d5bec338e978f8892ec8d4e1d7eb',1,'graphlab::icontext']]]
];
| JavaScript |
var searchData=
[
['pagerank_2ecpp',['pagerank.cpp',['../pagerank_8cpp.html',1,'']]],
['pagerank_5ffunctional_2ecpp',['pagerank_functional.cpp',['../pagerank__functional_8cpp.html',1,'']]],
['plotter_2ehpp',['plotter.hpp',['../plotter_8hpp.html',1,'']]],
['pthread_5ftools_2ehpp',['pthread_tools.hpp',['../pthread__tools_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['labelanalysis_2ehpp',['labelanalysis.hpp',['../labelanalysis_8hpp.html',1,'']]],
['logger_2ehpp',['logger.hpp',['../logger_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['cerr',['cerr',['../classgraphlab_1_1icontext.html#a9f7cbf4f381fa287ae2ebfc7ee356810',1,'graphlab::icontext']]],
['cgi_5fenv_5fblock',['cgi_env_block',['../structcgi__env__block.html',1,'']]],
['chifilenames_2ehpp',['chifilenames.hpp',['../chifilenames_8hpp.html',1,'']]],
['clear_5fbit',['clear_bit',['../classgraphchi_1_1dense__bitset.html#af6011c68b0b1427b89ff077591441185',1,'graphchi::dense_bitset']]],
['clear_5fgather_5fcache',['clear_gather_cache',['../classgraphlab_1_1icontext.html#a9f7c49ee6b4a59be90ae65841597bd5b',1,'graphlab::icontext']]],
['cmdopts_2ehpp',['cmdopts.hpp',['../cmdopts_8hpp.html',1,'']]],
['coloroutput',['COLOROUTPUT',['../logger_8hpp.html#a407629ed2d44412adc1a9fd1bf8fc35b',1,'logger.hpp']]],
['commit',['commit',['../classgraphchi_1_1memory__shard.html#a7b1304bddd0f80bda65a3e15ac7e7e3e',1,'graphchi::memory_shard::commit()'],['../classgraphchi_1_1sliding__shard.html#a6b6d3d549555c85ab3ee4bb30c678b02',1,'graphchi::sliding_shard::commit()']]],
['commit_5fgraph_5fchanges',['commit_graph_changes',['../classgraphchi_1_1graphchi__dynamicgraph__engine.html#a1e24d2f5bd6b215462fd6011cc1a0d48',1,'graphchi::graphchi_dynamicgraph_engine']]],
['communitydetection_2ecpp',['communitydetection.cpp',['../communitydetection_8cpp.html',1,'']]],
['communitydetectionprogram',['CommunityDetectionProgram',['../struct_community_detection_program.html',1,'']]],
['conditional',['conditional',['../classgraphchi_1_1conditional.html',1,'graphchi']]],
['configfile_2ehpp',['configfile.hpp',['../configfile_8hpp.html',1,'']]],
['connectedcomponents_2ecpp',['connectedcomponents.cpp',['../connectedcomponents_8cpp.html',1,'']]],
['connectedcomponentsprogram',['ConnectedComponentsProgram',['../struct_connected_components_program.html',1,'']]],
['connection',['Connection',['../classmongoose_1_1_connection.html',1,'mongoose']]],
['conversions_2ehpp',['conversions.hpp',['../conversions_8hpp.html',1,'']]],
['convert',['convert',['../namespacegraphchi.html#adbb0197281c952e57861a4a243f2148f',1,'graphchi']]],
['convert_5fadjlist',['convert_adjlist',['../namespacegraphchi.html#aad30a81856fd56402d4ced270e5ff0aa',1,'graphchi']]],
['convert_5fedgelist',['convert_edgelist',['../namespacegraphchi.html#a99513ad299ae1d25acb71aa322856e5e',1,'graphchi']]],
['convert_5fmatrixmarket_5ffor_5fals',['convert_matrixmarket_for_ALS',['../als_8hpp.html#aac24c18c19a226199f0b86cabb8ad63d',1,'als.hpp']]],
['convert_5fmatrixmarket_5ffor_5fals_5fgraphlab',['convert_matrixmarket_for_ALS_graphlab',['../als__graphlab_8cpp.html#a02f78fa953f1365d88783a04501f4016',1,'als_graphlab.cpp']]],
['cout',['cout',['../classgraphlab_1_1icontext.html#a7f827dd93aba5809b69cf659554f8869',1,'graphlab::icontext']]],
['cp',['cp',['../classgraphchi_1_1graphchi__dynamicgraph__engine.html#a62726a85f6c46c925bc44f85b98ef94a',1,'graphchi::graphchi_dynamicgraph_engine']]],
['create_5fdegree_5fhandler',['create_degree_handler',['../classgraphchi_1_1graphchi__dynamicgraph__engine.html#a76d10a9a93cbd83143084f10900255b6',1,'graphchi::graphchi_dynamicgraph_engine']]],
['created_5fedge',['created_edge',['../structgraphchi_1_1created__edge.html',1,'graphchi']]]
];
| JavaScript |
var searchData=
[
['null_5freporter',['null_reporter',['../classgraphchi_1_1null__reporter.html',1,'graphchi']]],
['null_5fstream',['null_stream',['../structnull__stream.html',1,'']]]
];
| JavaScript |
var searchData=
[
['labelanalysis_2ehpp',['labelanalysis.hpp',['../labelanalysis_8hpp.html',1,'']]],
['labelcount_5ftt',['labelcount_tt',['../structlabelcount__tt.html',1,'']]],
['latentvec_5ft',['latentvec_t',['../structlatentvec__t.html',1,'']]],
['load',['load',['../classgraphchi_1_1degree__data.html#a845b713beb8419274e2b5312ddd8bc5f',1,'graphchi::degree_data::load()'],['../classgraphchi_1_1vertex__data__store.html#a4885bac577540a6dcf0be31af0c3572c',1,'graphchi::vertex_data_store::load()']]],
['load_5fvertex_5fintervals',['load_vertex_intervals',['../classgraphchi_1_1graphchi__engine.html#a8c4fe7f4bccdbb667e6d4af8d35a07c0',1,'graphchi::graphchi_engine']]],
['local_5fid',['local_id',['../structgraphlab_1_1_graph_lab_vertex_wrapper.html#a751dcd1a2180f251d4ad93175a89602f',1,'graphlab::GraphLabVertexWrapper']]],
['log_5fchange',['log_change',['../structgraphchi_1_1graphchi__context.html#a28176afb423f7351d9ec14569eeb610d',1,'graphchi::graphchi_context']]],
['log_5fdebug',['LOG_DEBUG',['../logger_8hpp.html#a6ff63e8955665c4a58b1598f2b07c51a',1,'logger.hpp']]],
['log_5fdispatch',['log_dispatch',['../structlog__dispatch.html',1,'']]],
['log_5fdispatch_3c_20false_20_3e',['log_dispatch< false >',['../structlog__dispatch_3_01false_01_4.html',1,'']]],
['log_5fdispatch_3c_20true_20_3e',['log_dispatch< true >',['../structlog__dispatch_3_01true_01_4.html',1,'']]],
['log_5ferror',['LOG_ERROR',['../logger_8hpp.html#aced66975c154ea0e2a8ec3bc818b4e08',1,'logger.hpp']]],
['log_5ffatal',['LOG_FATAL',['../logger_8hpp.html#ac2164369b4d2bf72296f8ba6ea576ecf',1,'logger.hpp']]],
['log_5finfo',['LOG_INFO',['../logger_8hpp.html#aeb4f36db01bd128c7afeac5889dac311',1,'logger.hpp']]],
['log_5fnone',['LOG_NONE',['../logger_8hpp.html#a1632479322efa3952798f98177b54471',1,'logger.hpp']]],
['log_5fstream_5fdispatch',['log_stream_dispatch',['../structlog__stream__dispatch.html',1,'']]],
['log_5fstream_5fdispatch_3c_20false_20_3e',['log_stream_dispatch< false >',['../structlog__stream__dispatch_3_01false_01_4.html',1,'']]],
['log_5fstream_5fdispatch_3c_20true_20_3e',['log_stream_dispatch< true >',['../structlog__stream__dispatch_3_01true_01_4.html',1,'']]],
['log_5fwarning',['LOG_WARNING',['../logger_8hpp.html#adf4476a6a4ea6c74231c826e899d7189',1,'logger.hpp']]],
['logger',['logger',['../logger_8hpp.html#ab58cdd006f6b33cbe171ab32effef95b',1,'logger.hpp']]],
['logger_2ehpp',['logger.hpp',['../logger_8hpp.html',1,'']]]
];
| JavaScript |
var searchData=
[
['write_5fshards',['write_shards',['../classgraphchi_1_1sharder.html#acba67408a81dfaa5fdac73c1d61f4631',1,'graphchi::sharder']]]
];
| JavaScript |
var searchData=
[
['randomize',['randomize',['../structvertex__data.html#a4caa51a3710a504d31089b0865bb626d',1,'vertex_data']]],
['read_5fnext_5fvertices',['read_next_vertices',['../classgraphchi_1_1sliding__shard.html#a03c71ac33471a3239b63ce5e7033f08d',1,'graphchi::sliding_shard']]],
['read_5foutedges',['read_outedges',['../classgraphchi_1_1functional__vertex__unweighted__bulksync.html#a061aee312fc67647fe56c4acd87fc6ee',1,'graphchi::functional_vertex_unweighted_bulksync']]],
['readquerystring',['readQueryString',['../classmongoose_1_1_mongoose_request.html#ad6d55d79248cb560ffdecace8937e76b',1,'mongoose::MongooseRequest']]],
['refcountptr',['refcountptr',['../structgraphchi_1_1refcountptr.html',1,'graphchi']]],
['release_5fprior_5fto_5foffset',['release_prior_to_offset',['../classgraphchi_1_1sliding__shard.html#a9b8e6ee8b170b069aa250d8e6d2c266f',1,'graphchi::sliding_shard']]],
['residual',['residual',['../structvertex__data.html#a89b8e42b50a16c7c49a1c76b5b319853',1,'vertex_data']]],
['rmse',['rmse',['../als_8hpp.html#a4a31cf557efa8c68c5c0a73a5405ba3f',1,'als.hpp']]],
['role',['role',['../structedge__data.html#a3fbba49eb9690a4fdeeda275d6c9cad9',1,'edge_data']]],
['run',['run',['../classgraphchi_1_1graphchi__engine.html#a41254a769f3b0367b08f48bf2e16aa86',1,'graphchi::graphchi_engine']]],
['run_5ffunctional_5funweighted_5fsemisynchronous',['run_functional_unweighted_semisynchronous',['../namespacegraphchi.html#a70ac542b16515cd1f5e4bcdb4726ce1f',1,'graphchi']]],
['run_5ffunctional_5funweighted_5fsynchronous',['run_functional_unweighted_synchronous',['../namespacegraphchi.html#abc244c04632c39d92dd3e16916da6bb9',1,'graphchi']]],
['rwlock',['rwlock',['../classgraphchi_1_1rwlock.html',1,'graphchi']]]
];
| JavaScript |
var searchData=
[
['obs',['obs',['../structedge__data.html#a1fc50f971f9fdbb4c9c90e33bda1c758',1,'edge_data']]],
['operator_2b_3d',['operator+=',['../classgather__type.html#a672f8aac3ab0b1bb48e857b77307f621',1,'gather_type']]],
['orderbydegree',['OrderByDegree',['../classgraphchi_1_1_order_by_degree.html',1,'graphchi']]],
['outputlevel',['OUTPUTLEVEL',['../logger_8hpp.html#a3d18ed817dcda9f54a4f353ccf9b1b36',1,'logger.hpp']]]
];
| JavaScript |
var searchData=
[
['residual',['residual',['../structvertex__data.html#a89b8e42b50a16c7c49a1c76b5b319853',1,'vertex_data']]],
['rmse',['rmse',['../als_8hpp.html#a4a31cf557efa8c68c5c0a73a5405ba3f',1,'als.hpp']]],
['role',['role',['../structedge__data.html#a3fbba49eb9690a4fdeeda275d6c9cad9',1,'edge_data']]]
];
| JavaScript |
var searchData=
[
['target',['target',['../structgraphlab_1_1_graph_lab_edge_wrapper.html#a6c4d5eaded1d40e10775707ff7189dc7',1,'graphlab::GraphLabEdgeWrapper']]],
['testmongoserver',['TestMongoServer',['../class_test_mongo_server.html',1,'']]],
['thrinfo',['thrinfo',['../structgraphchi_1_1thrinfo.html',1,'graphchi']]],
['tolerance',['TOLERANCE',['../classals__vertex__program.html#a4d3fe82f9b913c88361646fecea3e181',1,'als_vertex_program']]],
['toplist_2ehpp',['toplist.hpp',['../toplist_8hpp.html',1,'']]],
['trianglecounting_2ecpp',['trianglecounting.cpp',['../trianglecounting_8cpp.html',1,'']]],
['trianglecountingprogram',['TriangleCountingProgram',['../struct_triangle_counting_program.html',1,'']]]
];
| JavaScript |
var searchData=
[
['xtx',['XtX',['../classgather__type.html#a79352d3ca5b6957aa4b21276c20da59f',1,'gather_type']]],
['xy',['Xy',['../classgather__type.html#a319a1856f1ad204ad8fd13592ab9a201',1,'gather_type']]]
];
| JavaScript |
var searchData=
[
['usa',['usa',['../structusa.html',1,'']]]
];
| JavaScript |
var searchData=
[
['modification_5flock',['modification_lock',['../classgraphchi_1_1graphchi__dynamicgraph__engine.html#a6dd321db58504ad1ed2c0d54387aa160',1,'graphchi::graphchi_dynamicgraph_engine']]]
];
| JavaScript |
var searchData=
[
['_5f_5fdel_5f_5f',['__del__',['../classmongoose_1_1_mongoose.html#adc0deac4be72ac03798b1c1f37302b75',1,'mongoose::Mongoose']]]
];
| JavaScript |
var searchData=
[
['xtx',['XtX',['../classgather__type.html#a79352d3ca5b6957aa4b21276c20da59f',1,'gather_type']]],
['xy',['Xy',['../classgather__type.html#a319a1856f1ad204ad8fd13592ab9a201',1,'gather_type']]]
];
| JavaScript |
var searchData=
[
['managed_5fpwritea_5fasync',['managed_pwritea_async',['../classgraphchi_1_1stripedio.html#a8fa21b2d669bd4ae553dffe483932fa9',1,'graphchi::stripedio']]],
['max_5fpriority',['max_priority',['../structgraphlab_1_1messages_1_1max__priority.html',1,'graphlab::messages']]],
['md5context',['MD5Context',['../struct_m_d5_context.html',1,'']]],
['memory_5fshard',['memory_shard',['../classgraphchi_1_1memory__shard.html',1,'graphchi']]],
['memoryshard_2ehpp',['memoryshard.hpp',['../memoryshard_8hpp.html',1,'']]],
['message',['message',['../structmessage.html',1,'']]],
['message_5ftype',['message_type',['../classgraphlab_1_1icontext.html#a64f23efbbf13a9421b8efada6966643b',1,'graphlab::icontext']]],
['metrics',['metrics',['../classgraphchi_1_1metrics.html',1,'graphchi']]],
['metrics_2ehpp',['metrics.hpp',['../metrics_8hpp.html',1,'']]],
['metrics_5fentry',['metrics_entry',['../structgraphchi_1_1metrics__entry.html',1,'graphchi']]],
['metrics_5freport',['metrics_report',['../namespacegraphchi.html#ac96bf710c0bf6795fde16808d06aec61',1,'graphchi']]],
['mg_5fauth_5fheader',['mg_auth_header',['../structmg__auth__header.html',1,'']]],
['mg_5fconnection',['mg_connection',['../structmg__connection.html',1,'']]],
['mg_5fcontext',['mg_context',['../structmg__context.html',1,'']]],
['mg_5fheader',['mg_header',['../structmg__request__info_1_1mg__header.html',1,'mg_request_info']]],
['mg_5fheader',['mg_header',['../classmongoose_1_1mg__header.html',1,'mongoose']]],
['mg_5frequest_5finfo',['mg_request_info',['../classmongoose_1_1mg__request__info.html',1,'mongoose']]],
['mg_5frequest_5finfo',['mg_request_info',['../structmg__request__info.html',1,'']]],
['mgstat',['mgstat',['../structmgstat.html',1,'']]],
['mmoutputter',['MMOutputter',['../struct_m_m_outputter.html',1,'']]],
['modification_5flock',['modification_lock',['../classgraphchi_1_1graphchi__dynamicgraph__engine.html#a6dd321db58504ad1ed2c0d54387aa160',1,'graphchi::graphchi_dynamicgraph_engine']]],
['mongcpp_2eh',['mongcpp.h',['../mongcpp_8h.html',1,'']]],
['mongoose',['Mongoose',['../class_mongoose.html',1,'']]],
['mongoose',['Mongoose',['../classmongoose_1_1_mongoose.html',1,'mongoose']]],
['mongooseconnection',['MongooseConnection',['../class_mongoose_connection.html',1,'']]],
['mongooseconnection',['MongooseConnection',['../classmongoose_1_1_mongoose_connection.html',1,'mongoose']]],
['mongooseheader',['MongooseHeader',['../struct_mongoose_header.html',1,'']]],
['mongooserequest',['MongooseRequest',['../classmongoose_1_1_mongoose_request.html',1,'mongoose']]],
['mongooserequestinfo',['MongooseRequestInfo',['../struct_mongoose_request_info.html',1,'']]],
['mongooseresponse',['MongooseResponse',['../classmongoose_1_1_mongoose_response.html',1,'mongoose']]],
['mongooseserver',['MongooseServer',['../classmongoose_1_1_mongoose_server.html',1,'mongoose']]],
['mutex',['mutex',['../classgraphchi_1_1mutex.html',1,'graphchi']]],
['mygraphchiprogram',['MyGraphChiProgram',['../struct_my_graph_chi_program.html',1,'']]]
];
| JavaScript |
var searchData=
[
['write_5fshards',['write_shards',['../classgraphchi_1_1sharder.html#acba67408a81dfaa5fdac73c1d61f4631',1,'graphchi::sharder']]]
];
| JavaScript |
function toggleVisibility(linkObj)
{
var base = $(linkObj).attr('id');
var summary = $('#'+base+'-summary');
var content = $('#'+base+'-content');
var trigger = $('#'+base+'-trigger');
var src=$(trigger).attr('src');
if (content.is(':visible')===true) {
content.hide();
summary.show();
$(linkObj).addClass('closed').removeClass('opened');
$(trigger).attr('src',src.substring(0,src.length-8)+'closed.png');
} else {
content.show();
summary.hide();
$(linkObj).removeClass('closed').addClass('opened');
$(trigger).attr('src',src.substring(0,src.length-10)+'open.png');
}
return false;
}
function updateStripes()
{
$('table.directory tr').
removeClass('even').filter(':visible:even').addClass('even');
}
function toggleLevel(level)
{
$('table.directory tr').each(function(){
var l = this.id.split('_').length-1;
var i = $('#img'+this.id.substring(3));
var a = $('#arr'+this.id.substring(3));
if (l<level+1) {
i.attr('src','ftv2folderopen.png');
a.attr('src','ftv2mnode.png');
$(this).show();
} else if (l==level+1) {
i.attr('src','ftv2folderclosed.png');
a.attr('src','ftv2pnode.png');
$(this).show();
} else {
$(this).hide();
}
});
updateStripes();
}
function toggleFolder(id)
{
var n = $('[id^=row_'+id+']');
var i = $('[id^=img_'+id+']');
var a = $('[id^=arr_'+id+']');
var c = n.slice(1);
if (c.filter(':first').is(':visible')===true) {
i.attr('src','ftv2folderclosed.png');
a.attr('src','ftv2pnode.png');
c.hide();
} else {
i.attr('src','ftv2folderopen.png');
a.attr('src','ftv2mnode.png');
c.show();
}
updateStripes();
}
function toggleInherit(id)
{
var rows = $('tr.inherit.'+id);
var img = $('tr.inherit_header.'+id+' img');
var src = $(img).attr('src');
if (rows.filter(':first').is(':visible')===true) {
rows.css('display','none');
$(img).attr('src',src.substring(0,src.length-8)+'closed.png');
} else {
rows.css('display','table-row'); // using show() causes jump in firefox
$(img).attr('src',src.substring(0,src.length-10)+'open.png');
}
}
| JavaScript |
// Adapted from http://jsfiddle.net/7HZcR/3/
var w = 500,
h = 500;
$.get('./file.txt', function(response){
var data = [];
var text_arr = response.split("\n");
for(var i = 0; i < text_arr.length; i++) {
if(text_arr[i].trim().length > 0) {
data.push(text_arr[i]);
}
}
d3.select("#order")
.selectAll("option")
.data(data)
.enter().append("option")
.text(String);
draw_graph(data[0]);
check_iterations('graph1500.1.csv.txt');
function check_iterations(filename) {
$.get(filename, function(response){
var settings = parse_settings(response);
$('#graph_table').empty();
for (var ind=0; ind < settings.length-1; ind = ind+2) {
$("#graph_table").append("<tr><td>" + settings[ind] + "</td><td>" + settings[ind+1] + "</td></tr>");
}
});
} //end of check_iterations
function parse_settings(text) {
var text_arr = text.split(/[\[\]]/);
var settings_arr = [];
for(var i = 0; i < text_arr.length; i++) {
if(text_arr[i].trim().length > 0) {
settings_arr.push(text_arr[i]);
}
}
return settings_arr;
}
});
function draw_graph(filename){
// Read file and operate
d3.csv(filename, function(links) {
// Build nodes object
var nodes = {};
//links = links.slice(1,80);
for (var i = 0; i < links.length; i++){
link = links[i];
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
}
d3.layout.force().stop();
d3.layout.force().nodes([]);
d3.layout.force().links([]);
d3.select("#thesvg").remove();
// Draw it
var force = d3.layout.force()
.nodes(d3.values(nodes))
.links(links)
.size([w, h])
.charge(-500)
.gravity(.5)
.on("tick", tick)
.start();
var svg = d3.select("#large_graph").append("svg:svg")
.attr("width", w)
.attr("height", h)
.attr("id", "thesvg");
var path = svg.append("svg:g").selectAll("path")
.data(force.links())
.enter().append("svg:path")
.attr("class", function(d) { return "link"; });
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle").style("fill", function(d) {
if (d.name <10000) return "red";
else if (d.name > 150000) return "green"; else return "steelblue";
})
.attr("r", function(d) {
return d.weight;
})
.on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
.on("mouseout", function(){d3.select(this).style("fill", "");})
.call(force.drag);
var text = svg.append("svg:g").selectAll("g")
.data(force.nodes())
.enter().append("svg:g");
// A copy of the text with a thick white stroke for legibility.
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.attr("class", "shadow")
.text(function(d) { return d.name; });
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) { return d.name; });
function tick() {
path.attr("d", function(d) {
return "M" + d.source.x + "," + d.source.y + "A0,0 0 0,1 " + d.target.x + "," + d.target.y;
});
circle.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
text.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
}); //end of draw_graph
//input = "graph1000.csv";
function check_iterations(filename) {
$.get(filename, function(response){
var settings = parse_settings(response);
$('#graph_table').empty();
for (var ind=0; ind < settings.length-1; ind = ind+2) {
$("#graph_table").append("<tr><td>" + settings[ind] + "</td><td>" + settings[ind+1] + "</td></tr>");
}
});
} //end of check_iterations
function parse_settings(text) {
var text_arr = text.split(/[\[\]]/);
var settings_arr = [];
for(var i = 0; i < text_arr.length; i++) {
if(text_arr[i].trim().length > 0) {
settings_arr.push(text_arr[i]);
}
}
return settings_arr;
}
d3.select("#order").on("change", function() {
//throw('going to draw' + this.value);
draw_graph(this.value);
check_iterations(this.value + '.txt');
});
};
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
//ATTENTION ! If you change the included JavaScript files make sure to also change the build.xml (arround line 210) accordingly!-->
var gJavascripts = ["gadget/adapter.js",
"gadget/stencilsetPolice.js",
"gadget/syncroWave.js",
"gadget/farbrausch.js",
"gadget/oryx.js"
]; | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
var stencilsetPolice = {
_stencilset: null,
_adapter: null,
initialize: function initialize(stencilset) {
stencilsetPolice._stencilset = stencilset;
stencilsetPolice._adapter = adapter.connect("");
stencilsetPolice._adapter.setStateCallback(stencilsetPolice.stateCallback);
},
stateCallback: function stateCallback() {
var stateStencilset = stencilsetPolice._adapter.getState().get("stencilSet");
if (stencilsetPolice._stencilset && stateStencilset && stateStencilset !== stencilsetPolice._stencilset) {
location.reload(true);
}
}
}; | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
/**
* This prevents errors from logging calls in case console is undefined.
*/
var consoleWrapper = {
// console wrapper by D. Christoff @ http://fragged.org/
_version: 2.3,
debug: false, // global debug on|off
quietDismiss: false, // may want to just drop, or alert instead,
method: "log",
_hasConsole: function(_method) {
var _method = _method || "log";
return typeof(console) == 'object' && typeof(console[_method]) != "undefined";
},
_consoleMethod: function() {
return false;
},
log: function() {
this.method = "log";
this._consoleMethod.apply(this, arguments);
},
info: function() {
this.method = "info";
this._consoleMethod.apply(this, arguments);
},
warn: function() {
this.method = "warn";
this._consoleMethod.apply(this, arguments);
},
clear: function() {
this.method = "clear";
this._consoleMethod.apply(this);
},
count: function() {
this.method = "count";
this._consoleMethod.apply(this, arguments);
},
debug: function() {
this.method = "debug";
this._consoleMethod.apply(this, arguments);
},
trace: function() {
this.method = "trace";
this._consoleMethod.apply(this, arguments);
},
assert: function() {
this.method = "assert";
this._consoleMethod.apply(this, arguments);
}
}; // end console wrapper.
if (typeof console !== 'object') {
console = consoleWrapper;
} | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
var gRootPath = "http://code.processwave.org/raw-file/";
var gStatusMessages = [ "Loading core features of ORYX",
"Loading the ORYX user experience",
"Loading stencil set for ORYX",
"Loading your model into ORYX",
"Loading good karma into your browser",
"Calculating the answer to life",
"Man, this takes like for ever to load...",
"Time for coffee!",
"Hello? Anybody at home?",
"Something probably went terribly wrong during the loading sequence..."
];
var gCurrentStatusMessage = 0;
var gBranchSelected = false;
var gAvailableBranches = [];
var gLoadedJavaScriptsCount = 0;
function initialize() {
getAllBranches();
if (wave && wave.isInWaveContainer()) {
wave.setStateCallback(stateUpdatedCallback);
}
}
function loadJavaScriptsAndThenOryx(branchName, stencilSet, importJSON) {
var path = gRootPath + branchName + "/";
var lab = $LAB;
$LAB.script(path + "gadget/includes.js").wait(
function loadIncludes() {
for (var i = 0; i < gJavascripts.length; i++) {
lab = lab.script(path + gJavascripts[i]).wait(getAfterWaitFunction(path, stencilSet, importJSON));
}
});
}
function getAfterWaitFunction(path, stencilSet, importJSON) {
return function afterWait() {
gLoadedJavaScriptsCount++;
if (gLoadedJavaScriptsCount === gJavascripts.length) {
//All Scripts loaded ==> initialize
adapter.initialize(true);
stencilsetPolice.initialize(stencilSet)
oryx.initialize();
// send the JSON that has to be imported to the ORYX
oryx.sendMessage("oryx", "import", importJSON);
//Load Oryx
var url = path + "/gadget/oryx.xhtml?stencilSetName=" + stencilSet;
$("#oryxFrame").attr("src",url);
}
};
}
function loadOryxBranch(branch, stencilSet) {
$("#branchSelection").hide();
$("#progressBar").show();
window.setTimeout(changeStatusMessage, 1500);
gBranchSelected = true;
$("#branchName").prepend(branch);
if (wave.getState().get("http_referer")) {
var referer = wave.getState().get("wavethis_referer");
//var referer = "http://oryx-project.org/backend/poem/model/9496/json";
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
gadgets.io.makeRequest(referer, processModelJSON, params);
} else {
loadJavaScriptsAndThenOryx(branch, stencilSet);
var dancingShapes = $("#dancingShapes").attr('checked') ? "yes" : "no";
if (wave) {
wave.getState().submitValue("stencilSet", stencilSet);
wave.getState().submitValue("dancingShapes", dancingShapes);
wave.getState().submitValue("branchName", branch);
}
setCookie(branch, stencilSet, dancingShapes);
}
}
function processModelJSON(obj) {
importJSON = obj.data;
stencilSetURL = importJSON.stencilset.url;
var stencilSet;
if (stencilSetURL.indexOf("bpmn2.0") != -1) {
stencilSet = "bpmn2.0";
} else if (stencilSetURL.indexOf("uml2.2") != -1) {
stencilSet = "uml2.2";
} else if (stencilSetURL.indexOf("fmcblockdiagram") != -1) {
stencilSet = "fmcblockdiagram";
}else if (stencilSetURL.indexOf("epc") != -1) {
stencilSet = "epc";
}else if (stencilSetURL.indexOf("petrinets") != -1) {
stencilSet = "petrinets";
}
// TODO: look for the following stencilsets: uml2.2, fmcblockdiagram, epc, petrinets
// regex for string before .json
loadJavaScriptsAndThenOryx("importWaveThis", stencilSet, importJSON);
}
function stateUpdatedCallback() {
if (wave.getState().get("dancingShapes") === "yes") {
$("#dancingShapes").attr('checked', true);
} else {
$("#dancingShapes").attr('checked', false);
}
if(!gBranchSelected) {
var branchName = wave.getState().get("branchName");
if (branchName) {
var stencilSet = wave.getState().get("stencilSet") || "bpmn2.0";
loadOryxBranch(branchName, stencilSet);
} else {
showManualBranchSelection();
}
}
}
function getAllBranches() {
var branchURL = "http://code.processwave.org/branches?rand=" + Math.random();
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
gadgets.io.makeRequest(branchURL, branchesResponse, params);
}
function branchesResponse(obj) {
var domdata = obj.data;
if (!domdata) {
domdata = document.createElement('div');
domdata.innerHTML = obj.text.replace(/<script(.|\s)*?\/script>/g, '');
}
if (!domdata) {
return;
}
var branches = domdata.getElementsByTagName("a");
var item;
var itemclass;
for (var i = 0; i < branches.length; i++) {
item = branches.item(i);
itemclass = item.getAttribute("class");
if (itemclass) {
gAvailableBranches.push($.trim(item.firstChild.data));
}
}
$("#enteredBranchName").autocomplete({
source: gAvailableBranches
});
}
function showManualBranchSelection() {
$("#branchSelection").show();
$("#progressBar").hide();
var textfield = $("#enteredBranchName");
var stencilSet = $("#stencilSet");
textfield.val($.cookies.get("branch")).focus().select();
textfield.keyup(function keyup(evt) {
if (evt.keyCode == 13 /* Return key */) {
onBranchLoadButtonClicked();
}
});
stencilSet.val(getStenciSetFromCookie());
gadgets.window.adjustHeight();
}
function getStenciSetFromCookie() {
var stencilSet = $.cookies.get("stencilSet");
if (stencilSet) {
return stencilSet;
}
return "bpmn2.0";
}
function onBranchLoadButtonClicked() {
loadOryxBranch($("#enteredBranchName").val(), $("#stencilSet").val());
}
function setCookie(branch, stencilSet, dancingShapes) {
var expiredate = new Date();
expiredate.setDate(expiredate.getDate() + 365);
$.cookies.set("branch", branch, {expiresAt: expiredate});
$.cookies.set("stencilSet", stencilSet, {expiresAt: expiredate});
$.cookies.set("dancingShapes", dancingShapes, {expiresAt: expiredate});
}
function changeStatusMessage() {
if (gCurrentStatusMessage >= gStatusMessages.length) {
return;
}
$("#statusMessage").fadeOut(callback = function changeStatusMessageCallback() {
$("#statusMessage").html(gStatusMessages[gCurrentStatusMessage++]).fadeIn();
window.setTimeout(changeStatusMessage, 3900);
});
}
function showOryx() {
$("#oryx").show();
$("#splashScreen").hide();
$("#header").show();
gadgets.window.adjustHeight();
}
function onDebugCheckbox() {
$('#debugger').toggle();
gadgets.window.adjustHeight();
}
gadgets.util.registerOnLoadHandler(initialize);
var splash = {'showOryx': showOryx}; | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
var splash = {
gOryxXhtmlPath: "http://ddj0ahgq8zch6.cloudfront.net/gadget/oryx_stable.xhtml",
gJavaScriptPath: "http://ddj0ahgq8zch6.cloudfront.net/gadget/gadgetDynamic.js",
gStatusMessages: [ "Loading core features",
"Loading the user experience",
"Loading stencil set",
"Loading your model",
"Loading good karma into your browser",
"Calculating the answer to life",
"Man, this takes like for ever to load...",
"Time for coffee!",
"Hello? Anybody at home?",
"That's it! I am out of messages..."
],
gCurrentStatusMessage: 0,
gStencilSetSelected: false,
initialize: function initialize() {
// When the user clicks on a stencilset button load the editor with the corresponding stencilset
$(".selection-button").click(
function onStencilsetClicked() {
var stencilset = $(this).attr('id').substr(10); // strip selection_ from the id to get the stencilset name
splash.loadOryx(stencilset);
}
);
wave.setStateCallback(splash.stateUpdatedCallback);
gadgets.window.adjustHeight();
},
stateUpdatedCallback: function stateUpdatedCallback() {
if (splash.gStencilSetSelected) {
return;
}
var stencilSet = wave.getState().get("stencilSet");
var importURL = wave.getState().get("wavethis_referer");
//var importURL = "http://oryx-project.org/backend/poem/model/9496/json"; //for testing (bpmn2.0-model)
if (stencilSet) {
splash.loadOryx(stencilSet);
} else if (importURL) {
var params = {};
importURL = importURL + "?" + Math.random();
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
gadgets.io.makeRequest(importURL, splash.processModelJSON, params);
} else {
splash.showStencilSetSelection();
}
},
processModelJSON: function processModelJSON(obj) {
importJSON = obj.data;
stencilSetURL = importJSON.stencilset.url;
var stencilSet;
var match = stencilSetURL.match(/\/([^\/]+).json/);
if (match) {
stencilSet = match[1];
if (stencilSet === "petrinet") {
stencilSet = "petrinets";
// For some reason, we use petrinets/petrinets.json, while Oryx uses the singular...
}
splash.loadOryx(stencilSet, importJSON);
} else {
// This should not happen, if it does show the stencilsetselection
splash.showStencilSetSelection();
}
},
showStencilSetSelection: function showStencilSetSelection() {
$("#splash-loading").hide();
$("#stencilset-selection").show();
gadgets.window.adjustHeight();
},
loadOryx: function loadOryx(stencilSet, importJSON) {
wave.getState().submitValue("stencilSet", stencilSet);
$("#stencilset-selection").hide();
$("#splash-loading").show();
splash.gStencilSetSelected = true;
window.setTimeout(splash.changeStatusMessage, 1500);
var oryxUrl = splash.gOryxXhtmlPath + "?stencilSetName=" + stencilSet;
splash.loadJavaScriptsAndThenOryx(oryxUrl, stencilSet, importJSON);
},
changeStatusMessage: function changeStatusMessage() {
if (splash.gCurrentStatusMessage >= splash.gStatusMessages.length) {
return;
}
$("#statusMessage").fadeOut(callback = function changeStatusMessageCallback() {
$("#statusMessage").html(splash.gStatusMessages[splash.gCurrentStatusMessage++]).fadeIn();
window.setTimeout(changeStatusMessage, 3900);
});
},
showOryx: function showOryx() {
$("#oryx").show();
$("#splashScreen").hide();
gadgets.window.adjustHeight();
},
loadJavaScriptsAndThenOryx: function loadJavaScriptsAndThenOryx(oryxUrl, stencilSet, importJSON) {
$LAB.script(splash.gJavaScriptPath).wait(function javaScriptLoadDone() {
adapter.initialize(true);
stencilsetPolice.initialize(stencilSet);
oryx.initialize();
if (typeof importJSON !== "undefined") {
oryx.sendMessage("oryx", "import", importJSON);
}
$("#oryxFrame").attr("src", oryxUrl);
});
}
}
gadgets.util.registerOnLoadHandler(splash.initialize); | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
var farbrausch = {
_adapter: null,
_oldState: {},
_dispatcherNamespace: "farbrausch",
initialize: function initialize() {
farbrausch._adapter = adapter.connect("fr", false);
farbrausch._adapter.setStateCallback(farbrausch.stateUpdatedCallback);
farbrausch._adapter.setParticipantCallback(farbrausch.participantsChangedCallback);
oryx.addMessageDispatcher(farbrausch._dispatcherNamespace, farbrausch.dispatcher);
farbrausch._sendParticipantsOfWave();
},
participantsChangedCallback: function participantsChangedCallback(participants) {
var message = {
"participants": farbrausch._createUserObjects(participants)
};
oryx.sendMessage(farbrausch._dispatcherNamespace, "participants", message);
},
stateUpdatedCallback: function stateUpdatedCallback() {
var state = farbrausch._adapter.getState();
var keys = state.getKeys();
var oldStateHasKey;
var ids = [];
var participants = farbrausch._adapter.getParticipants();
var colorMapping = {};
var message;
for (var i = 0; i < keys.length; i++) {
oldStateHasKey = farbrausch._oldState.hasOwnProperty(keys[i]);
if (!oldStateHasKey || (farbrausch._oldState[keys[i]] !== state.get(keys[i]))) {
colorMapping[keys[i]] = state.get(keys[i]);
farbrausch._oldState[keys[i]] = state.get(keys[i]);
}
}
for (var i = 0; i < participants.length; i++) {
ids.push(participants[i].getId());
}
message = {
"mapping": colorMapping
};
oryx.sendMessage(farbrausch._dispatcherNamespace, "update", message);
},
_sendParticipantsOfWave: function _sendParticipantsOfWave() {
//We can use the participantsChanged-Callback for this:
farbrausch.participantsChangedCallback(farbrausch._adapter.getParticipants());
},
_createUserObject: function _createUserObject(participant) {
var isCreator = (participant.getId() === this._adapter.getHost().getId());
return {
"id": participant.getId(),
"displayName": participant.getDisplayName(),
"thumbnailUrl": participant.getThumbnailUrl(),
"isCreator": isCreator
};
},
_createUserObjects: function _createUserObjects(participants) {
var userObjects = [];
for (var i = 0; i < participants.length; i++) {
userObjects.push(farbrausch._createUserObject(participants[i]));
};
return userObjects;
},
dispatcher: function dispatcher(data) {
if (data.action == "setColor") {
farbrausch._adapter.getState().submitValue(data.message.id, data.message.color);
}
}
} | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
var oryx = {
_dispatcherFunctions: {},
_oryxLoaded: false,
_messageBuffer: [],
_adapter: null,
initialize: function initialize() {
window.addEventListener("message", oryx.dispatchMessage, false);
oryx._adapter = adapter.connect("oryx");
oryx._adapter.setModeCallback(oryx.modeChangedCallback);
oryx._sendUserId();
farbrausch.initialize();
syncroWave.initialize();
},
addMessageDispatcher: function addMessageDispatcher(target, dispatcherFunction) {
oryx._dispatcherFunctions[target] = dispatcherFunction;
},
dispatchMessage: function dispatchMessage(event) {
if (event.origin !== "http://ddj0ahgq8zch6.cloudfront.net" && event.origin !== "http://code.processwave.org" && event.origin !== "http://oryx.processwave.org") {
return;
}
var data = gadgets.json.parse(event.data);
if (data.target === "oryx" && data.action === "loaded") {
// Oryx has loaded, send initial commands to Oryx
oryx._oryxLoaded = true;
for (var i = 0; i < oryx._messageBuffer.length; i++) {
oryx._postMessage(oryx._messageBuffer[i]);
}
} else if (data.target === "oryx" && data.action === "showOryx") {
splash.showOryx(); //can be found in splash.js
oryx.sendMessage("oryx", "shown");
} else {
if (oryx._dispatcherFunctions.hasOwnProperty(data.target)) {
oryx._dispatcherFunctions[data.target](data)
} else {
throw "Undispatched Message";
}
}
},
sendMessage: function sendMessage(target, action, message) {
var packedMessage = {
"target": target,
"action": action,
"message": message
};
if (!oryx._oryxLoaded) {
oryx._messageBuffer.push(packedMessage);
} else {
oryx._postMessage(packedMessage);
}
},
_postMessage: function _postMessage(message) {
var oryxFrame = document.getElementById("oryxFrame").contentWindow;
oryxFrame.postMessage(JSON.stringify(message), "*");
},
_sendUserId: function sendUserId() {
oryx.sendMessage("oryx", "setUserId", oryx._adapter.getViewer().getId());
},
modeChangedCallback: function modeChangedCallback(mode) {
if (mode === oryx._adapter.Mode.VIEW) {
oryx.sendMessage("oryx", "setMode", "view");
} else if (mode === oryx._adapter.Mode.EDIT) {
oryx.sendMessage("oryx", "setMode", "edit");
} else if (mode === oryx._adapter.Mode.PLAYBACK) {
//TODO: Think about this mode
oryx.sendMessage("oryx", "setMode", "view");
}
}
} | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
var adapter = {
allowSwapping: false, //Deaktivate Swapping here for debugging
_modeCallbacks: [],
_participantsCallbacks: [],
_mode: null,
_gotParticipantsCallback: false,
_gotStateCallback: false,
_stateCallbacks: [],
_delimiter: "\\",
_gadgetState: {},
_databaseRootUrl: "http://key-value-store.appspot.com/",
_gadgetId: null,
_GADGET_ID_KEY: "GADGETID",
_swapEnabled: false,
_swapablePrefixes: [],
_fetchedFromDb: false,
initialize: function initialize(swapEnabled) {
if (typeof swapEnabled === "boolean" && this.allowSwapping) {
adapter._swapEnabled = swapEnabled;
}
if (wave && wave.isInWaveContainer()) {
wave.setModeCallback(adapter._modeUpdatedCallback);
wave.setParticipantCallback(adapter._participantUpdatedCallback);
wave.setStateCallback(adapter._stateUpdatedCallback);
}
},
connect: function connect(prefix, swapable) {
if (typeof prefix !== "string") {
throw "type of prefix must be string";
}
if (prefix != "") {
prefix = prefix + adapter._delimiter;
}
if (swapable === true) {
adapter._swapablePrefixes.push(prefix);
}
return {
getHost: function getHost() {
return wave.getHost();
},
getMode: function getMode() {
return wave.getMode();
},
getParticipantById: function getParticipantById(id) {
return wave.getParticipantById(id);
},
getParticipants: function getParticipants() {
return wave.getParticipants();
},
getState: function getState() {
return {
get: function get(key) {
return adapter._get(prefix, key);
},
getKeys: function getKeys() {
return adapter._getKeys(prefix);
},
submitDelta: function submitDelta(delta) {
return adapter._submitDelta(prefix, delta);
},
submitValue: function submitValue(key, value) {
return adapter._submitValue(prefix, key, value);
}
};
},
getTime: function getTime() {
return wave.getTime();
},
getViewer: function getViewer() {
return wave.getViewer();
},
getWaveId: function getWaveId() {
return wave.getWaveId();
},
isInWaveContainer: function isInWaveContainer() {
return wave.isInWaveContainer();
},
log: function log(message) {
return wave.log(message);
},
setModeCallback: function setModeCallback(callback) {
adapter._modeCallbacks.push(callback);
if (adapter._mode) {
callback(adapter._mode);
}
},
setParticipantCallback: function setParticipantCallback(callback) {
adapter._participantsCallbacks.push(callback);
if (adapter._gotParticipantsCallback) {
callback(wave.getParticipants());
}
},
setStateCallback: function setStateCallback(callback) {
adapter._stateCallbacks.push(callback);
if (adapter._gotStateCallback) {
callback();
}
},
util: wave.util,
Mode: wave.Mode
};
},
_get: function _get(prefix, key) {
var finalKey = prefix + key;
return adapter._gadgetState[finalKey];
},
_getKeys: function _getKeys(prefix) {
var keys = [];
for (var key in adapter._gadgetState) {
if (adapter._gadgetState.hasOwnProperty(key) && key.indexOf(prefix) === 0) {
keys.push(key);
}
}
return adapter._removePrefixFromKeys(prefix, keys);
},
_removePrefixFromKeys: function _removePrefixFromKeys(prefix, keys) {
var returnKeys = [];
for (var i = 0; i < keys.length; i++) {
if (keys[i].substr(0,prefix.length) === prefix) {
returnKeys.push(keys[i].substring(prefix.length));
}
}
return returnKeys;
},
_submitDelta: function _submitDelta(prefix, delta) {
var newDelta = {};
for (var key in delta) {
if (delta.hasOwnProperty(key)) {
newDelta[prefix + key] = delta[key];
}
}
if (!adapter._swapEnabled) {
wave.getState().submitDelta(newDelta);
} else {
adapter._pushToDb(newDelta);
if (!adapter._isSwapable(prefix)) {
wave.getState().submitDelta(newDelta);
}
}
},
_submitValue: function _submitValue(prefix, key, value) {
var delta = {};
delta[key] = value;
adapter._submitDelta(prefix, delta);
},
_modeUpdatedCallback: function _modeUpdatedCallback(mode) {
adapter._mode = mode;
for (var i = 0; i < adapter._modeCallbacks.length; i++) {
adapter._modeCallbacks[i](mode);
}
},
_participantUpdatedCallback: function _participantUpdatedCallback(participants) {
adapter._gotParticipantsCallback = true;
for (var i = 0; i < adapter._participantsCallbacks.length; i++) {
adapter._participantsCallbacks[i](participants);
}
},
_stateUpdatedCallback: function _stateUpdatedCallback() {
adapter._gotStateCallback = true;
var keys = wave.getState().getKeys();
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
adapter._gadgetState[key] = wave.getState().get(key);
}
if (!adapter._fetchedFromDb && adapter._gadgetState[adapter._GADGET_ID_KEY]) {
adapter._setGadgetId();
adapter._fetchFromDb();
adapter._fetchedFromDb = true;
} else if (adapter._swapEnabled) {
adapter._setGadgetId();
adapter._fetchFromDb();
} else {
adapter._invokeStateCallbacks();
}
},
_invokeStateCallbacks: function _invokeStateCallbacks() {
adapter._gotStateCallback = true;
for (var i = 0; i < adapter._stateCallbacks.length; i++) {
adapter._stateCallbacks[i]();
}
},
//DB-Functions
_fetchFromDb: function _fetchFromDb() {
var params = {};
var url = adapter._getRequestUrl() + "?" + Math.random() //prevent Caching
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
gadgets.io.makeRequest(url, adapter._processDbData, params)
},
_processDbData: function _processDbData(obj) {
var jsonData = obj.data;
for (var key in jsonData) {
if (jsonData.hasOwnProperty(key)) {
adapter._gadgetState[key] = jsonData[key];
}
}
adapter._invokeStateCallbacks();
},
_pushToDb: function _pushToDb(delta) {
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
params[gadgets.io.RequestParameters.POST_DATA] = JSON.stringify(delta);
gadgets.io.makeRequest(adapter._getRequestUrl(), adapter._pushToDbCallback, params);
},
_pushToDbCallback: function _pushToDbCallback() {
var viewerId = wave.getViewer().getId();
var incrementalValue = parseInt(adapter._gadgetState[viewerId] || 0) + 1; //Nice!
adapter._gadgetState[viewerId] = incrementalValue;
wave.getState().submitValue(viewerId, incrementalValue);
},
_isSwapable: function _isSwapable(prefix) {
return adapter._swapablePrefixes.indexOf(prefix) !== -1;
},
_setGadgetId: function _setGadgetId() {
var stateId = wave.getState().get(adapter._GADGET_ID_KEY);
if (stateId == null) {
adapter._gadgetId = wave.getWaveId() + "_" + Math.floor(Math.random() * 1000000);
wave.getState().submitValue(adapter._GADGET_ID_KEY, adapter._gadgetId);
} else if (adapter._gadgetId == null){
adapter._gadgetId = stateId;
} else if (adapter._gadgetId != stateId){
adapter._gadgetId = stateId;
adapter._renameGadgetInDb(stateId);
}
},
_getRequestUrl: function _getRequestUrl() {
return adapter._databaseRootUrl + adapter._gadgetId + "/";
},
_renameGadgetInDb: function _renameGadgetInDb(newId) {
var url = adapter._getRequestUrl() + newId;
var params = {}
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
gadgets.io.makeRequest(url, null, params);
}
} | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
var syncroWave = {
/**
* This implements the interface between the syncro algorithm (syncro.js)
* and the Wave state
**/
_adapter: undefined,
initialize: function initialize() {
syncroWave._adapter = adapter.connect("pw", true);
syncroWave._adapter.setStateCallback(syncroWave.stateUpdatedCallback);
oryx.addMessageDispatcher("syncroWave", this.dispatcher);
},
stateUpdatedCallback: function stateUpdatedCallback() {
//send all commands in the state to syncro
oryx.sendMessage("syncro", "commands", syncroWave._getStateAsArray());
},
_getStateAsArray: function _getStateAsHash() {
// turn state with command objects into an array
var stateArray = [];
var waveState = syncroWave._adapter.getState();
var waveStateKeys = waveState.getKeys();
for (var i = 0; i < waveStateKeys.length; i++) {
var key = waveStateKeys[i];
var jsonValue = JSON.parse(waveState.get(key))
stateArray.push(jsonValue);
}
return stateArray;
},
dispatcher: function dispatcher(data) {
// save new command from local client in wave state
if (data.action == "save") {
syncroWave._adapter.getState().submitValue(data.message.id, JSON.stringify(data.message));
}
}
} | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
var ERDF = {
LITERAL: 0x01,
RESOURCE: 0x02,
DELIMITERS: ['.', '-'],
HASH: '#',
HYPHEN: "-",
schemas: [],
callback: undefined,
log: undefined,
init: function(callback) {
// init logging.
//ERDF.log = Log4js.getLogger("oryx");
//ERDF.log.setLevel(Log4js.Level.ALL);
//ERDF.log.addAppender(new ConsoleAppender(ERDF.log, false));
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("ERDF Parser is initialized.");
// register callbacks and default schemas.
ERDF.callback = callback;
ERDF.registerSchema('schema', XMLNS.SCHEMA);
ERDF.registerSchema('rdfs', XMLNS.RDFS);
},
run: function() {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("ERDF Parser is running.");
// do the work.
return ERDF._checkProfile() && ERDF.parse();
},
parse: function() {
//(ERDF.log.isDebugEnabled())
// ERDF.log.debug("Begin parsing document metadata.");
// time measuring
ERDF.__startTime = new Date();
var bodies = document.getElementsByTagNameNS(XMLNS.XHTML, 'body');
var subject = {type: ERDF.RESOURCE, value: ''};
var result = ERDF._parseDocumentMetadata() &&
ERDF._parseFromTag(bodies[0], subject);
// time measuring
ERDF.__stopTime = new Date();
var duration = (ERDF.__stopTime - ERDF.__startTime)/1000.;
//alert('ERDF parsing took ' + duration + ' s.');
return result;
},
_parseDocumentMetadata: function() {
// get links from head element.
var heads = document.getElementsByTagNameNS(XMLNS.XHTML, 'head');
var links = heads[0].getElementsByTagNameNS(XMLNS.XHTML, 'link');
var metas = heads[0].getElementsByTagNameNS(XMLNS.XHTML, 'meta');
// process links first, since they could contain schema definitions.
$A(links).each(function(link) {
var properties = link.getAttribute('rel');
var reversedProperties = link.getAttribute('rev');
var value = link.getAttribute('href');
ERDF._parseTriplesFrom(
ERDF.RESOURCE, '',
properties,
ERDF.RESOURCE, value);
ERDF._parseTriplesFrom(
ERDF.RESOURCE, value,
reversedProperties,
ERDF.RESOURCE, '');
});
// continue with metas.
$A(metas).each(function(meta) {
var property = meta.getAttribute('name');
var value = meta.getAttribute('content');
ERDF._parseTriplesFrom(
ERDF.RESOURCE, '',
property,
ERDF.LITERAL, value);
});
return true;
},
_parseFromTag: function(node, subject, depth) {
// avoid parsing non-xhtml content.
if(node.namespaceURI != XMLNS.XHTML) { return; }
// housekeeping.
if(!depth) depth=0;
var id = node.getAttribute('id');
// some logging.
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace(">".times(depth) + " Parsing " + node.nodeName + " ("+node.nodeType+") for data on " +
// ((subject.type == ERDF.RESOURCE) ? ('<' + subject.value + '>') : '') +
// ((subject.type == ERDF.LITERAL) ? '"' + subject.value + '"' : ''));
/* triple finding! */
// in a-tags...
if(node.nodeName.endsWith(':a') || node.nodeName == 'a') {
var properties = node.getAttribute('rel');
var reversedProperties = node.getAttribute('rev');
var value = node.getAttribute('href');
var title = node.getAttribute('title');
var content = node.textContent;
// rel triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.RESOURCE, value,
function(triple) {
var label = title? title : content;
// label triples
ERDF._parseTriplesFrom(
triple.object.type, triple.object.value,
'rdfs.label',
ERDF.LITERAL, label);
});
// rev triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
reversedProperties,
ERDF.RESOURCE, '');
// type triples
ERDF._parseTypeTriplesFrom(
subject.type, subject.value,
properties);
// in img-tags...
} else if(node.nodeName.endsWith(':img') || node.nodeName == 'img') {
var properties = node.getAttribute('class');
var value = node.getAttribute('src');
var alt = node.getAttribute('alt');
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.RESOURCE, value,
function(triple) {
var label = alt;
// label triples
ERDF._parseTriplesFrom(
triple.object.type, triple.object.value,
'rdfs.label',
ERDF.LITERAL, label);
});
}
// in every tag
var properties = node.getAttribute('class');
var title = node.getAttribute('title');
var content = node.textContent;
var label = title ? title : content;
// regular triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.LITERAL, label);
if(id) subject = {type: ERDF.RESOURCE, value: ERDF.HASH+id};
// type triples
ERDF._parseTypeTriplesFrom(
subject.type, subject.value,
properties);
// parse all children that are element nodes.
var children = node.childNodes;
if(children) $A(children).each(function(_node) {
if(_node.nodeType == _node.ELEMENT_NODE)
ERDF._parseFromTag(_node, subject, depth+1); });
},
_parseTriplesFrom: function(subjectType, subject, properties,
objectType, object, callback) {
if(!properties) return;
properties.toLowerCase().split(' ').each( function(property) {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Going for property " + property);
var schema = ERDF.schemas.find( function(schema) {
return false || ERDF.DELIMITERS.find( function(delimiter) {
return property.startsWith(schema.prefix + delimiter);
});
});
if(schema && object) {
property = property.substring(
schema.prefix.length+1, property.length);
var triple = ERDF.registerTriple(
new ERDF.Resource(subject),
{prefix: schema.prefix, name: property},
(objectType == ERDF.RESOURCE) ?
new ERDF.Resource(object) :
new ERDF.Literal(object));
if(callback) callback(triple);
}
});
},
_parseTypeTriplesFrom: function(subjectType, subject, properties, callback) {
if(!properties) return;
properties.toLowerCase().split(' ').each( function(property) {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Going for property " + property);
var schema = ERDF.schemas.find( function(schema) {
return false || ERDF.DELIMITERS.find( function(delimiter) {
return property.startsWith(ERDF.HYPHEN + schema.prefix + delimiter);
});
});
if(schema && subject) {
property = property.substring(schema.prefix.length+2, property.length);
var triple = ERDF.registerTriple(
(subjectType == ERDF.RESOURCE) ?
new ERDF.Resource(subject) :
new ERDF.Literal(subject),
{prefix: 'rdf', name: 'type'},
new ERDF.Resource(schema.namespace+property));
if(callback) callback(triple);
}
});
},
/**
* Checks for ERDF profile declaration in head of document.
*/
_checkProfile: function() {
// get profiles from head element.
var heads = document.getElementsByTagNameNS(XMLNS.XHTML, 'head');
var profiles = heads[0].getAttribute("profile");
var found = false;
// if erdf profile is contained.
if(profiles && profiles.split(" ").member(XMLNS.ERDF)) {
// pass check.
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Found ERDF profile " + XMLNS.ERDF);
return true;
} else {
// otherwise fail check.
//if(ERDF.log.isFatalEnabled())
// ERDF.log.fatal("No ERDF profile found.");
return false;
}
},
__stripHashes: function(s) {
return (s && s.substring(0, 1)=='#') ? s.substring(1, s.length) : s;
},
registerSchema: function(prefix, namespace) {
// TODO check whether already registered, if so, complain.
ERDF.schemas.push({
prefix: prefix,
namespace: namespace
});
//if(ERDF.log.isDebugEnabled())
// ERDF.log.debug("Prefix '"+prefix+"' for '"+namespace+"' registered.");
},
registerTriple: function(subject, predicate, object) {
// if prefix is schema, this is a schema definition.
if(predicate.prefix.toLowerCase() == 'schema')
this.registerSchema(predicate.name, object.value);
var triple = new ERDF.Triple(subject, predicate, object);
ERDF.callback(triple);
//if(ERDF.log.isInfoEnabled())
// ERDF.log.info(triple)
// return the registered triple.
return triple;
},
__enhanceObject: function() {
/* Resource state querying methods */
this.isResource = function() {
return this.type == ERDF.RESOURCE };
this.isLocal = function() {
return this.isResource() && this.value.startsWith('#') };
this.isCurrentDocument = function() {
return this.isResource() && (this.value == '') };
/* Resource getter methods.*/
this.getId = function() {
return this.isLocal() ? ERDF.__stripHashes(this.value) : false; };
/* Liiteral state querying methods */
this.isLiteral = function() {
return this.type == ERDF.LIITERAL };
},
serialize: function(literal) {
if(!literal){
return "";
}else if(literal.constructor == String) {
return literal;
} else if(literal.constructor == Boolean) {
return literal? 'true':'false';
} else {
return literal.toString();
}
}
};
ERDF.Triple = function(subject, predicate, object) {
this.subject = subject;
this.predicate = predicate;
this.object = object;
this.toString = function() {
return "[ERDF.Triple] " +
this.subject.toString() + ' ' +
this.predicate.prefix + ':' + this.predicate.name + ' ' +
this.object.toString();
};
};
ERDF.Resource = function(uri) {
this.type = ERDF.RESOURCE;
this.value = uri;
ERDF.__enhanceObject.apply(this);
this.toString = function() {
return '<' + this.value + '>';
}
};
ERDF.Literal = function(literal) {
this.type = ERDF.LITERAL;
this.value = ERDF.serialize(literal);
ERDF.__enhanceObject.apply(this);
this.toString = function() {
return '"' + this.value + '"';
}
}; | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
/**
* The super class for all classes in ORYX. Adds some OOP feeling to javascript.
* See article "Object Oriented Super Class Method Calling with JavaScript" on
* http://truecode.blogspot.com/2006/08/object-oriented-super-class-method.html
* for a documentation on this. Fairly good article that points out errors in
* Douglas Crockford's inheritance and super method calling approach.
* Worth reading.
* @class Clazz
*/
var Clazz = function() {};
/**
* Empty constructor.
* @methodOf Clazz.prototype
*/
Clazz.prototype.construct = function() {};
/**
* Can be used to build up inheritances of classes.
* @example
* var MyClass = Clazz.extend({
* construct: function(myParam){
* // Do sth.
* }
* });
* var MySubClass = MyClass.extend({
* construct: function(myParam){
* // Use this to call constructor of super class
* arguments.callee.$.construct.apply(this, arguments);
* // Do sth.
* }
* });
* @param {Object} def The definition of the new class.
*/
Clazz.extend = function(def) {
var classDef = function() {
if (arguments[0] !== Clazz) { this.construct.apply(this, arguments); }
};
var proto = new this(Clazz);
var superClass = this.prototype;
for (var n in def) {
var item = def[n];
if (item instanceof Function) item.$ = superClass;
proto[n] = item;
}
classDef.prototype = proto;
//Give this new class the same static extend method
classDef.extend = this.extend;
return classDef;
}; | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
XMLNS = {
ATOM: "http://www.w3.org/2005/Atom",
XHTML: "http://www.w3.org/1999/xhtml",
ERDF: "http://purl.org/NET/erdf/profile",
RDFS: "http://www.w3.org/2000/01/rdf-schema#",
RDF: "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
RAZIEL: "http://b3mn.org/Raziel",
SCHEMA: ""
};
//TODO kann kickstart sich vielleicht auch um die erzeugung von paketen/
// namespaces k�mmern? z.b. requireNamespace("ORYX.Core.SVG");
var Kickstart = {
started: false,
callbacks: [],
alreadyLoaded: [],
PATH: '',
load: function() { Kickstart.kick(); },
kick: function() {
console.log("loading");
if(!Kickstart.started) {
Kickstart.started = true;
Kickstart.callbacks.each(function(callback){
// call the registered callback asynchronously.
window.setTimeout(callback, 1);
});
}
},
register: function(callback) {
//TODO Add some mutual exclusion between kick and register calls.
with(Kickstart) {
if(started) window.setTimeout(callback, 1);
else Kickstart.callbacks.push(callback)
}
},
/**
* Loads a js, assuring that it has only been downloaded once.
* @param {String} url the script to load.
*/
require: function(url) {
// if not already loaded, include it.
if(Kickstart.alreadyLoaded.member(url))
return false;
return Kickstart.include(url);
},
/**
* Loads a js, regardless of whether it has only been already downloaded.
* @param {String} url the script to load.
*/
include: function(url) {
// prepare a script tag and place it in html head.
var head = document.getElementsByTagNameNS(XMLNS.XHTML, 'head')[0];
var s = document.createElementNS(XMLNS.XHTML, "script");
s.setAttributeNS(XMLNS.XHTML, 'type', 'text/javascript');
s.src = Kickstart.PATH + url;
//TODO macht es sinn, dass neue skript als letztes kind in den head
// einzubinden (stichwort reihenfolge der skript tags)?
head.appendChild(s);
// remember this url.
Kickstart.alreadyLoaded.push(url);
return true;
}
};
/*function pwInit(bla) {
if (bla == null) {
console.log("ignore empty part.");
return;
}
console.log("participant callback recv");
wave.setParticipantCallback(null);
Kickstart.load();
}*/
// register kickstart as the new onload event listener on current window.
// previous listener(s) are triggered to launch with kickstart.
function _pw_load() {
try {
console.log("i'm kickstarting");
Kickstart.load();
} catch (e) {
console.log("fail");
console.log(e);
}
}
console.log("I would kickstart soon");
//if (wave) {
// console.log("Wave Kickstart");
// wave.setParticipantCallback(pwInit);
//} else {
// console.log("Normal Kickstart");
Event.observe(window, 'load', Kickstart.load);
//} | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
/**
* @namespace Oryx name space for different utility methods
* @name ORYX.Utils
*/
ORYX.Utils = {
/**
* General helper method for parsing a param out of current location url
* @example
* // Current url in Browser => "http://oryx.org?param=value"
* ORYX.Utils.getParamFromUrl("param") // => "value"
* @param {Object} name
*/
getParamFromUrl: function(name){
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) {
return null;
}
else {
return results[1];
}
},
adjustGradient: function(gradient, reference){
if (ORYX.CONFIG.DISABLE_GRADIENT && gradient){
var col = reference.getAttributeNS(null, "stop-color") || "#ffffff";
$A(gradient.getElementsByTagName("stop")).each(function(stop){
if (stop == reference){ return; }
stop.setAttributeNS(null, "stop-color", col);
})
}
}
}
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if(!ORYX.Plugins) {
ORYX.Plugins = new Object();
}
ORYX.Plugins.Schlaumeier = {
schlaumeierWidth: 229,
schlaumeierHeight: 16,
padding: 2,
border: 1,
showtimes: {},
timer: null,
animationInProgress: true,
construct: function construct(facade) {
this.facade = facade;
this.canvasContainer = $$(".ORYX_Editor")[0].parentNode;
this.schlaumeier = document.createElement('div');
Element.extend(this.schlaumeier);
this.schlaumeier.setAttribute('id', 'pwave-schlaumeier');
this.schlaumeier.onclick = this.hideTooltip.bind(this);
this.canvasContainer.appendChild(this.schlaumeier);
window.addEventListener("resize", this.handleWindowResize.bind(this), false);
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_DISPLAY_SCHLAUMEIER, this.displayMessage.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_HIDE_SCHLAUMEIER, this.hideTooltip.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_ORYX_SHOWN, this.onOryxShown.bind(this));
},
onOryxShown: function onLoad() {
this.handleWindowResize();
this.animationInProgress = false;
},
handleWindowResize: function handleWindowResize() {
this.schlaumeier.style.right = 0 + this.getCanvasScrollbarOffsetForWidth() + 'px';
this.schlaumeier.style.top = '0px';
},
displayMessage: function displayMessage(event) {
if (this.animationInProgress) {
setTimeout(this.displayMessage.bind(this, event), 300);
return;
}
if (typeof event.showtimes === "undefined") {
event.showtimes = 1;
}
if (typeof event.duration === "undefined") {
event.duration = 8000;
}
if (!this.needsToBeDisplayed(event)) {
return;
}
this.setText(event.message);
this.animationInProgress = true;
setTimeout(this.showTooltip.bind(this), 300);
if (event.duration !== "infinite") {
this.timer = setTimeout(this.hideTooltip.bind(this), event.duration + 300);
}
},
hideTooltip: function hideTooltip() {
if (this.schlaumeier.style.display !== "none") {
this.animationInProgress = true;
jQuery(this.schlaumeier).hide("slide", {'direction' : "up"}, 700, this.animationFinished.bind(this));
}
},
showTooltip: function showTooltip() {
jQuery(this.schlaumeier).show("slide", {'direction' : "up"}, 700, this.animationFinished.bind(this));
},
animationFinished: function animationFinished() {
this.animationInProgress = false;
},
needsToBeDisplayed: function needsToBeDisplayed(event) {
if (typeof this.showtimes[event.message] === "undefined") {
this.showtimes[event.message] = event.showtimes;
}
if (this.showtimes[event.message] === "always") {
return true;
}
this.showtimes[event.message] -= 1;
if (this.showtimes[event.message] < 0) {
return false;
}
return true;
},
setText: function setText(newText) {
this.schlaumeier.hide();
clearTimeout(this.timer);
this.schlaumeier.update(newText);
this.handleWindowResize();
},
getCanvasScrollbarOffsetForWidth: function getCanvasScrollbarOffsetForWidth() {
return this.canvasContainer.offsetWidth - this.canvasContainer.clientWidth;
},
getCanvasScrollbarOffsetForHeight: function getCanvasScrollbarOffsetForHeight() {
return this.canvasContainer.offsetHeight - this.canvasContainer.clientHeight;
}
};
ORYX.Plugins.Schlaumeier = ORYX.Plugins.AbstractPlugin.extend(ORYX.Plugins.Schlaumeier); | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if (!ORYX.Plugins)
ORYX.Plugins = new Object();
// Implements the command class for a Shape Rename upon a double click on that shape
ORYX.Core.Commands["RenameShape"] = ORYX.Core.AbstractCommand.extend({
construct: function construct(shape, propId, oldValue, newValue, facade) {
arguments.callee.$.construct.call(this, facade);
this.el = shape;
this.propId = propId;
this.oldValue = oldValue;
this.newValue = newValue;
},
getCommandData: function getCommandData() {
var commandData = {
shapeId: this.el.resourceId,
propId: this.propId,
oldValue: this.oldValue,
newValue: this.newValue
};
return commandData;
},
createFromCommandData: function createFromCommandData(facade, commandData) {
var shape = facade.getCanvas().getChildShapeByResourceId(commandData.shapeId);
if (typeof shape === 'undefined') {
return undefined;
}
return new ORYX.Core.Commands["RenameShape"](shape, commandData.propId, commandData.oldValue, commandData.newValue, facade);
},
getAffectedShapes: function getAffectedShapes() {
return [this.el];
},
getCommandName: function getCommandName() {
return "RenameShape";
},
getDisplayName: function getDisplayName() {
return "Shape renamed";
},
execute: function execute() {
this.el.setProperty(this.propId, this.newValue);
//this.el.update();
if (this.isLocal()) {
this.facade.setSelection([this.el]);
}
this.facade.getCanvas().update();
this.facade.updateSelection(this.isLocal());
},
rollback: function rollback() {
this.el.setProperty(this.propId, this.oldValue);
//this.el.update();
if (this.isLocal()) {
this.facade.setSelection([this.el]);
}
this.facade.getCanvas().update();
this.facade.updateSelection(this.isLocal());
}
});
ORYX.Plugins.RenameShapes = Clazz.extend({
facade: undefined,
construct: function(facade){
this.facade = facade;
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_DBLCLICK, this.actOnDBLClick.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LABEL_DBLCLICK, this.actOnLabelDblClick.bind(this));
/* leads to errors on multilableshapes
this.facade.offer({
keyCodes: [{
keyCode: 113, // F2-Key
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.renamePerF2.bind(this)
});*/
document.documentElement.addEventListener(ORYX.CONFIG.EVENT_MOUSEDOWN, this.hide.bind(this), true )
},
actOnLabelDblClick: function actOnLabelDblClick(event, shape) {
var label = event.label;
if (!label.editable) {
return;
}
// find property the label corresponds to
if (typeof shape == 'undefined') {
return;
}
// id of label is not autogenerated by oryx, probably not a property label
if (label.id.indexOf(shape.id) === -1) {
return;
}
var normalizedLabelId = label.id.substr(41).toLowerCase();
if (typeof shape.properties["oryx-" + normalizedLabelId] === undefined) {
return;
}
var properties = this.getEditableProperties(shape);
var property = this.getPropertyForLabel(properties, shape, label);
if (typeof property === "undefined") {
return;
}
this.showTextField(shape, property, label);
},
/**
* This method handles the "F2" key down event. The selected shape are looked
* up and the editing of title/name of it gets started.
*/
renamePerF2 : function renamePerF2() {
var selectedShapes = this.facade.getSelection();
this.actOnDBLClick(undefined, selectedShapes.first());
},
getEditableProperties: function getEditableProperties(shape) {
// Get all properties which where at least one ref to view is set
var props = shape.getStencil().properties().findAll(function(item){
return (item.refToView()
&& item.refToView().length > 0
&& item.directlyEditable());
});
// from these, get all properties where write access are and the type is String
return props.findAll(function(item){ return !item.readonly() && item.type() == ORYX.CONFIG.TYPE_STRING });
},
getPropertyForLabel: function getPropertyForLabel(properties, shape, label) {
return properties.find(function(item){ return item.refToView().any(function(toView){ return label.id == shape.id + toView })});
},
actOnDBLClick: function actOnDBLClick(evt, shape){
if( !(shape instanceof ORYX.Core.Shape) ){ return }
// Destroys the old input, if there is one
this.destroy();
var props = this.getEditableProperties(shape);
// Get all ref ids
var allRefToViews = props.collect(function(prop){ return prop.refToView() }).flatten().compact();
// Get all labels from the shape with the ref ids
var labels = shape.getLabels().findAll(function(label){ return allRefToViews.any(function(toView){ return label.id.endsWith(toView) }); })
// If there are no referenced labels --> return
if( labels.length == 0 ){ return }
// Define the nearest label
var nearestLabel = labels.length == 1 ? labels[0] : null;
if( !nearestLabel ){
nearestLabel = labels.find(function(label){ return label.node == evt.target || label.node == evt.target.parentNode })
if( !nearestLabel ){
var evtCoord = this.facade.eventCoordinates(evt);
var trans = this.facade.getCanvas().rootNode.lastChild.getScreenCTM();
evtCoord.x *= trans.a;
evtCoord.y *= trans.d;
if (!shape instanceof ORYX.Core.Node) {
var diff = labels.collect(function(label){
var center = this.getCenterPosition( label.node );
var len = Math.sqrt( Math.pow(center.x - evtCoord.x, 2) + Math.pow(center.y - evtCoord.y, 2));
return {diff: len, label: label}
}.bind(this));
diff.sort(function(a, b){ return a.diff > b.diff })
nearestLabel = diff[0].label;
} else {
var diff = labels.collect(function(label){
var center = this.getDifferenceCenterForNode( label.node );
var len = Math.sqrt( Math.pow(center.x - evtCoord.x, 2) + Math.pow(center.y - evtCoord.y, 2));
return {diff: len, label: label}
}.bind(this));
diff.sort(function(a, b){ return a.diff > b.diff })
nearestLabel = diff[0].label;
}
}
}
// Get the particular property for the label
var prop = this.getPropertyForLabel(props, shape, nearestLabel);
this.showTextField(shape, prop, nearestLabel);
},
showTextField: function showTextField(shape, prop, label) {
// Set all particular config values
var htmlCont = this.facade.getCanvas().getHTMLContainer().id;
// Get the center position from the nearest label
var width;
if(!(shape instanceof ORYX.Core.Node)) {
var bounds = label.node.getBoundingClientRect();
width = Math.max(150, bounds.width);
} else {
width = shape.bounds.width();
}
if (!shape instanceof ORYX.Core.Node) {
var center = this.getCenterPosition( label.node );
center.x -= (width/2);
} else {
var center = shape.absoluteBounds().center();
center.x -= (width/2);
}
var propId = prop.prefix() + "-" + prop.id();
// Set the config values for the TextField/Area
var config = {
renderTo : htmlCont,
value : shape.properties[propId],
x : (center.x < 10) ? 10 : center.x,
y : center.y,
width : Math.max(100, width),
style : 'position:absolute',
allowBlank : prop.optional(),
maxLength : prop.length(),
emptyText : prop.title(),
cls : 'x_form_text_set_absolute',
listeners : {specialkey: this._specialKeyPressed.bind(this)}
};
// Depending on the property, generate
// ether an TextArea or TextField
if(prop.wrapLines()) {
config.y -= 30;
config['grow'] = true;
this.shownTextField = new Ext.form.TextArea(config);
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_DISPLAY_SCHLAUMEIER,
'message': "Press Shift+Enter to finish text entry."
});
} else {
config.y -= 16;
this.shownTextField = new Ext.form.TextField(config);
}
//focus
this.shownTextField.focus();
// Define event handler
// Blur -> Destroy
// Change -> Set new values
this.shownTextField.on( 'blur', this.destroy.bind(this) )
this.shownTextField.on( 'change', function(node, value){
var currentEl = shape;
var oldValue = currentEl.properties[propId];
var newValue = value;
var facade = this.facade;
if (oldValue != newValue) {
var command = new ORYX.Core.Commands["RenameShape"](currentEl, propId, oldValue, newValue, facade);
this.facade.executeCommands([command]);
}
}.bind(this) )
// Diable the keydown in the editor (that when hitting the delete button, the shapes not get deleted)
this.facade.disableEvent(ORYX.CONFIG.EVENT_KEYDOWN);
},
_specialKeyPressed: function _specialKeyPressed(field, e) {
// Enter or Ctrl+Enter pressed
var keyCode = e.getKey();
if (keyCode == 13 && (e.shiftKey || !field.initialConfig.grow)) {
field.fireEvent("change", null, field.getValue());
field.fireEvent("blur");
} else if (keyCode == e.ESC) {
field.fireEvent("blur");
}
},
getCenterPosition: function(svgNode){
var center = {x: 0, y:0 };
// transformation to the coordinate origin of the canvas
var trans = svgNode.getTransformToElement(this.facade.getCanvas().rootNode.lastChild);
var scale = this.facade.getCanvas().rootNode.lastChild.getScreenCTM();
var transLocal = svgNode.getTransformToElement(svgNode.parentNode);
var bounds = undefined;
center.x = trans.e - transLocal.e;
center.y = trans.f - transLocal.f;
try {
bounds = svgNode.getBBox();
} catch (e) {}
// Firefox often fails to calculate the correct bounding box
// in this case we fall back to the upper left corner of the shape
if (bounds === null || typeof bounds === "undefined" || bounds.width == 0 || bounds.height == 0) {
bounds = {
x: Number(svgNode.getAttribute('x')),
y: Number(svgNode.getAttribute('y')),
width: 0,
height: 0
};
}
center.x += bounds.x;
center.y += bounds.y;
center.x += bounds.width/2;
center.y += bounds.height/2;
center.x *= scale.a;
center.y *= scale.d;
return center;
},
getDifferenceCenterForNode: function getDifferenceCenterForNode(svgNode){
//for shapes that do not have multiple lables on the x-line, only the vertical difference matters
var center = this.getCenterPosition(svgNode);
center.x = 0;
center.y = center.y + 10;
return center;
},
hide: function(e){
if (this.shownTextField && (!e || !this.shownTextField.el || e.target !== this.shownTextField.el.dom)) {
this.shownTextField.onBlur();
}
},
destroy: function(e){
if( this.shownTextField ){
this.shownTextField.destroy();
delete this.shownTextField;
this.facade.enableEvent(ORYX.CONFIG.EVENT_KEYDOWN);
}
}
});
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
/**
* @namespace Oryx name space for plugins
* @name ORYX.Plugins
*/
if(!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Plugins.JSONExport = ORYX.Plugins.AbstractPlugin.extend({
construct: function construct(facade) {
arguments.callee.$.construct.apply(this, arguments);
this.facade.offer({
'name': ORYX.I18N.JSONExport.name,
'functionality': this.JSONExport.bind(this),
'group': ORYX.I18N.JSONExport.group,
'iconCls': 'pw-toolbar-button pw-toolbar-export',
'description': ORYX.I18N.JSONExport.desc,
'index': 1,
'minShape': 0,
'maxShape': 0,
'isEnabled': function(){return true},
'visibleInViewMode': true
});
},
/*
* Exporting a model from the processWave editor into the ORYX editor.
* We get the JSON-serialized model, the stencilset and the stencilset-extensions
* and POST them to an ORYX-URL.
*/
JSONExport: function JSONExport() {
// Getting the JSON represantation of the model:
var serializedCanvas = this.facade.getSerializedJSON();
// Getting the stencilSet:
var ssetObj = this.facade.getStencilSets();
// ssetObj contains a KV mapping of StencilSetNamespace -> StencilSetURL.
// as we don't know what the first key is, an in-loop helps us.
for (i in ssetObj) {
var ssetURL = ssetObj[i].source();
break;
// we break after the first StencilSet because there should be just one StencilSet normally.
}
ssetURL = ssetURL.slice(ssetURL.indexOf("stencilsets/"));
ssetURL = ssetURL.replace("petrinets.json", "petrinet.json");
// the guys from oryx-project use /petrinets/petrinet.json instead of petrinets.json
ssetURL = ssetURL.replace(/simpleBPMN2.0/g, "bpmn2.0")
// simpleBPMN2.0 is not yet supported in the oryx-project...
// bpmn2.0 does the job until it is supported.
// Getting the StencilSetExtensions:
var canvasObj = this.facade.getJSON();
var exts = Object.toJSON(canvasObj.ssextensions);
// Open a window with a hidden form and POST the data to the ORYX-project:
var win = window.open("");
win.document.open();
win.document.write("<p>Exporting...</p>");
// write something so the HTML body is present.
win.document.close();
var submitForm = win.document.createElement("form");
win.document.body.appendChild(submitForm);
var createHiddenElement = function(name, value) {
var newElement = document.createElement("input");
newElement.name=name;
newElement.type="hidden";
newElement.value = value;
return newElement;
}
submitForm.appendChild(createHiddenElement("json", serializedCanvas) );
submitForm.appendChild(createHiddenElement("stencilset", ssetURL) );
submitForm.appendChild(createHiddenElement("exts", exts));
submitForm.method = "POST";
submitForm.action= "http://oryx-project.org/oryx/jsoneditor";
submitForm.submit();
}
}); | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if (!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Plugins.Wave = Clazz.extend({
facade: undefined,
construct: function construct(facade) {
this.facade = facade;
// Send Message to outer gadget frame via POST-Message using this event
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_POST_MESSAGE, this.handlePostMessage.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_SYNCRO_INITIALIZATION_DONE, this.handleInitializationDone.bind(this));
window.addEventListener("message", this.handleIncomingCommand.bind(this), false);
this.postMessage("oryx", "loaded");
//Do not dispatch scrolling to wave
/*jQuery($$(".ORYX_Editor")[0].parentNode).mousewheel(function (event, delta) {
event.stopPropagation();
return (
(event.originalEvent.wheelDeltaY < 0 && event.currentTarget.scrollTop + event.currentTarget.clientHeight < event.currentTarget.scrollHeight) ||
(event.originalEvent.wheelDeltaY > 0 && event.currentTarget.scrollTop > 0) ||
(event.originalEvent.wheelDeltaX > 0) ||
(event.originalEvent.wheelDeltaX < 0)
);
});*/
},
handlePostMessage: function handlePostMessage(event) {
this.postMessage(event.target, event.action, event.message);
},
postMessage: function postMessage(target, action, message) {
var postMessage = {
'target': target,
'action': action,
'message': message
};
window.parent.postMessage(Object.toJSON(postMessage), "*");
},
handleIncomingCommand: function handleIncomingCommand(event) {
var data = event.data.evalJSON();
if (data.target === "oryx" && data.action === "setUserId") {
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_USER_ID_CHANGED,
'userId': data.message
});
} else if (data.target === "oryx" && data.action === "setMode") {
this.setModeTo(data.message);
} else if ((data.target === "oryx" && data.action === "shown")) {
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_ORYX_SHOWN
});
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
this.updateLablesForFirefox();
}
} else if (data.target === "oryx" && data.action === "import") {
console.log("Import message received:" + data.message);
this.facade.importJSON(data.message, true);
} else {
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_NEW_POST_MESSAGE_RECEIVED,
'data': data
});
}
},
// FireFox has a text wrapping-Bug: It cannot wrap text, that is not visible.
// We therefore have to update each label after it is displayed.
updateLablesForFirefox: function updateLablesForFirefox() {
var labels = ORYX.Core.SVG.Labels;
for (var i = 0; i < labels.length; i++) {
labels[i]._isChanged = true;
labels[i].update();
}
},
setModeTo: function setModeTo(mode) {
if (mode === "edit") {
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_HIDE_SCHLAUMEIER
});
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_BLIP_TOGGLED,
'editMode': true
});
} else {
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_DISPLAY_SCHLAUMEIER,
'message': "Switch blip to edit mode to edit diagram.",
'showtimes': "always",
'duration': "infinite"
});
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_BLIP_TOGGLED,
'editMode': false
});
}
},
handleInitializationDone: function handleInitializationDone(evt) {
this.postMessage("oryx", "showOryx");
}
}); | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if (!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Plugins.Edit = Clazz.extend({
construct: function(facade){
this.facade = facade;
this.clipboard = new ORYX.Plugins.Edit.ClipBoard(facade);
this.shapesToDelete = [];
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_DRAGDROP_END, this.handleDragEnd.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_SHAPESTODELETE, this.handleShapesToDelete.bind(this));
this.facade.offer({
name: ORYX.I18N.Edit.cut,
description: ORYX.I18N.Edit.cutDesc,
iconCls: 'pw-toolbar-button pw-toolbar-cut',
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: 88,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.callEdit.bind(this, this.editCut),
isEnabled: function() { return !this.facade.isReadOnlyMode(); }.bind(this),
group: ORYX.I18N.Edit.group,
index: 1,
minShape: 1,
visibleInViewMode: false
});
this.facade.offer({
name: ORYX.I18N.Edit.copy,
description: ORYX.I18N.Edit.copyDesc,
iconCls: 'pw-toolbar-button pw-toolbar-copy',
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: 67,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.callEdit.bind(this, this.editCopy, [true, false]),
isEnabled: function() { return !this.facade.isReadOnlyMode(); }.bind(this),
group: ORYX.I18N.Edit.group,
index: 2,
minShape: 1,
visibleInViewMode: false
});
this.facade.offer({
name: ORYX.I18N.Edit.paste,
description: ORYX.I18N.Edit.pasteDesc,
iconCls: 'pw-toolbar-button pw-toolbar-paste',
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: 86,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.callEdit.bind(this, this.editPaste),
isEnabled: function() { return !this.facade.isReadOnlyMode() && this.clipboard.isOccupied; }.bind(this),
group: ORYX.I18N.Edit.group,
index: 3,
minShape: 0,
maxShape: 0,
visibleInViewMode: false
});
this.facade.offer({
name: ORYX.I18N.Edit.del,
description: ORYX.I18N.Edit.delDesc,
iconCls: 'pw-toolbar-button pw-toolbar-delete',
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: 8,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
},
{
keyCode: 46,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.callEdit.bind(this, this.editDelete),
group: ORYX.I18N.Edit.group,
index: 4,
minShape: 1,
visibleInViewMode: false
});
},
callEdit: function(fn, args){
window.setTimeout(function(){
fn.apply(this, (args instanceof Array ? args : []));
}.bind(this), 1);
},
handleShapesToDelete: function handleShapesToDelete(event) {
this.shapesToDelete = this.shapesToDelete.concat(event.deletedShapes);
},
handleDragEnd: function handleDragEnd(event) {
//shapes whose selection were not updated because they were dragged are stored in shapesToDelete
//delete shapes from shapesToDelete from selection/canvas after dragging is finished
var selectedShapes = this.facade.getSelection();
for (var i = 0; i < this.shapesToDelete.length; i++) {
this.facade.deleteShape(this.shapesToDelete[i]);
selectedShapes = selectedShapes.without(this.shapesToDelete[i]);
}
this.shapesToDelete = [];
this.facade.setSelection(selectedShapes);
this.facade.getCanvas().update();
this.facade.updateSelection();
},
/**
* Handles the mouse down event and starts the copy-move-paste action, if
* control or meta key is pressed.
*/
handleMouseDown: function(event) {
if(this._controlPressed) {
this._controlPressed = false;
this.editCopy();
console.log("copiedEle: %0",this.clipboard.shapesAsJson)
console.log("mousevent: %o",event)
this.editPaste();
event.forceExecution = true;
this.facade.raiseEvent(event, this.clipboard.shapesAsJson);
}
},
/**
* Returns a list of shapes which should be considered while copying.
* Besides the shapes of given ones, edges and attached nodes are added to the result set.
* If one of the given shape is a child of another given shape, it is not put into the result.
*/
getAllShapesToConsider: function(shapes){
var shapesToConsider = []; // only top-level shapes
var childShapesToConsider = []; // all child shapes of top-level shapes
shapes.each(function(shape){
//Throw away these shapes which have a parent in given shapes
isChildShapeOfAnother = shapes.any(function(s2){
return s2.hasChildShape(shape);
});
if(isChildShapeOfAnother) return;
// This shape should be considered
shapesToConsider.push(shape);
// Consider attached nodes (e.g. intermediate events)
if (shape instanceof ORYX.Core.Node) {
var attached = shape.getOutgoingNodes();
attached = attached.findAll(function(a){ return !shapes.include(a) });
shapesToConsider = shapesToConsider.concat(attached);
}
childShapesToConsider = childShapesToConsider.concat(shape.getChildShapes(true));
}.bind(this));
// All edges between considered child shapes should be considered
// Look for these edges having incoming and outgoing in childShapesToConsider
var edgesToConsider = this.facade.getCanvas().getChildEdges().select(function(edge){
// Ignore if already added
if(shapesToConsider.include(edge)) return false;
// Ignore if there are no docked shapes
if(edge.getAllDockedShapes().size() === 0) return false;
// True if all docked shapes are in considered child shapes
return edge.getAllDockedShapes().all(function(shape){
// Remember: Edges can have other edges on outgoing, that is why edges must not be included in childShapesToConsider
return shape instanceof ORYX.Core.Edge || childShapesToConsider.include(shape);
});
});
shapesToConsider = shapesToConsider.concat(edgesToConsider);
return shapesToConsider;
},
/**
* Performs the cut operation by first copy-ing and then deleting the
* current selection.
*/
editCut: function(){
//TODO document why this returns false.
//TODO document what the magic boolean parameters are supposed to do.
this.editCopy(false, true);
this.editDelete(true);
return false;
},
/**
* Performs the copy operation.
* @param {Object} will_not_update ??
*/
editCopy: function( will_update, useNoOffset ){
var selection = this.facade.getSelection();
//if the selection is empty, do not remove the previously copied elements
if(selection.length == 0) return;
this.clipboard.refresh(selection, this.getAllShapesToConsider(selection), this.facade.getCanvas().getStencil().stencilSet().namespace(), useNoOffset);
if( will_update ) this.facade.updateSelection(true);
},
/**
* Performs the paste operation.
*/
editPaste: function(){
// Create a new canvas with childShapes
//and stencilset namespace to be JSON Import conform
var canvas = {
childShapes: this.clipboard.shapesAsJson,
stencilset:{
namespace:this.clipboard.SSnamespace
}
}
// Apply json helper to iterate over json object
Ext.apply(canvas, ORYX.Core.AbstractShape.JSONHelper);
var childShapeResourceIds = canvas.getChildShapes(true).pluck("resourceId");
var outgoings = {};
// Iterate over all shapes
canvas.eachChild(function(shape, parent){
// Throw away these references where referenced shape isn't copied
shape.outgoing = shape.outgoing.select(function(out){
return childShapeResourceIds.include(out.resourceId);
});
shape.outgoing.each(function(out){
if (!outgoings[out.resourceId]){ outgoings[out.resourceId] = [] }
outgoings[out.resourceId].push(shape)
});
return shape;
}.bind(this), true, true);
// Iterate over all shapes
canvas.eachChild(function(shape, parent){
// Check if there has a valid target
if(shape.target && !(childShapeResourceIds.include(shape.target.resourceId))){
shape.target = undefined;
shape.targetRemoved = true;
}
// Check if the first docker is removed
if( shape.dockers &&
shape.dockers.length >= 1 &&
shape.dockers[0].getDocker &&
((shape.dockers[0].getDocker().getDockedShape() &&
!childShapeResourceIds.include(shape.dockers[0].getDocker().getDockedShape().resourceId)) ||
!shape.getShape().dockers[0].getDockedShape()&&!outgoings[shape.resourceId])) {
shape.sourceRemoved = true;
}
return shape;
}.bind(this), true, true);
// Iterate over top-level shapes
canvas.eachChild(function(shape, parent){
// All top-level shapes should get an offset in their bounds
// Move the shape occording to COPY_MOVE_OFFSET
if (this.clipboard.useOffset) {
shape.bounds = {
lowerRight: {
x: shape.bounds.lowerRight.x + ORYX.CONFIG.COPY_MOVE_OFFSET,
y: shape.bounds.lowerRight.y + ORYX.CONFIG.COPY_MOVE_OFFSET
},
upperLeft: {
x: shape.bounds.upperLeft.x + ORYX.CONFIG.COPY_MOVE_OFFSET,
y: shape.bounds.upperLeft.y + ORYX.CONFIG.COPY_MOVE_OFFSET
}
};
}
// Only apply offset to shapes with a target
if (shape.dockers){
shape.dockers = shape.dockers.map(function(docker, i){
// If shape had a target but the copied does not have anyone anymore,
// migrate the relative dockers to absolute ones.
if( (shape.targetRemoved === true && i == shape.dockers.length - 1&&docker.getDocker) ||
(shape.sourceRemoved === true && i == 0&&docker.getDocker)){
var id = docker.id;
docker = docker.getDocker().bounds.center();
docker.id = id;
}
// If it is the first docker and it has a docked shape,
// just return the coordinates
if ((i == 0 && docker.getDocker instanceof Function &&
shape.sourceRemoved !== true && (docker.getDocker().getDockedShape() || ((outgoings[shape.resourceId]||[]).length > 0 && (!(shape.getShape() instanceof ORYX.Core.Node) || outgoings[shape.resourceId][0].getShape() instanceof ORYX.Core.Node)))) ||
(i == shape.dockers.length - 1 && docker.getDocker instanceof Function &&
shape.targetRemoved !== true && (docker.getDocker().getDockedShape() || shape.target))){
return {
'x': docker.x,
'y': docker.y,
'getDocker': docker.getDocker,
'id': docker.id
}
} else if (this.clipboard.useOffset) {
return {
'x': docker.x + ORYX.CONFIG.COPY_MOVE_OFFSET,
'y': docker.y + ORYX.CONFIG.COPY_MOVE_OFFSET,
'getDocker': docker.getDocker,
'id': docker.id
};
} else {
return {
'x': docker.x,
'y': docker.y,
'getDocker': docker.getDocker,
'id': docker.id
};
}
}.bind(this));
} else if (shape.getShape() instanceof ORYX.Core.Node && shape.dockers && shape.dockers.length > 0 && (!shape.dockers.first().getDocker || shape.sourceRemoved === true || !(shape.dockers.first().getDocker().getDockedShape() || outgoings[shape.resourceId]))){
shape.dockers = shape.dockers.map(function(docker, i){
if((shape.sourceRemoved === true && i == 0&&docker.getDocker)){
var id = docker.id;
docker = docker.getDocker().bounds.center();
docker.id = id;
}
if (this.clipboard.useOffset) {
return {
'x': docker.x + ORYX.CONFIG.COPY_MOVE_OFFSET,
'y': docker.y + ORYX.CONFIG.COPY_MOVE_OFFSET,
'getDocker': docker.getDocker,
'id': docker.id
};
} else {
return {
'x': docker.x,
'y': docker.y,
'getDocker': docker.getDocker,
'id': docker.id
};
}
}.bind(this));
}
return shape;
}.bind(this), false, true);
this.clipboard.useOffset = true;
this.facade.importJSON(canvas);
},
/**
* Performs the delete operation. No more asking.
*/
editDelete: function(){
var selection = this.facade.getSelection();
var clipboard = new ORYX.Plugins.Edit.ClipBoard();
clipboard.refresh(selection, this.getAllShapesToConsider(selection));
if (clipboard.shapesAsJson.length > 0) {
var command = new ORYX.Core.Commands["Edit.DeleteCommand"](clipboard , this.facade);
this.facade.executeCommands([command]);
}
}
});
ORYX.Plugins.Edit.ClipBoard = Clazz.extend({
construct: function(facade){
this.shapesAsJson = [];
this.selection = [];
this.SSnamespace="";
this.useOffset=true;
},
isOccupied: function(){
return this.shapesAsJson.length > 0;
},
refresh: function(selection, shapes, namespace, useNoOffset){
this.selection = selection;
this.SSnamespace=namespace;
// Store outgoings, targets and parents to restore them later on
this.outgoings = {};
this.parents = {};
this.targets = {};
this.useOffset = useNoOffset !== true;
this.shapesAsJson = shapes.map(function(shape){
var s = shape.toJSON();
s.parent = {resourceId : shape.getParentShape().resourceId};
s.parentIndex = shape.getParentShape().getChildShapes().indexOf(shape)
return s;
});
}
});
ORYX.Core.Commands["Edit.DeleteCommand"] = ORYX.Core.AbstractCommand.extend({
construct: function construct(clipboard, facade) {
arguments.callee.$.construct.call(this, facade);
this.clipboard = clipboard;
this.shapesAsJson = clipboard.shapesAsJson;
var newShapesAsJson = [];
//add type and namespace to shapesAsJsonEntries
for (var i = 0; i < this.shapesAsJson.length; i++) {
var shapeAsJson = this.shapesAsJson[i];
var shape = this.facade.getCanvas().getChildShapeByResourceId(shapeAsJson.resourceId);
if (typeof shape !== "undefined") {
var stencil = shape.getStencil();
shapeAsJson.type = stencil.type();
shapeAsJson.namespace = stencil.namespace();
newShapesAsJson.push(shapeAsJson);
}
}
this.shapesAsJson = newShapesAsJson;
// Store dockers of deleted shapes to restore connections
this.dockers = this.shapesAsJson.map(function(shapeAsJson){
var shape = facade.getCanvas().getChildShapeByResourceId(shapeAsJson.resourceId);
if (typeof shape !== "undefined") {
var incomingDockers = shape.getIncomingShapes().map(function(s){return s.getDockers().last()})
var outgoingDockers = shape.getOutgoingShapes().map(function(s){return s.getDockers().first()})
var dockers = shape.getDockers().concat(incomingDockers, outgoingDockers).compact().map(function(docker) {
return {
object: docker,
referencePoint: docker.referencePoint,
dockedShape: docker.getDockedShape()
};
});
return dockers;
} else {
return [];
}
}).flatten();
},
execute: function execute() {
var deletedShapes = [];
var selectedShapes = this.facade.getSelection();
for (var i = 0; i < this.shapesAsJson.length; i++) {
var shapeAsJson = this.shapesAsJson[i];
// Delete shape
var shape = this.facade.getCanvas().getChildShapeByResourceId(shapeAsJson.resourceId);
if (typeof shape !== "undefined") {
deletedShapes.push(shape);
this.facade.raiseEvent(
{
"type": ORYX.CONFIG.EVENT_SHAPEDELETED,
"shape": shape
}
);
this.facade.deleteShape(shape);
} else {
ORYX.Log.warn("Trying to delete deleted shape.");
}
}
if (this.isLocal()) {
this.facade.getCanvas().update();
this.facade.setSelection([]);
} else {
var newSelectedShapes = selectedShapes;
for (var i = 0; i < deletedShapes.length; i++) {
newSelectedShapes = newSelectedShapes.without(deletedShapes[i]);
}
var isDragging = this.facade.isDragging();
if (!isDragging) {
this.facade.setSelection(newSelectedShapes);
} else {
//raise event, which assures, that selection and canvas will be updated after dragging is finished
this.facade.raiseEvent(
{
"type": ORYX.CONFIG.EVENT_SHAPESTODELETE,
"deletedShapes": deletedShapes
}
);
}
this.facade.getCanvas().update();
this.facade.updateSelection(this.isLocal());
}
},
rollback: function rollback(){
var selectedShapes = [];
for (var i = 0; i < this.shapesAsJson.length; i++) {
var shapeAsJson = this.shapesAsJson[i];
var shape = shapeAsJson.getShape();
selectedShapes.push(shape);
var parent = this.facade.getCanvas().getChildShapeByResourceId(shapeAsJson.parent.resourceId) || this.facade.getCanvas();
parent.add(shape, shape.parentIndex);
}
//reconnect shapes
this.dockers.each(function(d) {
d.object.setDockedShape(d.dockedShape);
d.object.setReferencePoint(d.referencePoint);
}.bind(this));
this.facade.getCanvas().update();
this.facade.updateSelection(this.isLocal());
},
getCommandData: function getCommandData() {
var options = {
shapes: this.shapesAsJson
};
return options;
},
createFromCommandData: function createFromCommandData(facade, commandData) {
var clipboard = new ORYX.Plugins.Edit.ClipBoard(facade);
var getShape = function getShape(resourceId) {
var shape = facade.getCanvas().getChildShapeByResourceId(resourceId);
return shape;
}
clipboard.shapesAsJson = commandData.shapes;
// Checking if at least one shape that has to be deleted still exists
var shapesExist = false;
for (var i = 0; i < clipboard.shapesAsJson.length; i++) {
var resourceId = clipboard.shapesAsJson[i].resourceId;
if (typeof facade.getCanvas().getChildShapeByResourceId(resourceId) !== 'undefined') {
shapesExist = true;
break;
}
}
if (!shapesExist) {
return undefined;
}
clipboard.shapesAsJson.each(function injectGetShape(shapeAsJson) {
shapeAsJson.template = shapeAsJson.properties;
shapeAsJson.shapeOptions = { resourceId: shapeAsJson.resourceId };
var shape = getShape(shapeAsJson.resourceId);
shapeAsJson.getShape = function() {
return shape;
};
});
return new ORYX.Core.Commands["Edit.DeleteCommand"](clipboard, facade);
},
getCommandName: function getCommandName() {
return "Edit.DeleteCommand";
},
getDisplayName: function getDisplayName() {
return "Shape deleted";
},
getAffectedShapes: function getAffectedShapes() {
return this.shapesAsJson.map(function (shapeAsJson) {
return shapeAsJson.getShape();
// return this.facade.getCanvas().getChildShapeByResourceId(shapeAsJson.resourceId);
}.bind(this));
}
});
ORYX.Core.Commands["Main.JsonImport"] = ORYX.Core.AbstractCommand.extend({
construct: function(jsonObject, loadSerializedCB, noSelectionAfterImport, facade){
arguments.callee.$.construct.call(this, facade);
this.jsonObject = jsonObject;
this.noSelection = noSelectionAfterImport;
this.shapes;
this.connections = [];
this.parents = new Hash();
this.selection = this.facade.getSelection();
this.loadSerialized = loadSerializedCB;
},
getAffectedShapes: function getAffectedShapes() {
if (this.shapes) {
return this.shapes;
}
return [];
},
getCommandData: function getCommandData() {
return {"jsonObject": this.jsonObject};
},
createFromCommandData: function createFromCommandData(facade, data) {
return new ORYX.Core.Commands["Main.JsonImport"](data.jsonObject, facade.loadSerialized, true, facade);
},
getCommandName: function getCommandName() {
return "Main.JsonImport";
},
getDisplayName: function getDisplayName() {
return "Shape pasted";
},
execute: function(){
if (!this.shapes) {
// Import the shapes out of the serialization
this.shapes = this.loadSerialized( this.jsonObject );
//store all connections
this.shapes.each(function(shape) {
if (shape.getDockers) {
var dockers = shape.getDockers();
if (dockers) {
if (dockers.length > 0) {
this.connections.push([dockers.first(), dockers.first().getDockedShape(), dockers.first().referencePoint]);
}
if (dockers.length > 1) {
this.connections.push([dockers.last(), dockers.last().getDockedShape(), dockers.last().referencePoint]);
}
}
}
//store parents
this.parents[shape.id] = shape.parent;
}.bind(this));
} else {
this.shapes.each(function(shape) {
this.parents[shape.id].add(shape);
}.bind(this));
this.connections.each(function(con) {
con[0].setDockedShape(con[1]);
con[0].setReferencePoint(con[2]);
//con[0].update();
});
}
//this.parents.values().uniq().invoke("update");
this.facade.getCanvas().update();
if(!this.noSelection)
this.facade.setSelection(this.shapes);
else
this.facade.updateSelection(true);
},
rollback: function(){
var selection = this.facade.getSelection();
this.shapes.each(function(shape) {
selection = selection.without(shape);
this.facade.deleteShape(shape);
}.bind(this));
this.facade.getCanvas().update();
this.facade.setSelection(selection);
}
});
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if(!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Plugins.SelectionFrame = Clazz.extend({
construct: function(facade) {
this.facade = facade;
// Register on MouseEvents
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MOUSEDOWN, this.handleMouseDown.bind(this));
document.documentElement.addEventListener(ORYX.CONFIG.EVENT_MOUSEUP, this.handleMouseUp.bind(this), true);
// Some initiale variables
this.position = {x:0, y:0};
this.size = {width:0, height:0};
this.offsetPosition = {x: 0, y: 0}
// (Un)Register Mouse-Move Event
this.moveCallback = undefined;
this.offsetScroll = {x:0,y:0}
// HTML-Node of Selection-Frame
this.node = ORYX.Editor.graft("http://www.w3.org/1999/xhtml", this.facade.getCanvas().getHTMLContainer(),
['div', {'class':'Oryx_SelectionFrame'}]);
this.hide();
},
handleMouseDown: function(event, uiObj) {
// If there is the Canvas
if( uiObj instanceof ORYX.Core.Canvas ) {
// Calculate the Offset
var scrollNode = uiObj.rootNode.parentNode.parentNode;
var a = this.facade.getCanvas().node.getScreenCTM();
this.offsetPosition = {
x: a.e,
y: a.f
}
// Set the new Position
this.setPos({x: Event.pointerX(event)-this.offsetPosition.x, y:Event.pointerY(event)-this.offsetPosition.y});
// Reset the size
this.resize({width:0, height:0});
this.moveCallback = this.handleMouseMove.bind(this);
// Register Mouse-Move Event
document.documentElement.addEventListener(ORYX.CONFIG.EVENT_MOUSEMOVE, this.moveCallback, false);
this.offsetScroll = {x:scrollNode.scrollLeft,y:scrollNode.scrollTop};
// Show the Frame
this.show();
}
Event.stop(event);
},
handleMouseUp: function(event) {
// If there was an MouseMoving
if(this.moveCallback) {
// Hide the Frame
this.hide();
// Unregister Mouse-Move
document.documentElement.removeEventListener(ORYX.CONFIG.EVENT_MOUSEMOVE, this.moveCallback, false);
this.moveCallback = undefined;
var corrSVG = this.facade.getCanvas().node.getScreenCTM();
// Calculate the positions of the Frame
var a = {
x: this.size.width > 0 ? this.position.x : this.position.x + this.size.width,
y: this.size.height > 0 ? this.position.y : this.position.y + this.size.height
}
var b = {
x: a.x + Math.abs(this.size.width),
y: a.y + Math.abs(this.size.height)
}
// Fit to SVG-Coordinates
a.x /= corrSVG.a; a.y /= corrSVG.d;
b.x /= corrSVG.a; b.y /= corrSVG.d;
// Calculate the elements from the childs of the canvas
var elements = this.facade.getCanvas().getChildShapes(true).findAll(function(value) {
var absBounds = value.absoluteBounds();
var bA = absBounds.upperLeft();
var bB = absBounds.lowerRight();
return (bA.x > a.x && bA.y > a.y && bB.x < b.x && bB.y < b.y);
});
this.facade.setSelection(elements, undefined, undefined, true);
}
},
handleMouseMove: function(event) {
// Calculate the size
var size = {
width : Event.pointerX(event) - this.position.x - this.offsetPosition.x,
height : Event.pointerY(event) - this.position.y - this.offsetPosition.y
}
var scrollNode = this.facade.getCanvas().rootNode.parentNode.parentNode;
size.width -= this.offsetScroll.x - scrollNode.scrollLeft;
size.height -= this.offsetScroll.y - scrollNode.scrollTop;
// Set the size
this.resize(size);
Event.stop(event);
},
hide: function() {
this.node.style.display = "none";
},
show: function() {
this.node.style.display = "";
},
setPos: function(pos) {
// Set the Position
this.node.style.top = pos.y + "px";
this.node.style.left = pos.x + "px";
this.position = pos;
},
resize: function(size) {
// Calculate the negative offset
this.setPos(this.position);
this.size = Object.clone(size);
if(size.width < 0) {
this.node.style.left = (this.position.x + size.width) + "px";
size.width = - size.width;
}
if(size.height < 0) {
this.node.style.top = (this.position.y + size.height) + "px";
size.height = - size.height;
}
// Set the size
this.node.style.width = size.width + "px";
this.node.style.height = size.height + "px";
}
});
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if (!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Plugins.KeysMove = ORYX.Plugins.AbstractPlugin.extend({
facade: undefined,
construct: function(facade){
this.facade = facade;
this.copyElements = [];
//this.facade.registerOnEvent(ORYX.CONFIG.EVENT_KEYDOWN, this.keyHandler.bind(this));
// SELECT ALL
this.facade.offer({
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: 65,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.selectAll.bind(this)
});
// MOVE LEFT SMALL
this.facade.offer({
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: ORYX.CONFIG.KEY_CODE_LEFT,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.move.bind(this, ORYX.CONFIG.KEY_CODE_LEFT, false)
});
// MOVE LEFT
this.facade.offer({
keyCodes: [{
keyCode: ORYX.CONFIG.KEY_CODE_LEFT,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.move.bind(this, ORYX.CONFIG.KEY_CODE_LEFT, true)
});
// MOVE RIGHT SMALL
this.facade.offer({
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: ORYX.CONFIG.KEY_CODE_RIGHT,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.move.bind(this, ORYX.CONFIG.KEY_CODE_RIGHT, false)
});
// MOVE RIGHT
this.facade.offer({
keyCodes: [{
keyCode: ORYX.CONFIG.KEY_CODE_RIGHT,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.move.bind(this, ORYX.CONFIG.KEY_CODE_RIGHT, true)
});
// MOVE UP SMALL
this.facade.offer({
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: ORYX.CONFIG.KEY_CODE_UP,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.move.bind(this, ORYX.CONFIG.KEY_CODE_UP, false)
});
// MOVE UP
this.facade.offer({
keyCodes: [{
keyCode: ORYX.CONFIG.KEY_CODE_UP,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.move.bind(this, ORYX.CONFIG.KEY_CODE_UP, true)
});
// MOVE DOWN SMALL
this.facade.offer({
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: ORYX.CONFIG.KEY_CODE_DOWN,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.move.bind(this, ORYX.CONFIG.KEY_CODE_DOWN, false)
});
// MOVE DOWN
this.facade.offer({
keyCodes: [{
keyCode: ORYX.CONFIG.KEY_CODE_DOWN,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.move.bind(this, ORYX.CONFIG.KEY_CODE_DOWN, true)
});
},
/**
* Select all shapes in the editor
*
*/
selectAll: function(e){
Event.stop(e.event);
this.facade.setSelection(this.facade.getCanvas().getChildShapes(true))
},
move: function(key, far, e) {
Event.stop(e.event);
// calculate the distance to move the objects and get the selection.
var distance = far? 20 : 5;
var selection = this.facade.getSelection();
var currentSelection = this.facade.getSelection();
var p = {x: 0, y: 0};
// switch on the key pressed and populate the point to move by.
switch(key) {
case ORYX.CONFIG.KEY_CODE_LEFT:
p.x = -1*distance;
break;
case ORYX.CONFIG.KEY_CODE_RIGHT:
p.x = distance;
break;
case ORYX.CONFIG.KEY_CODE_UP:
p.y = -1*distance;
break;
case ORYX.CONFIG.KEY_CODE_DOWN:
p.y = distance;
break;
}
// move each shape in the selection by the point calculated and update it.
selection = selection.findAll(function(shape){
// Check if this shape is docked to an shape in the selection
if(shape instanceof ORYX.Core.Node && shape.dockers.length == 1 && selection.include( shape.dockers.first().getDockedShape() )){
return false
}
// Check if any of the parent shape is included in the selection
var s = shape.parent;
do{
if(selection.include(s)){
return false
}
}while(s = s.parent);
// Otherwise, return true
return true;
});
/* Edges must not be movable, if only edges are selected and at least
* one of them is docked.
*/
var edgesMovable = true;
var onlyEdgesSelected = selection.all(function(shape) {
if(shape instanceof ORYX.Core.Edge) {
if(shape.isDocked()) {
edgesMovable = false;
}
return true;
}
return false;
});
if(onlyEdgesSelected && !edgesMovable) {
/* Abort moving shapes */
return;
}
selection = selection.map(function(shape){
if( shape instanceof ORYX.Core.Node ){
/*if( shape.dockers.length == 1 ){
return shape.dockers.first()
} else {*/
return shape
//}
} else if( shape instanceof ORYX.Core.Edge ) {
var dockers = shape.dockers;
if( selection.include( shape.dockers.first().getDockedShape() ) ){
dockers = dockers.without( shape.dockers.first() )
}
if( selection.include( shape.dockers.last().getDockedShape() ) ){
dockers = dockers.without( shape.dockers.last() )
}
return dockers
} else {
return null
}
}).flatten().compact();
if (selection.size() > 0) {
//Stop moving at canvas borders
var selectionBounds = [ this.facade.getCanvas().bounds.lowerRight().x,
this.facade.getCanvas().bounds.lowerRight().y,
0,
0 ];
selection.each(function(s) {
selectionBounds[0] = Math.min(selectionBounds[0], s.bounds.upperLeft().x);
selectionBounds[1] = Math.min(selectionBounds[1], s.bounds.upperLeft().y);
selectionBounds[2] = Math.max(selectionBounds[2], s.bounds.lowerRight().x);
selectionBounds[3] = Math.max(selectionBounds[3], s.bounds.lowerRight().y);
});
if (selectionBounds[0]+p.x < 0)
p.x = -selectionBounds[0];
if (selectionBounds[1]+p.y < 0)
p.y = -selectionBounds[1];
var shapeDistancesToParentLowerY = selection.map(function(shape) {
var parent = shape.parent || this.facade.getCanvas();
return Math.abs(parent.absoluteBounds().lowerRight().y - shape.absoluteBounds().lowerRight().y);
});
var minShapeDistanceY = shapeDistancesToParentLowerY.min();
var shapeDistancesToParentLowerX = selection.map(function(shape) {
var parent = shape.parent || this.facade.getCanvas();
return Math.abs(parent.absoluteBounds().lowerRight().x - shape.absoluteBounds().lowerRight().x);
});
var minShapeDistanceX = shapeDistancesToParentLowerX.min();
if (p.x > minShapeDistanceX)
p.x = minShapeDistanceX;
if (p.y > minShapeDistanceY)
p.y = minShapeDistanceY;
if (p.x!=0 || p.y!=0) {
// Instantiate the moveCommand
var moveShapes = selection.map(function addTargetPositionToShapes(shape) {
return {
shape: shape,
origin: shape.absoluteBounds().center(),
target: {'x': shape.absoluteBounds().center().x + p.x, 'y': shape.absoluteBounds().center().y + p.y}
};
}.bind(this));
var commands = [new ORYX.Core.Commands["DragDropResize.MoveCommand"](moveShapes, null, currentSelection, this.facade)];
// Execute the commands
this.facade.executeCommands(commands);
}
}
}
// /**
// * The key handler for this plugin. Every action from the set of cut, copy,
// * paste and delete should be accessible trough simple keyboard shortcuts.
// * This method checks whether any event triggers one of those actions.
// *
// * @param {Object} event The keyboard event that should be analysed for
// * triggering of this plugin.
// */
// keyHandler: function(event){
// //TODO document what event.which is.
//
// ORYX.Log.debug("keysMove.js handles a keyEvent.");
//
// // assure we have the current event.
// if (!event)
// event = window.event;
//
// // get the currently pressed key and state of control key.
// var pressedKey = event.which || event.keyCode;
// var ctrlPressed = event.ctrlKey;
//
// // if the key is one of the arrow keys, forward to move and return.
// if ([ORYX.CONFIG.KEY_CODE_LEFT, ORYX.CONFIG.KEY_CODE_RIGHT,
// ORYX.CONFIG.KEY_CODE_UP, ORYX.CONFIG.KEY_CODE_DOWN].include(pressedKey)) {
//
// this.move(pressedKey, !ctrlPressed);
// return;
// }
//
// }
});
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if(!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Plugins.ShapeHighlighting = Clazz.extend({
construct: function(facade) {
this.parentNode = facade.getCanvas().getSvgContainer();
// The parent Node
this.node = ORYX.Editor.graft("http://www.w3.org/2000/svg", this.parentNode,
['g']);
this.highlightNodes = {};
facade.registerOnEvent(ORYX.CONFIG.EVENT_HIGHLIGHT_SHOW, this.setHighlight.bind(this));
facade.registerOnEvent(ORYX.CONFIG.EVENT_HIGHLIGHT_HIDE, this.hideHighlight.bind(this));
},
setHighlight: function(options) {
if(options && options.highlightId){
var node = this.highlightNodes[options.highlightId];
if(!node){
node= ORYX.Editor.graft("http://www.w3.org/2000/svg", this.node,
['path', {
"stroke-width": 2.0, "fill":"none"
}]);
this.highlightNodes[options.highlightId] = node;
}
if(options.elements && options.elements.length > 0) {
this.setAttributesByStyle( node, options );
this.show(node);
} else {
this.hide(node);
}
}
},
hideHighlight: function(options) {
if(options && options.highlightId && this.highlightNodes[options.highlightId]){
this.hide(this.highlightNodes[options.highlightId]);
}
},
hide: function(node) {
node.setAttributeNS(null, 'display', 'none');
},
show: function(node) {
node.setAttributeNS(null, 'display', '');
},
setAttributesByStyle: function( node, options ){
// If the style say, that it should look like a rectangle
if( options.style && options.style == ORYX.CONFIG.SELECTION_HIGHLIGHT_STYLE_RECTANGLE ){
// Set like this
var bo = options.elements[0].absoluteBounds();
var strWidth = options.strokewidth ? options.strokewidth : ORYX.CONFIG.BORDER_OFFSET
node.setAttributeNS(null, "d", this.getPathRectangle( bo.a, bo.b , strWidth ) );
node.setAttributeNS(null, "stroke", options.color ? options.color : ORYX.CONFIG.SELECTION_HIGHLIGHT_COLOR);
node.setAttributeNS(null, "stroke-opacity", options.opacity ? options.opacity : 0.2);
node.setAttributeNS(null, "stroke-width", strWidth);
} else if(options.elements.length == 1
&& options.elements[0] instanceof ORYX.Core.Edge &&
options.highlightId != "selection") {
/* Highlight containment of edge's childs */
node.setAttributeNS(null, "d", this.getPathEdge(options.elements[0].dockers));
node.setAttributeNS(null, "stroke", options.color ? options.color : ORYX.CONFIG.SELECTION_HIGHLIGHT_COLOR);
node.setAttributeNS(null, "stroke-opacity", options.opacity ? options.opacity : 0.2);
node.setAttributeNS(null, "stroke-width", ORYX.CONFIG.OFFSET_EDGE_BOUNDS);
}else {
// If not, set just the corners
node.setAttributeNS(null, "d", this.getPathByElements(options.elements));
node.setAttributeNS(null, "stroke", options.color ? options.color : ORYX.CONFIG.SELECTION_HIGHLIGHT_COLOR);
node.setAttributeNS(null, "stroke-opacity", options.opacity ? options.opacity : 1.0);
node.setAttributeNS(null, "stroke-width", options.strokewidth ? options.strokewidth : 2.0);
}
},
getPathByElements: function(elements){
if(!elements || elements.length <= 0) {return undefined}
// Get the padding and the size
var padding = ORYX.CONFIG.SELECTED_AREA_PADDING;
var path = ""
// Get thru all Elements
elements.each((function(element) {
if(!element) {return}
// Get the absolute Bounds and the two Points
var bounds = element.absoluteBounds();
bounds.widen(padding)
var a = bounds.upperLeft();
var b = bounds.lowerRight();
path = path + this.getPath(a ,b);
}).bind(this));
return path;
},
getPath: function(a, b){
return this.getPathCorners(a, b);
},
getPathCorners: function(a, b){
var size = ORYX.CONFIG.SELECTION_HIGHLIGHT_SIZE;
var path = ""
// Set: Upper left
path = path + "M" + a.x + " " + (a.y + size) + " l0 -" + size + " l" + size + " 0 ";
// Set: Lower left
path = path + "M" + a.x + " " + (b.y - size) + " l0 " + size + " l" + size + " 0 ";
// Set: Lower right
path = path + "M" + b.x + " " + (b.y - size) + " l0 " + size + " l-" + size + " 0 ";
// Set: Upper right
path = path + "M" + b.x + " " + (a.y + size) + " l0 -" + size + " l-" + size + " 0 ";
return path;
},
getPathRectangle: function(a, b, strokeWidth){
var size = ORYX.CONFIG.SELECTION_HIGHLIGHT_SIZE;
var path = ""
var offset = strokeWidth / 2.0;
// Set: Upper left
path = path + "M" + (a.x + offset) + " " + (a.y);
path = path + " L" + (a.x + offset) + " " + (b.y - offset);
path = path + " L" + (b.x - offset) + " " + (b.y - offset);
path = path + " L" + (b.x - offset) + " " + (a.y + offset);
path = path + " L" + (a.x + offset) + " " + (a.y + offset);
return path;
},
getPathEdge: function(edgeDockers) {
var length = edgeDockers.length;
var path = "M" + edgeDockers[0].bounds.center().x + " "
+ edgeDockers[0].bounds.center().y;
for(i=1; i<length; i++) {
var dockerPoint = edgeDockers[i].bounds.center();
path = path + " L" + dockerPoint.x + " " + dockerPoint.y;
}
return path;
}
});
ORYX.Plugins.HighlightingSelectedShapes = Clazz.extend({
construct: function(facade) {
this.facade = facade;
this.opacityFull = 0.9;
this.opacityLow = 0.4;
// Register on Dragging-Events for show/hide of ShapeMenu
//this.facade.registerOnEvent(ORYX.CONFIG.EVENT_DRAGDROP_START, this.hide.bind(this));
//this.facade.registerOnEvent(ORYX.CONFIG.EVENT_DRAGDROP_END, this.show.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_CANVAS_RESIZE_UPDATE_HIGHLIGHTS, this.onSelectionChanged.bind(this));
},
/**
* On the Selection-Changed
*
*/
onSelectionChanged: function(event) {
if(event.elements && event.elements.length > 1) {
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_HIGHLIGHT_SHOW,
highlightId:'selection',
elements: event.elements.without(event.subSelection),
color: ORYX.CONFIG.SELECTION_HIGHLIGHT_COLOR,
opacity: !event.subSelection ? this.opacityFull : this.opacityLow
});
if(event.subSelection){
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_HIGHLIGHT_SHOW,
highlightId:'subselection',
elements: [event.subSelection],
color: ORYX.CONFIG.SELECTION_HIGHLIGHT_COLOR,
opacity: this.opacityFull
});
} else {
this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_HIGHLIGHT_HIDE, highlightId:'subselection'});
}
} else {
this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_HIGHLIGHT_HIDE, highlightId:'selection'});
this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_HIGHLIGHT_HIDE, highlightId:'subselection'});
}
}
});
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
/**
* @namespace Oryx name space for plugins
* @name ORYX.Plugins
*/
if(!ORYX.Plugins)
ORYX.Plugins = new Object();
/**
* The UML plugin provides layout methods referring to the UML stencilset.
*
* @class ORYX.Plugins.UML
* @extends Clazz
* @param {Object} facade The facade of the editor
*/
ORYX.Plugins.UML =
/** @lends ORYX.Plugins.UML.prototype */
{
/**
* Creates a new instance of the UML plugin and registers it on the
* layout events listed in the UML stencil set.
*
* @constructor
* @param {Object} facade The facade of the editor
*/
construct: function(facade) {
this.facade = facade;
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_PROPWINDOW_PROP_CHANGED, this.handlePropertyChanged.bind(this));
this.facade.registerOnEvent('layout.uml.class', this.handleLayoutClass.bind(this));
this.facade.registerOnEvent('layout.uml.list', this.handleLayoutList.bind(this));
this.facade.registerOnEvent('layout.uml.association', this.handleLayoutAssociation.bind(this));
this.facade.registerOnEvent('layout.uml.qualified_association', this.handleLayoutQualifiedAssociation.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LOADED, this.addReadingDirectionOnLoad.bind(this));
},
/**
* Add reading direction on load.
*
* Because the reading direction arrow is added to the
* label of an edge, we have to iterate over all edges
* and add the arrow on load for it to appear.
*
* @param {Object} event
*/
addReadingDirectionOnLoad : function(event) {
this.facade.getCanvas().edges.each(function(shape){
if (shape.properties["oryx-direction"] == "left" || shape.properties["oryx-direction"] == "right") {
this.addReadingDirection(shape);
}
}.bind(this));
},
/**
* calculates the height of a text, taking line breaks into consideration
*
* @param {Object} labelElement the label
* @param {String} the label test
*/
calculateLabelHeight : function (labelElement, labelValue) {
var fontSize = labelElement.getFontSize();
var newlineOccurences = 1;
labelValue.scan('\n', function() { newlineOccurences += 1; });
// 0.75 account for padding around the label
return newlineOccurences * fontSize + 0.75;
},
/**
* Add Reading Direction to the name label after it has been changed
*/
handlePropertyChanged : function(event) {
if (event["key"] == "oryx-name") {
this.addReadingDirection(event.elements[0]);
}
},
/**
* Layout class shapes.
* - make text italic when abstract
* - resize methods and attributes boxes according to their content
*/
handleLayoutClass : function(event) {
var shape = event.shape;
if (shape.propertiesChanged["oryx-abstract"] == true) {
var className = event.shape.getLabels().find(
function(label) { return label.id == (event.shape.id + "className") }
);
if (shape.properties["oryx-abstract"] == true) {
className.node.setAttribute("font-style", "italic");
} else {
className.node.setAttribute("font-style", "none");
}
}
if (shape.propertiesChanged["oryx-attributes"] == true || shape.propertiesChanged["oryx-methods"]) {
var attributesValue = event.shape.properties["oryx-attributes"];
var methodsValue = event.shape.properties["oryx-methods"];
var attributes = event.shape.getLabels().find(
function(label) { return label.id == (event.shape.id + "attributes") }
);
var methods = event.shape.getLabels().find(
function(label) { return label.id == (event.shape.id + "methods") }
);
var separator = event.shape._svgShapes.find(
function(element) { return element.element.id == (event.shape.id + "separator") }
).element;
var attributesHeight = this.calculateLabelHeight(attributes, attributesValue);
var methodsHeight = this.calculateLabelHeight(methods, methodsValue);
// 24px account for the class name
var distanceTilSeparator = 24 + attributesHeight + 2;
var heightOfOneLine = 12 + 2; // 12px font size, 4px paddng
var distanceTilBottom = distanceTilSeparator + methodsHeight + 2;
separator.setAttribute("transform", "translate(0, " + (attributesHeight - heightOfOneLine) + ")");
// separator.setAttribute("y1", distanceTilSeparator);
// separator.setAttribute("y2", distanceTilSeparator);
// realign methods label (so that oryx' internal references are correct)
methods.y = distanceTilSeparator + 3;
methods.node.setAttribute("y", distanceTilSeparator + 3);
// realign the methods line by line (required for a visual change)
for (var i = 0; i < methods.node.childElementCount; i++) {
methods.node.childNodes[i].setAttribute("y", distanceTilSeparator + 2);
}
// resize shape
shape.bounds.set(
shape.bounds.a.x,
shape.bounds.a.y,
shape.bounds.b.x,
shape.bounds.a.y + distanceTilBottom + 7
);
}
},
/**
* Layout the interface and enumeration shape. Resize according to their content.
*/
handleLayoutList : function(event) {
var shape = event.shape;
if (shape.propertiesChanged["oryx-items"] == true) {
var itemsValue = shape.properties["oryx-items"];
var items = shape.getLabels().find(
function(label) { return label.id == (event.shape.id + "items") }
);
var itemsHeight = this.calculateLabelHeight(items, itemsValue);
var distanceTilBottom = 32 + itemsHeight + 2;
// resize shape
shape.bounds.set(
shape.bounds.a.x,
shape.bounds.a.y,
shape.bounds.b.x,
shape.bounds.a.y + distanceTilBottom + 5
);
}
},
/**
* Draws the reading direction arrow when an association is changed.
*/
handleLayoutAssociation : function(event) {
this.addReadingDirection(event.shape);
},
/**
* Adds the reading direction to the "name" label of an association.
*/
addReadingDirection : function(shape) {
var name = shape.getLabels().find(
function(label) { return label.id == (shape.id + "name") }
);
if (shape.properties["oryx-direction"] == "left") {
name.text("◀ " + shape.properties["oryx-name"]);
}
else if (shape.properties["oryx-direction"] == "right") {
name.text(shape.properties["oryx-name"] + " ▶");
}
else {
name.text(shape.properties["oryx-name"]);
}
name.update();
},
/**
* Resizes the qualifier box of a qualified association according to its content.
*/
handleLayoutQualifiedAssociation : function(event) {
var shape = event.shape;
var qualifier = shape.getLabels().find(
function(label) { return label.id == (event.shape.id + "qualifier") }
);
var size = qualifier._estimateTextWidth(shape.properties["oryx-qualifier"], 12);
// enforce minimum size, looks bad otherwise
if (size < 40) size = 40;
shape._markers.values()[0].element.lastElementChild.setAttribute("width", size+5);
shape._markers.values()[0].element.setAttributeNS(null, "markerWidth", size+5)
}
};
ORYX.Plugins.UML = Clazz.extend(ORYX.Plugins.UML);
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if (!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Plugins.ShapeTooltip = ORYX.Plugins.AbstractPlugin.extend({
_users: {},
construct: function construct() {
arguments.callee.$.construct.apply(this, arguments);
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_SHAPEADDED, this.addHoverListener.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_SHAPEDELETED, this.removeTooltip.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_FARBRAUSCH_NEW_INFOS, this.handleFarbrauschEvent.bind(this));
},
handleFarbrauschEvent: function handleFarbrauschEvent(evt) {
for (var userId in evt.users) {
if (!evt.users.hasOwnProperty(userId)) {
return;
}
var evtUser = evt.users[userId];
var user = this._users[userId];
if (typeof user === "undefined" || evtUser.color !== user.color || evtUser.displayName !== user.displayName || evtUser.thumbnailUrl !== user.thumbnailUrl) {
this._users[userId] = evtUser;
}
}
},
_getThumbnailUrlById: function _getThumbnailUrlById(id) {
var user = this._users[id];
if (user) {
return user.thumbnailUrl;
}
return "https://wave.google.com/wave/static/images/unknown.jpg";
},
_getColorById: function _getColorById(id) {
var user = this._users[id];
if (user) {
return user.color;
}
return "#000000";
},
_getDisplayNameById: function _getThumbnailUrlById(id) {
var user = this._users[id];
if (user) {
return user.displayName;
}
return "Anonymous";
},
/*
* JavaScript Pretty Date
* Copyright (c) 2008 John Resig (jquery.com)
* Licensed under the MIT license.
*/
_prettyDate: function _prettyDate(time){
var date = new Date();
date.setTime(time);
var diff = (((new Date()).getTime() - date.getTime()) / 1000);
var day_diff = Math.floor(diff / 86400);
if (isNaN(day_diff) || day_diff < 0) {
return "from future";
}
return day_diff == 0 && (
diff < 3 && "just now" ||
diff < 60 && (Math.round(diff / 5) * 5) + " seconds ago" ||
diff < 120 && "1 minute ago" ||
diff < 3600 && Math.floor(diff / 60) + " minutes ago" ||
diff < 7200 && "1 hour ago" ||
diff < 86400 && Math.floor(diff / 3600) + " hours ago") ||
day_diff == 1 && "Yesterday" ||
day_diff < 7 && day_diff + " days ago" ||
day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago" ||
Math.round(day_diff / 365) == 1 && "1 year ago" ||
Math.round(day_diff / 365) + " years ago";
},
removeTooltip: function removeTooltip(event) {
var shape = event.shape;
if ((shape instanceof ORYX.Core.AbstractShape) && (typeof this.associatedShape !== "undefined")) {
if (shape.resourceId === this.associatedShape.resourceId) {
var hover = {};
clearTimeout(hover.timer);
this.hideOverlay();
}
}
},
addHoverListener: function addHoverListener(event) {
var shape = event.shape;
if (shape instanceof ORYX.Core.AbstractShape) {
var hover = {};
var clearTooltip = function clearTooltip(event) {
clearTimeout(hover.timer);
this.hideOverlay();
}
var handleMouseOver = function handleMouseOver(event) {
var createTooltip = function createTooltip() {
this.associatedShape = shape;
this.hideOverlay();
var border = 5;
var imageWidth = 40;
if (!shape.metadata) {
return;
}
var displayName = this._getDisplayNameById(shape.getLastChangedBy());
var prettyDate = this._prettyDate(shape.getLastChangedAt());
var thumbnailUrl = this._getThumbnailUrlById(shape.getLastChangedBy());
var commandName = shape.getLastCommandDisplayName() || "Awesome stuff";
var g = ORYX.Editor.graft("http://www.w3.org/2000/svg", null,
['g', {"x": 0, "y": 0, "height": 55}]
);
var rect = ORYX.Editor.graft("http://www.w3.org/2000/svg", g,
['rect', {"name": "bubble","x": border, "y": border, "rx": 5, "ry": 5, "width": 140, "height": (imageWidth + 8), "style": "fill: rgb(255, 250, 205); stroke-width:0.5; stroke:rgb(0,0,0)"}]
);
var avatar = ORYX.Editor.graft("http://www.w3.org/2000/svg", g,
['image', {"x": border + 5, "y": border + 4, "width": imageWidth, "height": imageWidth}]
);
var username = ORYX.Editor.graft("http://www.w3.org/2000/svg", g,
['text', {"x": border + (imageWidth + 11), "y": border + 15, "style": "stroke-width: 0; fill: rgb(42, 42, 42);"}]
);
username.textContent = displayName;
var command = ORYX.Editor.graft("http://www.w3.org/2000/svg", g,
['text', {"x": border + (imageWidth + 11), "y": border + 28, "style": "stroke-width: 0; fill: rgb(127, 125, 102);", "font-size": 10}]
);
command.textContent = commandName;
var time = ORYX.Editor.graft("http://www.w3.org/2000/svg", g,
['text', {"x": border + (imageWidth + 11), "y": border + 41, "style": "stroke-width: 0; fill: rgb(127, 125, 102);", "font-size": 10}]
);
time.textContent = prettyDate;
var userNameEl = new ORYX.Core.SVG.Label({'textElement' : username});
var commandEl = new ORYX.Core.SVG.Label({'textElement' : command});
var timeEl = new ORYX.Core.SVG.Label({'textElement' : time});
var widthDisplayName = userNameEl._estimateTextWidth(displayName, 12);
var widthCommandName = commandEl._estimateTextWidth(commandName, 10);
var widthDate = timeEl._estimateTextWidth(prettyDate, 10);
// adjust rect width to make username fit
rect.setAttribute("width", Math.max(Math.max(widthDisplayName, widthCommandName), widthDate) + (imageWidth + 26));
var avatarCorners = ORYX.Editor.graft("http://www.w3.org/2000/svg", g,
['rect', {"x": border + 5, "y": border + 4, "rx": 2, "ry": 2, "width": imageWidth, "height": imageWidth, "style": "fill-opacity: 0.0; stroke-width: 1; stroke: rgb(255, 250, 205)"}]
);
avatar.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', thumbnailUrl);
this.showOverlay(shape, null, g, "N", false, true);
};
hover.timer = setTimeout(createTooltip.bind(this), 600);
};
shape.node.addEventListener(ORYX.CONFIG.EVENT_MOUSEOVER, handleMouseOver.bind(this), true);
shape.node.addEventListener(ORYX.CONFIG.EVENT_MOUSEOUT, clearTooltip.bind(this), true);
}
}
}); | JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if(!ORYX.Plugins) {
ORYX.Plugins = new Object();
}
ORYX.Plugins.ShapeMenuPlugin = {
construct: function(facade) {
this.facade = facade;
this.alignGroups = new Hash();
var containerNode = this.facade.getCanvas().getHTMLContainer();
this.shapeMenu = new ORYX.Plugins.ShapeMenu(containerNode);
this.currentShapes = [];
// Register on dragging and resizing events for show/hide of ShapeMenu
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_DRAGDROP_START, this.hideShapeMenu.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_DRAGDROP_END, this.showShapeMenu.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_RESIZE_START, (function(){
this.hideShapeMenu();
this.hideMorphMenu();
}).bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_RESIZE_END, this.showShapeMenu.bind(this));
// Enable DragZone
var DragZone = new Ext.dd.DragZone(containerNode.parentNode, {shadow: !Ext.isMac});
DragZone.afterDragDrop = this.afterDragging.bind(this, DragZone);
DragZone.beforeDragOver = this.beforeDragOver.bind(this, DragZone);
// Memory of created Buttons
this.createdButtons = {};
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_STENCIL_SET_LOADED, (function(){ this.registryChanged() }).bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_SHAPEDELETED, this.clearShapeMenu.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_SHAPEBOUNDS_CHANGED, this.onBoundsChanged.bind(this));
this.timer = null;
this.resetElements = true;
},
onBoundsChanged: function onBoundsChanged(event) {
if (this.currentShapes.include(event.shape)) {
this.hideShapeMenu();
this.showShapeMenu();
}
},
clearShapeMenu: function clearShapeMenu(event) {
if (this.currentShapes.include(event.shape)) {
this.hideShapeMenu();
}
},
hideShapeMenu: function(event) {
window.clearTimeout(this.timer);
this.timer = null;
this.shapeMenu.hide();
},
showShapeMenu: function( dontGenerateNew ) {
if( !dontGenerateNew || this.resetElements ){
window.clearTimeout(this.timer);
this.timer = window.setTimeout(function(){
// Close all Buttons
this.shapeMenu.closeAllButtons();
// Show the Morph Button
this.showMorphButton(this.currentShapes);
// Show the Stencil Buttons
this.showStencilButtons(this.currentShapes);
// Show the ShapeMenu
this.shapeMenu.show(this.currentShapes);
this.resetElements = false;
}.bind(this), 300)
} else {
window.clearTimeout(this.timer);
this.timer = null;
// Show the ShapeMenu
this.shapeMenu.show(this.currentShapes);
}
},
registryChanged: function(pluginsData) {
if(pluginsData) {
pluginsData = pluginsData.each(function(value) {value.group = value.group ? value.group : 'unknown'});
this.pluginsData = pluginsData.sortBy( function(value) {
return (value.group + "" + value.index);
});
}
this.shapeMenu.removeAllButtons();
this.shapeMenu.setNumberOfButtonsPerLevel(ORYX.CONFIG.SHAPEMENU_RIGHT, 2);
this.createdButtons = {};
this.createMorphMenu();
if( !this.pluginsData ){
this.pluginsData = [];
}
this.baseMorphStencils = this.facade.getRules().baseMorphs();
// Checks if the stencil set has morphing attributes
var isMorphing = this.facade.getRules().containsMorphingRules();
// Create Buttons for all Stencils of all loaded stencilsets
var stencilsets = this.facade.getStencilSets();
stencilsets.values().each((function(stencilSet){
var nodes = stencilSet.nodes();
nodes.each((function(stencil) {
// Create a button for each node
var option = {type: stencil.id(), namespace: stencil.namespace(), connectingType: true};
var button = new ORYX.Plugins.ShapeMenuButton({
callback: this.newShape.bind(this, option),
icon: stencil.icon(),
align: ORYX.CONFIG.SHAPEMENU_RIGHT,
group: 0,
//dragcallback: this.hideShapeMenu.bind(this),
msg: stencil.title() + " - " + ORYX.I18N.ShapeMenuPlugin.clickDrag
});
// Add button to shape menu
this.shapeMenu.addButton(button);
// Add to the created Button Array
this.createdButtons[stencil.namespace() + stencil.type() + stencil.id()] = button;
// Drag'n'Drop will enable
Ext.dd.Registry.register(button.node.lastChild, option);
}).bind(this));
var edges = stencilSet.edges();
edges.each((function(stencil) {
// Create a button for each edge
var option = {type: stencil.id(), namespace: stencil.namespace()};
var button = new ORYX.Plugins.ShapeMenuButton({
callback: this.newShape.bind(this, option),
icon: stencil.icon(), // /* uml has morphing rules for all shapes, this makes them indistinguishable. */ isMorphing ? ORYX.PATH + "images/edges.png" : stencil.icon(),
align: ORYX.CONFIG.SHAPEMENU_RIGHT,
group: 1,
//dragcallback: this.hideShapeMenu.bind(this),
msg: (isMorphing ? ORYX.I18N.Edge : stencil.title()) + " - " + ORYX.I18N.ShapeMenuPlugin.drag
});
// Add button to shape menu
this.shapeMenu.addButton(button);
// Add to the created Button Array
this.createdButtons[stencil.namespace() + stencil.type() + stencil.id()] = button;
// Drag'n'Drop will enable
Ext.dd.Registry.register(button.node.lastChild, option);
}).bind(this));
}).bind(this));
},
createMorphMenu: function() {
this.morphMenu = new Ext.menu.Menu({
id: 'Oryx_morph_menu',
items: []
});
this.morphMenu.on("mouseover", function() {
this.morphMenuHovered = true;
}, this);
this.morphMenu.on("mouseout", function() {
this.morphMenuHovered = false;
}, this);
// Create the button to show the morph menu
var button = new ORYX.Plugins.ShapeMenuButton({
hovercallback: (ORYX.CONFIG.ENABLE_MORPHMENU_BY_HOVER ? this.showMorphMenu.bind(this) : undefined),
resetcallback: (ORYX.CONFIG.ENABLE_MORPHMENU_BY_HOVER ? this.hideMorphMenu.bind(this) : undefined),
callback: (ORYX.CONFIG.ENABLE_MORPHMENU_BY_HOVER ? undefined : this.toggleMorphMenu.bind(this)),
icon: ORYX.PATH + 'editor/images/wrench_orange.png',
align: ORYX.CONFIG.SHAPEMENU_BOTTOM,
group: 0,
msg: ORYX.I18N.ShapeMenuPlugin.morphMsg
});
this.shapeMenu.setNumberOfButtonsPerLevel(ORYX.CONFIG.SHAPEMENU_BOTTOM, 1)
this.shapeMenu.addButton(button);
this.morphMenu.getEl().appendTo(button.node);
this.morphButton = button;
},
showMorphMenu: function() {
this.morphMenu.show(this.morphButton.node);
this._morphMenuShown = true;
},
hideMorphMenu: function() {
this.morphMenu.hide();
this._morphMenuShown = false;
},
toggleMorphMenu: function() {
if(this._morphMenuShown)
this.hideMorphMenu();
else
this.showMorphMenu();
},
onSelectionChanged: function(event) {
// don't do this for remote commands
if (!event.isLocal)
return;
//var elements = event.elements;
var selection = this.facade.getSelection();
this.hideShapeMenu();
this.hideMorphMenu();
if (!selection.length > 0) {
return;
}
if (selection[0] instanceof ORYX.Core.Edge) {
return;
}
if (this.currentShapes.inspect() !== selection.inspect()) {
this.currentShapes = selection;
this.resetElements = true;
this.showShapeMenu();
} else {
this.showShapeMenu(true)
}
this.facade.updateSelection(false);
},
/**
* Show button for morphing the selected shape into another stencil
*/
showMorphButton: function(elements) {
if(elements.length != 1) return;
var possibleMorphs = this.facade.getRules().morphStencils({ stencil: elements[0].getStencil() });
possibleMorphs = possibleMorphs.select(function(morph) {
if(elements[0].getStencil().type() === "node") {
//check containment rules
return this.facade.getRules().canContain({containingShape:elements[0].parent, containedStencil:morph});
} else {
//check connect rules
return this.facade.getRules().canConnect({
sourceShape: elements[0].dockers.first().getDockedShape(),
edgeStencil: morph,
targetShape: elements[0].dockers.last().getDockedShape()
});
}
}.bind(this));
if(possibleMorphs.size()<=1) return; // if morphing to other stencils is not possible, don't show button
this.morphMenu.removeAll();
// populate morph menu with the possible morph stencils ordered by their position
possibleMorphs = possibleMorphs.sortBy(function(stencil) { return stencil.position(); });
possibleMorphs.each((function(morph) {
var menuItem = new Ext.menu.Item({
text: morph.title(),
icon: morph.icon(),
disabled: morph.id()==elements[0].getStencil().id(),
disabledClass: ORYX.CONFIG.MORPHITEM_DISABLED,
handler: (function() { this.morphShape(elements[0], morph); }).bind(this)
});
this.morphMenu.add(menuItem);
}).bind(this));
this.morphButton.prepareToShow();
},
/**
* Show buttons for creating following shapes
*/
showStencilButtons: function(elements) {
if(elements.length != 1) return;
//TODO temporaere nutzung des stencilsets
var sset = this.facade.getStencilSets()[elements[0].getStencil().namespace()];
// Get all available edges
var edges = this.facade.getRules().outgoingEdgeStencils({canvas:this.facade.getCanvas(), sourceShape:elements[0]});
// And find all targets for each Edge
var targets = new Array();
var addedEdges = new Array();
var isMorphing = this.facade.getRules().containsMorphingRules();
edges.each((function(edge) {
if (isMorphing){
if(this.baseMorphStencils.include(edge)) {
var shallAppear = true;
} else {
// if edge is member of a morph groups where none of the base morphs is in the outgoing edges
// we want to display the button (but only for the first one)
var possibleMorphs = this.facade.getRules().morphStencils({ stencil: edge });
var shallAppear = !possibleMorphs.any((function(morphStencil) {
if(this.baseMorphStencils.include(morphStencil) && edges.include(morphStencil)) return true;
return addedEdges.include(morphStencil);
}).bind(this));
}
}
if(shallAppear || !isMorphing) {
if(this.createdButtons[edge.namespace() + edge.type() + edge.id()])
this.createdButtons[edge.namespace() + edge.type() + edge.id()].prepareToShow();
addedEdges.push(edge);
}
// get all targets for this edge
targets = targets.concat(this.facade.getRules().targetStencils(
{canvas:this.facade.getCanvas(), sourceShape:elements[0], edgeStencil:edge}));
}).bind(this));
targets.uniq();
var addedTargets = new Array();
// Iterate all possible target
targets.each((function(target) {
if (isMorphing){
// continue with next target stencil
if (target.type()==="edge") return;
// continue when stencil should not shown in the shape menu
if (!this.facade.getRules().showInShapeMenu(target)) return
// if target is not a base morph
if(!this.baseMorphStencils.include(target)) {
// if target is member of a morph groups where none of the base morphs is in the targets
// we want to display the button (but only for the first one)
var possibleMorphs = this.facade.getRules().morphStencils({ stencil: target });
if(possibleMorphs.size()==0) return; // continue with next target
var baseMorphInTargets = possibleMorphs.any((function(morphStencil) {
if(this.baseMorphStencils.include(morphStencil) && targets.include(morphStencil)) return true;
return addedTargets.include(morphStencil);
}).bind(this));
if(baseMorphInTargets) return; // continue with next target
}
}
// if this is reached the button shall appear in the shape menu:
if(this.createdButtons[target.namespace() + target.type() + target.id()])
this.createdButtons[target.namespace() + target.type() + target.id()].prepareToShow();
addedTargets.push(target);
}).bind(this));
},
beforeDragOver: function(dragZone, target, event){
if (this.shapeMenu.isVisible){
this.hideShapeMenu();
}
var coord = this.facade.eventCoordinates(event.browserEvent);
var aShapes = this.facade.getCanvas().getAbstractShapesAtPosition(coord);
if(aShapes.length <= 0) {return false;}
var el = aShapes.last();
if(this._lastOverElement == el) {
return false;
} else {
// check containment rules
var option = Ext.dd.Registry.getHandle(target.DDM.currentTarget);
// revert to original options if these were modified
if(option.backupOptions) {
for(key in option.backupOptions) {
option[key] = option.backupOptions[key];
}
delete option.backupOptions;
}
var stencilSet = this.facade.getStencilSets()[option.namespace];
var stencil = stencilSet.stencil(option.type);
var candidate = aShapes.last();
if(stencil.type() === "node") {
//check containment rules
var canContain = this.facade.getRules().canContain({containingShape:candidate, containedStencil:stencil});
// if not canContain, try to find a morph which can be contained
if(!canContain) {
var possibleMorphs = this.facade.getRules().morphStencils({stencil: stencil});
for(var i=0; i<possibleMorphs.size(); i++) {
canContain = this.facade.getRules().canContain({
containingShape:candidate,
containedStencil:possibleMorphs[i]
});
if(canContain) {
option.backupOptions = Object.clone(option);
option.type = possibleMorphs[i].id();
option.namespace = possibleMorphs[i].namespace();
break;
}
}
}
this._currentReference = canContain ? candidate : undefined;
} else { //Edge
var curCan = candidate, orgCan = candidate;
var canConnect = false;
while(!canConnect && curCan && !(curCan instanceof ORYX.Core.Canvas)){
candidate = curCan;
//check connection rules
canConnect = this.facade.getRules().canConnect({
sourceShape: this.currentShapes.first(),
edgeStencil: stencil,
targetShape: curCan
});
curCan = curCan.parent;
}
// if not canConnect, try to find a morph which can be connected
if(!canConnect) {
candidate = orgCan;
var possibleMorphs = this.facade.getRules().morphStencils({stencil: stencil});
for(var i=0; i<possibleMorphs.size(); i++) {
var curCan = candidate;
var canConnect = false;
while(!canConnect && curCan && !(curCan instanceof ORYX.Core.Canvas)){
candidate = curCan;
//check connection rules
canConnect = this.facade.getRules().canConnect({
sourceShape: this.currentShapes.first(),
edgeStencil: possibleMorphs[i],
targetShape: curCan
});
curCan = curCan.parent;
}
if(canConnect) {
option.backupOptions = Object.clone(option);
option.type = possibleMorphs[i].id();
option.namespace = possibleMorphs[i].namespace();
break;
} else {
candidate = orgCan;
}
}
}
this._currentReference = canConnect ? candidate : undefined;
}
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_HIGHLIGHT_SHOW,
highlightId:'shapeMenu',
elements: [candidate],
color: this._currentReference ? ORYX.CONFIG.SELECTION_VALID_COLOR : ORYX.CONFIG.SELECTION_INVALID_COLOR
});
var pr = dragZone.getProxy();
pr.setStatus(this._currentReference ? pr.dropAllowed : pr.dropNotAllowed );
pr.sync();
}
this._lastOverElement = el;
return false;
},
afterDragging: function(dragZone, target, event) {
if (!(this.currentShapes instanceof Array)||this.currentShapes.length<=0) {
return;
}
var sourceShape = this.currentShapes;
this._lastOverElement = undefined;
// Hide the highlighting
this.facade.raiseEvent({type: ORYX.CONFIG.EVENT_HIGHLIGHT_HIDE, highlightId:'shapeMenu'});
// Check if drop is allowed
var proxy = dragZone.getProxy()
if(proxy.dropStatus == proxy.dropNotAllowed) { return this.facade.updateSelection(true);}
// Check if there is a current Parent
if(!this._currentReference) { return }
var option = Ext.dd.Registry.getHandle(target.DDM.currentTarget);
option['parent'] = this._currentReference;
var xy = event.getXY();
var pos = {x: xy[0], y: xy[1]};
var a = this.facade.getCanvas().node.getScreenCTM();
// Correcting the UpperLeft-Offset
pos.x -= a.e; pos.y -= a.f;
// Correcting the Zoom-Faktor
pos.x /= a.a; pos.y /= a.d;
// Correcting the ScrollOffset
pos.x -= document.documentElement.scrollLeft;
pos.y -= document.documentElement.scrollTop;
var parentAbs = this._currentReference.absoluteXY();
pos.x -= parentAbs.x;
pos.y -= parentAbs.y;
// If the ctrl key is not pressed,
// snapp the new shape to the center
// if it is near to the center of the other shape
if (!event.ctrlKey){
// Get the center of the shape
var cShape = this.currentShapes[0].bounds.center();
// Snapp +-20 Pixel horizontal to the center
if (20 > Math.abs(cShape.x - pos.x)){
pos.x = cShape.x;
}
// Snapp +-20 Pixel vertical to the center
if (20 > Math.abs(cShape.y - pos.y)){
pos.y = cShape.y;
}
}
option['position'] = pos;
option['connectedShape'] = this.currentShapes[0];
if(option['connectingType']) {
var stencilset = this.facade.getStencilSets()[option.namespace];
var containedStencil = stencilset.stencil(option.type);
var args = { sourceShape: this.currentShapes[0], targetStencil: containedStencil };
option['connectingType'] = this.facade.getRules().connectMorph(args).id();
}
if (ORYX.CONFIG.SHAPEMENU_DISABLE_CONNECTED_EDGE===true) {
delete option['connectingType'];
}
var command = new ORYX.Core.Commands["ShapeMenu.CreateCommand"](Object.clone(option), this._currentReference, pos, this.facade);
this.facade.executeCommands([command]);
// Inform about completed Drag
this.facade.raiseEvent({type: ORYX.CONFIG.EVENT_SHAPE_MENU_CLOSE, source:sourceShape, destination:this.currentShapes});
// revert to original options if these were modified
if(option.backupOptions) {
for(key in option.backupOptions) {
option[key] = option.backupOptions[key];
}
delete option.backupOptions;
}
this._currentReference = undefined;
},
newShape: function(option, event) {
var stencilset = this.facade.getStencilSets()[option.namespace];
var containedStencil = stencilset.stencil(option.type);
if(this.facade.getRules().canContain({
containingShape:this.currentShapes.first().parent,
"containedStencil":containedStencil
})) {
option['connectedShape'] = this.currentShapes[0];
option['parent'] = this.currentShapes.first().parent;
option['containedStencil'] = containedStencil;
var args = { sourceShape: this.currentShapes[0], targetStencil: containedStencil };
var targetStencil = this.facade.getRules().connectMorph(args);
if (!targetStencil){ return }// Check if there can be a target shape
option['connectingType'] = targetStencil.id();
if (ORYX.CONFIG.SHAPEMENU_DISABLE_CONNECTED_EDGE===true) {
delete option['connectingType'];
}
var command = new ORYX.Core.Commands["ShapeMenu.CreateCommand"](option, undefined, undefined, this.facade);
this.facade.executeCommands([command]);
}
},
/**
* Morph a shape to a new stencil
* @param {Shape} shape
* @param {Stencil} stencil
*/
morphShape: function(shape, stencil) {
var command = new ORYX.Core.Commands["ShapeMenu.MorphCommand"](shape, stencil, this.facade);
this.facade.executeCommands([command]);
}
}
ORYX.Plugins.ShapeMenuPlugin = ORYX.Plugins.AbstractPlugin.extend(ORYX.Plugins.ShapeMenuPlugin);
ORYX.Plugins.ShapeMenu = {
/***
* Constructor.
*/
construct: function(parentNode) {
this.bounds = undefined;
this.shapes = undefined;
this.buttons = [];
this.isVisible = false;
this.node = ORYX.Editor.graft("http://www.w3.org/1999/xhtml", $(parentNode),
['div', {id: ORYX.Editor.provideId(), 'class':'Oryx_ShapeMenu'}]);
this.alignContainers = new Hash();
this.numberOfButtonsPerLevel = new Hash();
},
addButton: function(button) {
this.buttons.push(button);
// lazy grafting of the align containers
if(!this.alignContainers[button.align]) {
this.alignContainers[button.align] = ORYX.Editor.graft("http://www.w3.org/1999/xhtml", this.node,
['div', {'class':button.align}]);
this.node.appendChild(this.alignContainers[button.align]);
// add event listeners for hover effect
var onBubble = false;
this.alignContainers[button.align].addEventListener(ORYX.CONFIG.EVENT_MOUSEOVER, this.hoverAlignContainer.bind(this, button.align), onBubble);
this.alignContainers[button.align].addEventListener(ORYX.CONFIG.EVENT_MOUSEOUT, this.resetAlignContainer.bind(this, button.align), onBubble);
this.alignContainers[button.align].addEventListener(ORYX.CONFIG.EVENT_MOUSEUP, this.hoverAlignContainer.bind(this, button.align), onBubble);
}
this.alignContainers[button.align].appendChild(button.node);
},
deleteButton: function(button) {
this.buttons = this.buttons.without(button);
this.node.removeChild(button.node);
},
removeAllButtons: function() {
var me = this;
this.buttons.each(function(value){
if (value.node&&value.node.parentNode)
value.node.parentNode.removeChild(value.node);
});
this.buttons = [];
},
closeAllButtons: function() {
this.buttons.each(function(value){ value.prepareToHide() });
this.isVisible = false;
},
/**
* Show the shape menu
*/
show: function(shapes) {
//shapes = (shapes||[]).findAll(function(r){ return r && r.node && r.node.parent });
if(shapes.length <= 0 )
return
this.shapes = shapes;
var newBounds = undefined;
var tmpBounds = undefined;
this.shapes.each(function(value) {
var a = value.node.getScreenCTM();
var upL = value.absoluteXY();
a.e = a.a*upL.x;
a.f = a.d*upL.y;
tmpBounds = new ORYX.Core.Bounds(a.e, a.f, a.e+a.a*value.bounds.width(), a.f+a.d*value.bounds.height());
/*if(value instanceof ORYX.Core.Edge) {
tmpBounds.moveBy(value.bounds.upperLeft())
}*/
if(!newBounds)
newBounds = tmpBounds
else
newBounds.include(tmpBounds);
});
this.bounds = newBounds;
//this.bounds.moveBy({x:document.documentElement.scrollLeft, y:document.documentElement.scrollTop});
var bounds = this.bounds;
var a = this.bounds.upperLeft();
var left = 0,
leftButtonGroup = 0;
var top = 0,
topButtonGroup = 0;
var bottom = 0,
bottomButtonGroup;
var right = 0
rightButtonGroup = 0;
var size = 22;
this.getWillShowButtons().sortBy(function(button) {
return button.group;
});
this.getWillShowButtons().each(function(button){
var numOfButtonsPerLevel = this.getNumberOfButtonsPerLevel(button.align);
if (button.align == ORYX.CONFIG.SHAPEMENU_LEFT) {
// vertical levels
if(button.group!=leftButtonGroup) {
left = 0;
leftButtonGroup = button.group;
}
var x = Math.floor(left / numOfButtonsPerLevel);
var y = left % numOfButtonsPerLevel;
button.setLevel(x);
button.setPosition(a.x-5 - (x+1)*size,
a.y+numOfButtonsPerLevel*button.group*size + button.group*0.3*size + y*size);
//button.setPosition(a.x-22, a.y+left*size);
left++;
} else if (button.align == ORYX.CONFIG.SHAPEMENU_TOP) {
// horizontal levels
if(button.group!=topButtonGroup) {
top = 0;
topButtonGroup = button.group;
}
var x = top % numOfButtonsPerLevel;
var y = Math.floor(top / numOfButtonsPerLevel);
button.setLevel(y);
button.setPosition(a.x+numOfButtonsPerLevel*button.group*size + button.group*0.3*size + x*size,
a.y-5 - (y+1)*size);
top++;
} else if (button.align == ORYX.CONFIG.SHAPEMENU_BOTTOM) {
// horizontal levels
if(button.group!=bottomButtonGroup) {
bottom = 0;
bottomButtonGroup = button.group;
}
var x = bottom % numOfButtonsPerLevel;
var y = Math.floor(bottom / numOfButtonsPerLevel);
button.setLevel(y);
button.setPosition(a.x+numOfButtonsPerLevel*button.group*size + button.group*0.3*size + x*size,
a.y+bounds.height() + 5 + y*size);
bottom++;
} else {
// vertical levels
if(button.group!=rightButtonGroup) {
right = 0;
rightButtonGroup = button.group;
}
var x = Math.floor(right / numOfButtonsPerLevel)
var y = right % numOfButtonsPerLevel;
button.setLevel(x);
button.setPosition(a.x+bounds.width() + 5 + x*size,
a.y+numOfButtonsPerLevel*button.group*size + button.group*0.3*size + y*size - 5);
right++;
}
button.show();
}.bind(this));
this.isVisible = true;
},
/**
* Hide the shape menu
*/
hide: function() {
this.buttons.each(function(button){
button.hide();
});
this.isVisible = false;
//this.bounds = undefined;
//this.shape = undefined;
},
hoverAlignContainer: function(align, evt) {
this.buttons.each(function(button){
if(button.align == align) button.showOpaque();
});
},
resetAlignContainer: function(align, evt) {
this.buttons.each(function(button){
if(button.align == align) button.showTransparent();
});
},
isHover: function() {
return this.buttons.any(function(value){
return value.isHover();
});
},
getWillShowButtons: function() {
return this.buttons.findAll(function(value){return value.willShow});
},
/**
* Returns a set on buttons for that align value
* @params {String} align
* @params {String} group
*/
getButtons: function(align, group){
return this.getWillShowButtons().findAll(function(b){ return b.align == align && (group === undefined || b.group == group)})
},
/**
* Set the number of buttons to display on each level of the shape menu in the specified align group.
* Example: setNumberOfButtonsPerLevel(ORYX.CONFIG.SHAPEMENU_RIGHT, 2) causes that the buttons of the right align group
* will be rendered in 2 rows.
*/
setNumberOfButtonsPerLevel: function(align, number) {
this.numberOfButtonsPerLevel[align] = number;
},
/**
* Returns the number of buttons to display on each level of the shape menu in the specified align group.
* Default value is 1
*/
getNumberOfButtonsPerLevel: function(align) {
if(this.numberOfButtonsPerLevel[align])
return Math.min(this.getButtons(align,0).length, this.numberOfButtonsPerLevel[align]);
else
return 1;
}
}
ORYX.Plugins.ShapeMenu = Clazz.extend(ORYX.Plugins.ShapeMenu);
ORYX.Plugins.ShapeMenuButton = {
/**
* Constructor
* @param option A key map specifying the configuration options:
* id: (String) The id of the parent DOM element for the new button
* icon: (String) The url to the icon of the button
* msg: (String) A tooltip message
* caption:(String) The caption of the button (attention: button width > 22, only set for single column button layouts)
* align: (String) The direction in which the button is aligned
* group: (Integer) The button group in the specified alignment
* (buttons in the same group will be aligned side by side)
* callback: (Function) A callback that is executed when the button is clicked
* dragcallback: (Function) A callback that is executed when the button is dragged
* hovercallback: (Function) A callback that is executed when the button is hovered
* resetcallback: (Function) A callback that is executed when the button is reset
* arguments: (Array) An argument array to pass to the callback functions
*/
construct: function(option) {
if(option) {
this.option = option;
if(!this.option.arguments)
this.option.arguments = [];
} else {
//TODO error
}
this.parentId = this.option.id ? this.option.id : null;
// graft the button.
var buttonClassName = this.option.caption ? "Oryx_button_with_caption" : "Oryx_button";
this.node = ORYX.Editor.graft("http://www.w3.org/1999/xhtml", $(this.parentId),
['div', {'class':buttonClassName}]);
var imgOptions = {src:this.option.icon};
if(this.option.msg){
imgOptions.title = this.option.msg;
}
// graft and update icon (not in grafting for ns reasons).
//TODO Enrich graft()-function to do this in one of the above steps.
if(this.option.icon)
ORYX.Editor.graft("http://www.w3.org/1999/xhtml", this.node,
['img', imgOptions]);
if(this.option.caption) {
var captionNode = ORYX.Editor.graft("http://www.w3.org/1999/xhtml", this.node, ['span']);
ORYX.Editor.graft("http://www.w3.org/1999/xhtml", captionNode, this.option.caption);
}
var onBubble = false;
this.node.addEventListener(ORYX.CONFIG.EVENT_MOUSEOVER, this.hover.bind(this), onBubble);
this.node.addEventListener(ORYX.CONFIG.EVENT_MOUSEOUT, this.reset.bind(this), onBubble);
this.node.addEventListener(ORYX.CONFIG.EVENT_MOUSEDOWN, this.activate.bind(this), onBubble);
this.node.addEventListener(ORYX.CONFIG.EVENT_MOUSEUP, this.hover.bind(this), onBubble);
this.node.addEventListener('click', this.trigger.bind(this), onBubble);
this.node.addEventListener(ORYX.CONFIG.EVENT_MOUSEMOVE, this.move.bind(this), onBubble);
this.align = this.option.align ? this.option.align : ORYX.CONFIG.SHAPEMENU_RIGHT;
this.group = this.option.group ? this.option.group : 0;
this.hide();
this.dragStart = false;
this.isVisible = false;
this.willShow = false;
this.resetTimer;
},
hide: function() {
this.node.style.display = "none";
this.isVisible = false;
},
show: function() {
this.node.style.display = "";
this.node.style.opacity = this.opacity;
this.isVisible = true;
},
showOpaque: function() {
this.node.style.opacity = 1.0;
},
showTransparent: function() {
this.node.style.opacity = this.opacity;
},
prepareToShow: function() {
this.willShow = true;
},
prepareToHide: function() {
this.willShow = false;
this.hide();
},
setPosition: function(x, y) {
this.node.style.left = x + "px";
this.node.style.top = y + "px";
},
setLevel: function(level) {
if(level==0) this.opacity = 0.5;
else if(level==1) this.opacity = 0.2;
//else if(level==2) this.opacity = 0.1;
else this.opacity = 0.0;
},
setChildWidth: function(width) {
this.childNode.style.width = width + "px";
},
reset: function(evt) {
// Delete the timeout for hiding
window.clearTimeout( this.resetTimer )
this.resetTimer = window.setTimeout( this.doReset.bind(this), 100)
if(this.option.resetcallback) {
this.option.arguments.push(evt);
var state = this.option.resetcallback.apply(this, this.option.arguments);
this.option.arguments.remove(evt);
}
},
doReset: function() {
if(this.node.hasClassName('Oryx_down'))
this.node.removeClassName('Oryx_down');
if(this.node.hasClassName('Oryx_hover'))
this.node.removeClassName('Oryx_hover');
},
activate: function(evt) {
this.node.addClassName('Oryx_down');
//Event.stop(evt);
this.dragStart = true;
},
isHover: function() {
return this.node.hasClassName('Oryx_hover') ? true: false;
},
hover: function(evt) {
// Delete the timeout for hiding
window.clearTimeout( this.resetTimer )
this.resetTimer = null;
this.node.addClassName('Oryx_hover');
this.dragStart = false;
if(this.option.hovercallback) {
this.option.arguments.push(evt);
var state = this.option.hovercallback.apply(this, this.option.arguments);
this.option.arguments.remove(evt);
}
},
move: function(evt) {
if(this.dragStart && this.option.dragcallback) {
this.option.arguments.push(evt);
var state = this.option.dragcallback.apply(this, this.option.arguments);
this.option.arguments.remove(evt);
}
},
trigger: function(evt) {
if(this.option.callback) {
//Event.stop(evt);
this.option.arguments.push(evt);
var state = this.option.callback.apply(this, this.option.arguments);
this.option.arguments.remove(evt);
}
this.dragStart = false;
},
toString: function() {
return "HTML-Button " + this.id;
}
}
ORYX.Plugins.ShapeMenuButton = Clazz.extend(ORYX.Plugins.ShapeMenuButton);
//create command for undo/redo
ORYX.Core.Commands["ShapeMenu.CreateCommand"] = ORYX.Core.AbstractCommand.extend({
construct: function construct(option, currentReference, position, facade) {
arguments.callee.$.construct.call(this, facade);
this.connectedShape = option.connectedShape;
this.connectingType = option.connectingType;
this.namespace = option.namespace;
this.type = option.type;
this.containedStencil = option.containedStencil;
this.parent = option.parent;
this.currentReference = currentReference;
this.position = position;
this.shape;
this.edge;
this.targetRefPos;
this.sourceRefPos;
this.shapeOptions = option.shapeOptions;
this.option = option;
},
getCommandData: function getCommandData() {
var cmd = {
"option": {
"shapeOptions" : {
"id": this.shape["id"],
"resourceId": this.shape["resourceId"]
},
"type": this.type,
"namespace": this.namespace,
// connectingType is a stencil id
"connectedShape": this.connectedShape.resourceId,
"connectingType": this.connectingType,
"parent": this.parent.resourceId
}
}
if (typeof this.currentReference !== "undefined") {
cmd["currentReference"] = this.currentReference["resourceId"];
}
if (typeof this.position !== "undefined") {
cmd["position"] = this.position;
}
return cmd;
},
createFromCommandData: function createFromCommandData(facade, commandData) {
var option = commandData["option"];
var currentReference = undefined;
var position = undefined;
var stencilset = facade.getStencilSets()[option["namespace"]];
option["parent"] = facade.getCanvas().getChildShapeOrCanvasByResourceId(option["parent"]);
option["connectedShape"] = facade.getCanvas().getChildShapeByResourceId(option["connectedShape"]);
option["containedStencil"] = stencilset.stencil(option["type"]);
if (typeof commandData["currentReference"] !== "undefined") {
currentReference = facade.getCanvas().getChildShapeOrCanvasByResourceId(commandData["currentReference"]);
}
if (typeof commandData["position"] !== "undefined") {
position = commandData["position"];
option["position"] = position;
}
return new ORYX.Core.Commands["ShapeMenu.CreateCommand"](option, currentReference, position, facade);
},
getCommandName: function getCommandName() {
return "ShapeMenu.CreateCommand";
},
getDisplayName: function getDisplayName() {
return "Shape created";
},
getAffectedShapes: function getAffectedShapes() {
// this does not work before the shape is executed as it is a CreateCommand
var shapes = [this.shape];
if (this.shape instanceof ORYX.Core.Node) {
if (this.edge instanceof ORYX.Core.Edge) {
shapes.push(this.edge);
} else if (this.shape.getIncomingShapes().first()) {
shapes.push(this.shape.getIncomingShapes().first());
}
}
return shapes;
},
execute: function execute() {
var resume = false;
if (typeof this.shape !== 'undefined') {
if (this.shape instanceof ORYX.Core.Node) {
this.parent.add(this.shape);
if (typeof this.edge !== 'undefined') {
this.facade.getCanvas().add(this.edge);
this.edge.dockers.first().setDockedShape(this.connectedShape);
this.edge.dockers.first().bounds.centerMoveTo(this.connectedShape.absoluteBounds().center());
this.edge.dockers.first().setReferencePoint(this.sourceRefPos);
this.edge.dockers.first().update();
this.edge.dockers.first().parent._update();
this.edge.dockers.last().bounds.centerMoveTo(this.shape.absoluteBounds().center());
this.edge.dockers.last().setDockedShape(this.shape);
this.edge.dockers.last().setReferencePoint(this.targetRefPos);
this.edge.dockers.last().update();
this.edge._update();
}
if (this.isLocal()) {
this.facade.setSelection([this.shape]);
}
} else if (this.shape instanceof ORYX.Core.Edge) {
this.facade.getCanvas().add(this.shape);
this.shape.dockers.first().setDockedShape(this.connectedShape);
this.shape.dockers.first().setReferencePoint(this.sourceRefPos);
this.shape.dockers.first().update();
this.shape._update();
}
resume = true;
} else {
this.shape = this.facade.createShape(this.option);
this.edge = (!(this.shape instanceof ORYX.Core.Edge)) ? this.shape.getIncomingShapes().first() : undefined;
}
if ((typeof this.currentReference !== 'undefined') && (typeof this.position !== 'undefined')) {
if (this.shape instanceof ORYX.Core.Edge) {
if (!(this.currentReference instanceof ORYX.Core.Canvas)) {
this.shape.dockers.last().setDockedShape(this.currentReference);
this.shape.dockers.last().setReferencePoint(this.currentReference.absoluteBounds().midPoint());
}
else {
this.shape.dockers.last().bounds.centerMoveTo(this.position);
}
this.sourceRefPos = this.shape.dockers.first().referencePoint;
this.targetRefPos = this.shape.dockers.last().referencePoint;
this.shape.dockers.last().update();
this.shape.dockers.last().parent._update();
} else if (typeof this.edge !== 'undefined'){
this.sourceRefPos = this.edge.dockers.first().referencePoint;
this.targetRefPos = this.edge.dockers.last().referencePoint;
}
} else if (typeof this.position !== 'undefined') {
if (typeof this.shape.dockers.last() !== 'undefined') {
this.shape.dockers.last().setDockedShape(this.currentReference);
}
this.shape.bounds.centerMoveTo(this.position);
if (this.shape instanceof ORYX.Core.Node){
(this.shape.dockers||[]).each(function(docker){
docker.bounds.centerMoveTo(this.position);
}.bind(this));
}
if (typeof this.edge !== 'undefined'){
this.edge.dockers.first().bounds.centerMoveTo(this.connectedShape.absoluteBounds().center());
this.edge.dockers.first().setDockedShape(this.connectedShape);
this.edge.dockers.first().update();
this.edge._update();
this.edge.dockers.last().bounds.centerMoveTo(this.shape.absoluteBounds().center());
this.edge.dockers.last().setDockedShape(this.shape);
this.edge.dockers.last().update();
this.edge._update();
if ((typeof this.sourceRefPos !== 'undefined') && (typeof this.targetRefPos !== 'undefined')) {
this.edge.dockers.first().setReferencePoint(this.sourceRefPos);
this.edge.dockers.last().setReferencePoint(this.targetRefPos);
} else {
this.sourceRefPos = this.edge.dockers.first().referencePoint;
this.targetRefPos = this.edge.dockers.last().referencePoint;
}
}
} else {
var containedStencil = this.containedStencil;
var connectedShape = this.connectedShape;
var bc = connectedShape.bounds;
var bs = this.shape.bounds;
var pos = bc.center();
pos.y = this.connectedShape.bounds.center().y;
// for some reason, uml complex classes fail to be positioned, although the center.y is copied it turns out to be 5 pixels to high
if (this.containedStencil._jsonStencil.id === "http://b3mn.org/stencilset/UML2.2Class#ComplexClass") {
pos.y = pos.y + 5;
}
if(containedStencil.defaultAlign()==="north") {
pos.y -= (bc.height() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET + (bs.height()/2);
} else if(containedStencil.defaultAlign()==="northeast") {
pos.x += (bc.width() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET_CORNER + (bs.width()/2);
pos.y -= (bc.height() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET_CORNER + (bs.height()/2);
} else if(containedStencil.defaultAlign()==="southeast") {
pos.x += (bc.width() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET_CORNER + (bs.width()/2);
pos.y += (bc.height() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET_CORNER + (bs.height()/2);
} else if(containedStencil.defaultAlign()==="south") {
pos.y += (bc.height() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET + (bs.height()/2);
} else if(containedStencil.defaultAlign()==="southwest") {
pos.x -= (bc.width() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET_CORNER + (bs.width()/2);
pos.y += (bc.height() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET_CORNER + (bs.height()/2);
} else if(containedStencil.defaultAlign()==="west") {
pos.x -= (bc.width() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET + (bs.width()/2);
} else if(containedStencil.defaultAlign()==="northwest") {
pos.x -= (bc.width() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET_CORNER + (bs.width()/2);
pos.y -= (bc.height() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET_CORNER + (bs.height()/2);
} else {
pos.x += (bc.width() / 2) + ORYX.CONFIG.SHAPEMENU_CREATE_OFFSET + (bs.width()/2);
}
// Move shape to the new position
this.shape.bounds.centerMoveTo(pos);
// Move all dockers of a node to the position
if (this.shape instanceof ORYX.Core.Node){
(this.shape.dockers||[]).each(function(docker){
docker.bounds.centerMoveTo(pos);
})
}
//this.shape.update();
this.position = pos;
if (typeof this.edge !== 'undefined'){
this.sourceRefPos = this.edge.dockers.first().referencePoint;
this.targetRefPos = this.edge.dockers.last().referencePoint;
}
}
this.facade.getCanvas().update();
this.facade.updateSelection(this.isLocal());
// Try to layout the edge that has been created
/*if (!resume) {
var event = {
'type': ORYX.CONFIG.EVENT_LAYOUT
};
if (typeof this.edge !== 'undefined') {
event.shapes = [this.edge];
} else if (this.shape instanceof ORYX.Core.Edge) {
event.shapes = [this.shape];
}
this.facade.raiseEvent(event);
}*/
},
rollback: function rollback() {
// If syncro tells us to revert a command, we have to pick necessary references ourselves.
if (typeof this.shape === 'undefined') {
this.shape = this.facade.getCanvas().getChildShapeByResourceId(this.shapeOptions.resourceId);
// createShape() by convention creates the connecting edge with "<shape>_edge" as its resource id:
this.edge = this.facade.getCanvas().getChildShapeByResourceId(this.shapeOptions.resourceId + "_edge");
if (typeof this.shape === 'undefined' || typeof this.shape === 'ORYX.Core.Node' && typeof this.edge === 'undefined' ) {
throw "Could not revert ShapeMenu.CreateCommand. this.shape or this.edge is undefined.";
}
}
this.facade.deleteShape(this.shape);
this.facade.raiseEvent(
{
"type": ORYX.CONFIG.EVENT_SHAPEDELETED,
"shape": this.shape
}
);
var deletedShapes = [this.shape];
var selectedShapes = this.facade.getSelection();
var newSelectedShapes = selectedShapes.without(this.shape);
if (typeof this.edge !== 'undefined') {
this.facade.deleteShape(this.edge);
this.facade.raiseEvent(
{
"type": ORYX.CONFIG.EVENT_SHAPEDELETED,
"shape": this.shape
}
);
var newSelectedShapes = newSelectedShapes.without(this.edge);
deletedShapes.push(this.edge);
}
this.facade.getCanvas().update();
if (this.isLocal()) {
this.facade.setSelection(newSelectedShapes);
} else {
var isDragging = this.facade.isDragging();
if (!isDragging) {
this.facade.setSelection(newSelectedShapes);
} else {
//raise event, which assures, that selection and canvas will be updated after dragging is finished
this.facade.raiseEvent(
{
"type": ORYX.CONFIG.EVENT_SHAPESTODELETE,
"deletedShapes": deletedShapes
}
);
}
}
this.facade.getCanvas().update();
if (this.isLocal()) {
this.facade.setSelection(newSelectedShapes);
} else {
var isDragging = this.facade.isDragging();
if (!isDragging) {
this.facade.setSelection(newSelectedShapes);
} else {
//raise event, which assures, that selection and canvas will be updated after dragging is finished
this.facade.raiseEvent(
{
"type": ORYX.CONFIG.EVENT_SHAPESTODELETE,
"deletedShapes": deletedShapes
}
);
}
}
this.facade.updateSelection(this.isLocal());
}
});
ORYX.Core.Commands["ShapeMenu.MorphCommand"] = ORYX.Core.AbstractCommand.extend({
construct: function(shape, stencil, facade){
arguments.callee.$.construct.call(this, facade);
this.shape = shape;
this.stencil = stencil;
this.facade = facade;
this.newShape;
},
getCommandData: function getCommandData() {
var cmd = {
"option": {
"shapeOptions" : {
"resourceId": this.shape["resourceId"]
},
"stencilId": this.stencil.id(),
"stencilNamespace": this.stencil.namespace()
}
};
return cmd;
},
createFromCommandData: function createFromCommandData(facade, commandData) {
var option = commandData["option"];
var shapeOptions = option.shapeOptions;
var shape = facade.getCanvas().getChildShapeByResourceId(shapeOptions.resourceId);
// Checking if the shape doesn't exist anymore (i.e. has been deleted remotely), then don't instantiate a conmmand.
if (typeof shape === 'undefined') {
return undefined;
}
var stencilSet = facade.getStencilSets()[option.stencilNamespace];
var stencil = stencilSet.stencil(option.stencilId);
return new ORYX.Core.Commands["ShapeMenu.MorphCommand"](shape, stencil, facade);
},
getCommandName: function getCommandName() {
return "ShapeMenu.MorphCommand";
},
getDisplayName: function getDisplayName() {
return "Shape morphed";
},
getAffectedShapes: function getAffectedShapes() {
return [this.newShape];
},
execute: function(){
var shape = this.shape;
var stencil = this.stencil;
var resourceId = shape.resourceId;
var id = shape.id;
// Serialize all attributes
var serialized = shape.serialize();
stencil.properties().each((function(prop) {
if(prop.readonly()) {
serialized = serialized.reject(function(serProp) {
return serProp.name==prop.id();
});
}
}).bind(this));
// Get shape if already created, otherwise create a new shape
if (this.newShape){
newShape = this.newShape;
this.facade.getCanvas().add(newShape);
} else {
newShape = this.facade.createShape({
"type": stencil.id(),
"namespace": stencil.namespace(),
"resourceId": resourceId,
"shapeOptions": {
"resourceId": resourceId,
"id": id
}
});
}
// calculate new bounds using old shape's upperLeft and new shape's width/height
var boundsObj = serialized.find(function(serProp){
return (serProp.prefix === "oryx" && serProp.name === "bounds");
});
var changedBounds = null;
if(!this.facade.getRules().preserveBounds(shape.getStencil())) {
var bounds = boundsObj.value.split(",");
if (parseInt(bounds[0], 10) > parseInt(bounds[2], 10)) { // if lowerRight comes first, swap array items
var tmp = bounds[0];
bounds[0] = bounds[2];
bounds[2] = tmp;
tmp = bounds[1];
bounds[1] = bounds[3];
bounds[3] = tmp;
}
bounds[2] = parseInt(bounds[0], 10) + newShape.bounds.width();
bounds[3] = parseInt(bounds[1], 10) + newShape.bounds.height();
boundsObj.value = bounds.join(",");
} else {
var height = shape.bounds.height();
var width = shape.bounds.width();
// consider the minimum and maximum size of
// the new shape
if (newShape.minimumSize) {
if (shape.bounds.height() < newShape.minimumSize.height) {
height = newShape.minimumSize.height;
}
if (shape.bounds.width() < newShape.minimumSize.width) {
width = newShape.minimumSize.width;
}
}
if(newShape.maximumSize) {
if(shape.bounds.height() > newShape.maximumSize.height) {
height = newShape.maximumSize.height;
}
if(shape.bounds.width() > newShape.maximumSize.width) {
width = newShape.maximumSize.width;
}
}
changedBounds = {
a : {
x: shape.bounds.a.x,
y: shape.bounds.a.y
},
b : {
x: shape.bounds.a.x + width,
y: shape.bounds.a.y + height
}
};
}
var oPos = shape.bounds.center();
if(changedBounds !== null) {
newShape.bounds.set(changedBounds);
}
// Set all related dockers
this.setRelatedDockers(shape, newShape);
// store DOM position of old shape
var parentNode = shape.node.parentNode;
var nextSibling = shape.node.nextSibling;
// Delete the old shape
this.facade.deleteShape(shape);
// Deserialize the new shape - Set all attributes
newShape.deserialize(serialized);
if(changedBounds !== null) {
newShape.bounds.set(changedBounds);
}
// for some reason, uml complex classes fail to be positioned, although the center.y is copied it turns out to be 5 pixels to high
if (stencil._jsonStencil.id === "http://b3mn.org/stencilset/UML2.2Class#ComplexClass") {
oPos.y = oPos.y + 5;
}
if(newShape.getStencil().type()==="edge" || (newShape.dockers.length==0 || !newShape.dockers[0].getDockedShape())) {
newShape.bounds.centerMoveTo(oPos);
}
if(newShape.getStencil().type()==="node" && (newShape.dockers.length==0 || !newShape.dockers[0].getDockedShape())) {
this.setRelatedDockers(newShape, newShape);
}
// place at the DOM position of the old shape
if(nextSibling) parentNode.insertBefore(newShape.node, nextSibling);
else parentNode.appendChild(newShape.node);
// Set selection
if (this.isLocal() ) {
this.facade.setSelection([newShape]);
} else if (this.facade.getSelection().include(this.shape)) {
this.facade.setSelection(this.facade.getSelection().without(shape).concat(newShape));
}
this.facade.getCanvas().update();
this.facade.updateSelection(this.isLocal());
this.newShape = newShape;
},
rollback: function(){
if (!this.shape || !this.newShape || !this.newShape.parent) {return}
// Append shape to the parent
this.newShape.parent.add(this.shape);
// Set dockers
this.setRelatedDockers(this.newShape, this.shape);
// Delete new shape
this.facade.deleteShape(this.newShape);
// Set selection
if (this.isLocal()) {
this.facade.setSelection([this.shape]);
} else if (this.facade.getSelection().include(this.newShape)){
this.facade.setSelection(this.facade.getSelection().without(this.newShape).concat(this.shape));
}
// Update
this.facade.getCanvas().update();
this.facade.updateSelection(this.isLocal());
},
/**
* Set all incoming and outgoing edges from the shape to the new shape
* @param {Shape} shape
* @param {Shape} newShape
*/
setRelatedDockers: function(shape, newShape){
if(shape.getStencil().type()==="node") {
(shape.incoming||[]).concat(shape.outgoing||[])
.each(function(i) {
i.dockers.each(function(docker) {
if (docker.getDockedShape() == shape) {
var rPoint = Object.clone(docker.referencePoint);
// Move reference point per percent
var rPointNew = {
x: rPoint.x*newShape.bounds.width()/shape.bounds.width(),
y: rPoint.y*newShape.bounds.height()/shape.bounds.height()
};
docker.setDockedShape(newShape);
// Set reference point and center to new position
docker.setReferencePoint(rPointNew);
if(i instanceof ORYX.Core.Edge) {
docker.bounds.centerMoveTo(rPointNew);
} else {
var absXY = shape.absoluteXY();
docker.bounds.centerMoveTo({x:rPointNew.x+absXY.x, y:rPointNew.y+absXY.y});
//docker.bounds.moveBy({x:rPointNew.x-rPoint.x, y:rPointNew.y-rPoint.y});
}
}
});
});
// for attached events
if(shape.dockers.length>0&&shape.dockers.first().getDockedShape()) {
newShape.dockers.first().setDockedShape(shape.dockers.first().getDockedShape());
newShape.dockers.first().setReferencePoint(Object.clone(shape.dockers.first().referencePoint));
}
} else { // is edge
newShape.dockers.first().setDockedShape(shape.dockers.first().getDockedShape());
newShape.dockers.first().setReferencePoint(shape.dockers.first().referencePoint);
newShape.dockers.last().setDockedShape(shape.dockers.last().getDockedShape());
newShape.dockers.last().setReferencePoint(shape.dockers.last().referencePoint);
}
}
});
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if(!ORYX.Plugins) {
ORYX.Plugins = new Object();
}
ORYX.Plugins.AddDocker = Clazz.extend({
/**
* Constructor
* @param {Object} Facade: The Facade of the Editor
*/
construct: function(facade) {
this.facade = facade;
this.facade.offer({
'name':ORYX.I18N.AddDocker.add,
'functionality': this.enableAddDocker.bind(this),
'group': ORYX.I18N.AddDocker.group,
'iconCls': 'pw-toolbar-button pw-toolbar-add-docker',
'description': ORYX.I18N.AddDocker.addDesc,
'index': 1,
'toggle': true,
'minShape': 0,
'maxShape': 0,
'visibleInViewMode': false
});
this.facade.offer({
'name':ORYX.I18N.AddDocker.del,
'functionality': this.enableDeleteDocker.bind(this),
'group': ORYX.I18N.AddDocker.group,
'iconCls': 'pw-toolbar-button pw-toolbar-remove-docker',
'description': ORYX.I18N.AddDocker.delDesc,
'index': 2,
'toggle': true,
'minShape': 0,
'maxShape': 0,
'visibleInViewMode': false
});
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MOUSEDOWN, this.handleMouseDown.bind(this));
},
enableAddDocker: function(button, pressed) {
//FIXME This should be done while construct, but this isn't possible right now!
this.addDockerButton = button;
if (pressed) {
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_DISPLAY_SCHLAUMEIER,
'message': "Try Alt+Click on an edge to add docker."
});
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_DISABLE_DOCKER_CREATION
});
} else if (!(this.enabledDelete())){
// AddDocker button was deselected, so allow for docker creation with ALT+click again.
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_ENABLE_DOCKER_CREATION
});
}
// Unpress deleteDockerButton
if(pressed && this.deleteDockerButton)
this.deleteDockerButton.toggle(false);
},
enableDeleteDocker: function(button, pressed) {
//FIXME This should be done while construct, but this isn't possible right now!
this.deleteDockerButton = button;
if (pressed) {
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_DISPLAY_SCHLAUMEIER,
'message': "Try Alt+Click on a docker to remove it."
});
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_DISABLE_DOCKER_CREATION
});
}
// Unpress addDockerButton
if(pressed && this.addDockerButton) {
this.addDockerButton.toggle(false);
} else if (!pressed && !(this.enabledAdd())) {
// if the deletebutton has been unpressed and the addbutton is not enabled, docker creation should be possible
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_ENABLE_DOCKER_CREATION
});
}
},
enabledAdd: function(){
return this.addDockerButton ? this.addDockerButton.pressed : false;
},
enabledDelete: function(){
return this.deleteDockerButton ? this.deleteDockerButton.pressed : false;
},
/**
* MouseDown Handler
*
*/
handleMouseDown: function(event, uiObj) {
if (this.enabledAdd() && uiObj instanceof ORYX.Core.Edge) {
this.newDockerCommand({
edge: uiObj,
position: this.facade.eventCoordinates(event)
});
} else if (this.enabledDelete() && uiObj instanceof ORYX.Core.Controls.Docker && uiObj.parent instanceof ORYX.Core.Edge) {
//check if uiObj is not the first or last docker of its parent, if not so instanciate deleteCommand
if ((uiObj.parent.dockers.first() !== uiObj) && (uiObj.parent.dockers.last() !== uiObj)) {
this.newDockerCommand({
edge: uiObj.parent,
docker: uiObj
});
}
} else if ( this.enabledAdd() ){
this.addDockerButton.toggle(false);
} else if ( this.enabledDelete() ) {
this.deleteDockerButton.toggle(false);
}
},
// Options: edge (required), position (required if add), docker (required if delete)
newDockerCommand: function newDockerCommand(options){
if(!options.edge)
return;
var args = {
"options": options
}
var command = new ORYX.Core.Commands["DockerCreation.NewDockerCommand"](this.enabledAdd(), this.enabledDelete(), options.edge, options.docker, options.position, this.facade, args);
this.facade.executeCommands([command]);
}
});
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if(!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Core.Commands["DragDropResize.DockCommand"] = ORYX.Core.AbstractCommand.extend({
construct: function construct(docker, relativePosition, newDockedShape, facade) {
arguments.callee.$.construct.call(this, facade);
this.docker = docker;
this.newPosition = relativePosition;
this.newDockedShape = newDockedShape;
this.newParent = newDockedShape.parent || facade.getCanvas();
this.newParent = newDockedShape.parent || facade.getCanvas();
this.oldDockedShape = docker.getDockedShape();
if (typeof this.oldDockedShape === "undefined") {
this.oldPosition = docker.parent.bounds.center()
} else {
// if oldDockedShape was not the canvas, i.e. results in undefined, calculate relative position
this.oldPosition = this.facade.getCanvas().node.ownerSVGElement.createSVGPoint();
this.oldPosition.x = Math.abs((this.oldDockedShape.absoluteBounds().lowerRight().x - docker.parent.absoluteBounds().center().x) / this.oldDockedShape.bounds.width());
this.oldPosition.y = Math.abs((this.oldDockedShape.absoluteBounds().lowerRight().y - docker.parent.absoluteBounds().center().y) / this.oldDockedShape.bounds.height());
}
this.oldParent = docker.parent.parent || facade.getCanvas();
this.facade = facade;
},
execute: function execute() {
this.dock(this.newDockedShape, this.newParent, this.newPosition);
// Raise Event for having the docked shape on top of the other shape
this.facade.raiseEvent(
{
"type": ORYX.CONFIG.EVENT_ARRANGEMENTLIGHT_TOP,
"shape": this.docker.parent
}
)
},
rollback: function rollback() {
this.dock( this.oldDockedShape, this.oldParent, this.oldPosition );
},
getCommandName: function getCommandName() {
return "DragDropResize.DockCommand";
},
getDisplayName: function getDisplayName() {
return "Event docked";
},
dock: function(toDockShape, parent, relativePosition) {
var relativePos = relativePosition;
/* if shape should be attached to a shape, calculate absolute position, otherwise relativePosition is relative to canvas, i.e. absolute
values are expected to be between 0 and 1, if faulty values are found, they are set manually - with x = 0 and y = 0, shape will be docked at lower right corner*/
if (typeof toDockShape !== "undefined") {
var absolutePosition = this.facade.getCanvas().node.ownerSVGElement.createSVGPoint();
if ((0 > relativePos.x) || (relativePos.x > 1) || (0 > relativePos.y) || (relativePos.y > 1)) {
relativePos.x = 0;
relativePos.y = 0;
}
absolutePosition.x = Math.abs(toDockShape.absoluteBounds().lowerRight().x - relativePos.x * toDockShape.bounds.width());
absolutePosition.y = Math.abs(toDockShape.absoluteBounds().lowerRight().y - relativePos.y * toDockShape.bounds.height());
} else {
var absolutePosition = relativePosition;
}
// Add to the same parent Shape
parent.add(this.docker.parent)
//it seems that for docker to be moved, the dockedShape need to be cleared first
this.docker.setDockedShape(undefined);
this.docker.bounds.centerMoveTo(absolutePosition);
this.docker.setDockedShape(toDockShape);
//this.docker.update();
if (this.isLocal()) {
this.facade.setSelection([this.docker.parent]);
}
this.facade.getCanvas().update();
this.facade.updateSelection(this.isLocal());
},
getCommandData: function getCommandData() {
var getDockerId = function(docker) {
var dockerId;
if (typeof docker !== "undefined") {
dockerId = docker.id;
}
return dockerId;
};
var cmd = {
"dockerParentId": this.docker.parent.resourceId,
"newPosition": this.newPosition,
"newDockedShapeId": this.newDockedShape.resourceId
};
return cmd;
},
createFromCommandData: function jsonDeserialize(facade, commandData) {
var docker, parent, newShape, newPosition;
var canvas = facade.getCanvas();
newShape = canvas.getChildShapeByResourceId(commandData.newDockedShapeId);
// Don't instantiate a new command when the shape to be resized doesn't exist anymore.
if (typeof newShape === 'undefined') {
return undefined;
}
parent = canvas.getChildShapeByResourceId(commandData.dockerParentId);
newPosition = canvas.node.ownerSVGElement.createSVGPoint();
newPosition.x = commandData.newPosition.x;
newPosition.y = commandData.newPosition.y;
for (var i = 0; i < newShape.dockers.length; i++) {
if (newShape.dockers[i].id == commandData.dockerId) {
docker = newShape.dockers[i];
}
}
var newCommand = new ORYX.Core.Commands["DragDropResize.DockCommand"](parent.dockers[0], newPosition, newShape, facade);
return newCommand;
},
getAffectedShapes: function getAffectedShapes() {
return [this.docker.parent];
}
});
ORYX.Plugins.DragDropResize = ORYX.Plugins.AbstractPlugin.extend({
/**
* Constructor
* @param {Object} Facade: The Facade of the Editor
*/
construct: function(facade) {
this.facade = facade;
// Initialize variables
this.currentShapes = []; // Current selected Shapes
//this.pluginsData = []; // Available Plugins
this.toMoveShapes = []; // Shapes there will be moved
this.distPoints = []; // Distance Points for Snap on Grid
this.isResizing = false; // Flag: If there was currently resized
this.dragEnable = false; // Flag: If Dragging is enabled
this.dragIntialized = false; // Flag: If the Dragging is initialized
this.edgesMovable = true; // Flag: If an edge is docked it is not movable
this.offSetPosition = {x: 0, y: 0}; // Offset of the Dragging
this.faktorXY = {x: 1, y: 1}; // The Current Zoom-Faktor
this.containmentParentNode; // the current future parent node for the dragged shapes
this.isAddingAllowed = false; // flag, if adding current selected shapes to containmentParentNode is allowed
this.isAttachingAllowed = false; // flag, if attaching to the current shape is allowed
this.callbackMouseMove = this.handleMouseMove.bind(this);
this.callbackMouseUp = this.handleMouseUp.bind(this);
// Get the SVG-Containernode
var containerNode = this.facade.getCanvas().getSvgContainer();
// Create the Selected Rectangle in the SVG
this.selectedRect = new ORYX.Plugins.SelectedRect(containerNode);
// Show grid line if enabled
if (ORYX.CONFIG.SHOW_GRIDLINE) {
this.vLine = new ORYX.Plugins.GridLine(containerNode, ORYX.Plugins.GridLine.DIR_VERTICAL);
this.hLine = new ORYX.Plugins.GridLine(containerNode, ORYX.Plugins.GridLine.DIR_HORIZONTAL);
}
// Get a HTML-ContainerNode
containerNode = this.facade.getCanvas().getHTMLContainer();
this.scrollNode = this.facade.getCanvas().rootNode.parentNode.parentNode;
// Create the southeastern button for resizing
this.resizerSE = new ORYX.Plugins.Resizer(containerNode, "southeast", this.facade);
this.resizerSE.registerOnResize(this.onResize.bind(this)); // register the resize callback
this.resizerSE.registerOnResizeEnd(this.onResizeEnd.bind(this, "southeast")); // register the resize end callback
this.resizerSE.registerOnResizeStart(this.onResizeStart.bind(this)); // register the resize start callback
// Create the northwestern button for resizing
this.resizerNW = new ORYX.Plugins.Resizer(containerNode, "northwest", this.facade);
this.resizerNW.registerOnResize(this.onResize.bind(this)); // register the resize callback
this.resizerNW.registerOnResizeEnd(this.onResizeEnd.bind(this, "northwest")); // register the resize end callback
this.resizerNW.registerOnResizeStart(this.onResizeStart.bind(this)); // register the resize start callback
// For the Drag and Drop
// Register on MouseDown-Event on a Shape
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MOUSEDOWN, this.handleMouseDown.bind(this));
// register for layouting event
// this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LAYOUT_EDGES, this.handleLayoutEdges.bind(this));
// listen for canvas resizes causing moving of shapes
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_CANVAS_RESIZE_SHAPES_MOVED, this.onCanvasResizeShapesMoved.bind(this));
},
handleLayoutEdges: function(event) {
this.layoutEdges(event.node, event.edges, event.offset);
},
/**
* On Mouse Down
*
*/
handleMouseDown: function(event, uiObj) {
// If the selection Bounds not intialized and the uiObj is not member of current selectio
// then return
if(!this.dragBounds || !this.currentShapes.member(uiObj) || !this.toMoveShapes.length) {return};
// Start Dragging
this.dragEnable = true;
this.dragIntialized = true;
this.edgesMovable = true;
// Calculate the current zoom factor
var a = this.facade.getCanvas().node.getScreenCTM();
this.faktorXY.x = a.a;
this.faktorXY.y = a.d;
// Set the offset position of dragging
var upL = this.dragBounds.upperLeft();
this.offSetPosition = {
x: Event.pointerX(event) - (upL.x * this.faktorXY.x),
y: Event.pointerY(event) - (upL.y * this.faktorXY.y)};
this.offsetScroll = {x:this.scrollNode.scrollLeft,y:this.scrollNode.scrollTop};
// Register on Global Mouse-MOVE Event
document.documentElement.addEventListener(ORYX.CONFIG.EVENT_MOUSEMOVE, this.callbackMouseMove, false);
// Register on Global Mouse-UP Event
document.documentElement.addEventListener(ORYX.CONFIG.EVENT_MOUSEUP, this.callbackMouseUp, true);
},
/**
* On Key Mouse Up
*
*/
handleMouseUp: function(event) {
//disable containment highlighting
this.facade.raiseEvent({ type:ORYX.CONFIG.EVENT_HIGHLIGHT_HIDE,
highlightId:"dragdropresize.contain" });
this.facade.raiseEvent({ type:ORYX.CONFIG.EVENT_HIGHLIGHT_HIDE,
highlightId:"dragdropresize.attached" });
// If Dragging is finished
if (this.dragEnable) {
var position = this.calculateDragPosition(event);
this.dragBounds.moveTo(position);
// and update the current selection
if (!this.dragIntialized) {
this.afterDrag();
// Check if the Shape is allowed to dock to the other Shape
if (this.isAttachingAllowed &&
this.toMoveShapes.length == 1 && this.toMoveShapes[0] instanceof ORYX.Core.Node &&
this.toMoveShapes[0].dockers.length > 0) {
// Get the position and the docker
var position = this.facade.eventCoordinates( event );
// calculate the relative position of the docker within the newDockedShape
var newDockedShape = this.containmentParentNode;
var relativePosition = this.facade.getCanvas().node.ownerSVGElement.createSVGPoint();
relativePosition.x = (newDockedShape.absoluteBounds().lowerRight().x - position.x) / newDockedShape.bounds.width();
relativePosition.y = (newDockedShape.absoluteBounds().lowerRight().y - position.y) / newDockedShape.bounds.height();
var docker = this.toMoveShapes[0].dockers[0];
// Instantiate the dockCommand
var command = new ORYX.Core.Commands["DragDropResize.DockCommand"](docker, relativePosition, this.containmentParentNode, this.facade);
this.facade.executeCommands([command]);
// Check if adding is allowed to the other Shape
} else if( this.isAddingAllowed ) {
// Refresh all Shapes --> Set the new Bounds
this.refreshSelectedShapes();
}
this.facade.updateSelection(true);
this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_DRAGDROP_END});
}
if (this.vLine)
this.vLine.hide();
if (this.hLine)
this.hLine.hide();
this.facade.updateSelection(true);
}
// Disable
this.dragEnable = false;
// UnRegister on Global Mouse-UP/-Move Event
document.documentElement.removeEventListener(ORYX.CONFIG.EVENT_MOUSEUP, this.callbackMouseUp, true);
document.documentElement.removeEventListener(ORYX.CONFIG.EVENT_MOUSEMOVE, this.callbackMouseMove, false);
},
/**
* On Key Mouse Move
*
*/
handleMouseMove: function(event) {
if (!this.dragEnable) {
return;
};
if (this.dragIntialized) {
// Raise Event: Drag will be started
this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_DRAGDROP_START});
this.dragIntialized = false;
// And hide the resizers and the highlighting
this.resizerSE.hide();
this.resizerNW.hide();
// if only edges are selected, containmentParentNode must be the canvas
this._onlyEdges = this.currentShapes.all(function(currentShape) {
return (currentShape instanceof ORYX.Core.Edge);
});
// Do method before Drag
this.beforeDrag();
this._currentUnderlyingNodes = [];
}
var position = this.calculateDragPosition(event);
this.dragBounds.moveTo(position);
// Update the selection rectangle
this.resizeRectangle(this.dragBounds);
this.isAttachingAllowed = false;
//check, if a node can be added to the underlying node
var underlyingNodes = $A(this.facade.getCanvas().getAbstractShapesAtPosition(this.facade.eventCoordinates(event)));
var checkIfAttachable = this.toMoveShapes.length == 1 && this.toMoveShapes[0] instanceof ORYX.Core.Node && this.toMoveShapes[0].dockers.length > 0
checkIfAttachable = checkIfAttachable && underlyingNodes.length != 1
if (!checkIfAttachable &&
underlyingNodes.length === this._currentUnderlyingNodes.length &&
underlyingNodes.all(function(node, index){return this._currentUnderlyingNodes[index] === node}.bind(this))) {
return;
} else if(this._onlyEdges) {
this.isAddingAllowed = true;
this.containmentParentNode = this.facade.getCanvas();
} else {
/* Check the containment and connection rules */
var options = { event : event,
underlyingNodes : underlyingNodes,
checkIfAttachable : checkIfAttachable };
this.checkRules(options);
}
this._currentUnderlyingNodes = underlyingNodes.reverse();
//visualize the containment result
if (this.isAttachingAllowed) {
this.facade.raiseEvent({ type: ORYX.CONFIG.EVENT_HIGHLIGHT_SHOW,
highlightId: "dragdropresize.attached",
elements: [this.containmentParentNode],
style: ORYX.CONFIG.SELECTION_HIGHLIGHT_STYLE_RECTANGLE,
color: ORYX.CONFIG.SELECTION_VALID_COLOR });
} else {
this.facade.raiseEvent({ type: ORYX.CONFIG.EVENT_HIGHLIGHT_HIDE,
highlightId: "dragdropresize.attached" });
}
if( !this.isAttachingAllowed ){
if( this.isAddingAllowed ) {
this.facade.raiseEvent({ type: ORYX.CONFIG.EVENT_HIGHLIGHT_SHOW,
highlightId: "dragdropresize.contain",
elements: [this.containmentParentNode],
color: ORYX.CONFIG.SELECTION_VALID_COLOR });
} else {
this.facade.raiseEvent({ type: ORYX.CONFIG.EVENT_HIGHLIGHT_SHOW,
highlightId: "dragdropresize.contain",
elements: [this.containmentParentNode],
color: ORYX.CONFIG.SELECTION_INVALID_COLOR });
}
} else {
this.facade.raiseEvent({ type: ORYX.CONFIG.EVENT_HIGHLIGHT_HIDE,
highlightId: "dragdropresize.contain" });
}
},
calculateDragPosition : function(event) {
var position = { x: Event.pointerX(event) - this.offSetPosition.x,
y: Event.pointerY(event) - this.offSetPosition.y };
position.x -= this.offsetScroll.x - this.scrollNode.scrollLeft;
position.y -= this.offsetScroll.y - this.scrollNode.scrollTop;
// If not the Control-Key are pressed
var modifierKeyPressed = event.shiftKey || event.ctrlKey;
if(ORYX.CONFIG.GRID_ENABLED && !modifierKeyPressed) {
// Snap the current position to the nearest Snap-Point
position = this.snapToGrid(position);
} else {
if (this.vLine) {
this.vLine.hide();
}
if (this.hLine) {
this.hLine.hide();
}
}
// Adjust the point by the zoom faktor
position.x /= this.faktorXY.x;
position.y /= this.faktorXY.y;
// Set that the position is not lower than zero
position.x = Math.max(0, position.x)
position.y = Math.max(0, position.y)
// Set that the position is not bigger than the canvas
var c = this.facade.getCanvas();
position.x = Math.min(c.bounds.width() - this.dragBounds.width(), position.x);
position.y = Math.min(c.bounds.height() - this.dragBounds.height(), position.y);
return position;
},
// /**
// * Rollbacks the docked shape of an edge, if the edge is not movable.
// */
// redockEdges: function() {
// this._undockedEdgesCommand.dockers.each(function(el){
// el.docker.setDockedShape(el.dockedShape);
// el.docker.setReferencePoint(el.refPoint);
// })
// },
/**
* Checks the containment and connection rules for the selected shapes.
*/
checkRules : function(options) {
var event = options.event;
var underlyingNodes = options.underlyingNodes;
var checkIfAttachable = options.checkIfAttachable;
var noEdges = options.noEdges;
//get underlying node that is not the same than one of the currently selected shapes or
// a child of one of the selected shapes with the highest z Order.
// The result is a shape or the canvas
this.containmentParentNode = underlyingNodes.reverse().find((function(node) {
return (node instanceof ORYX.Core.Canvas) ||
(((node instanceof ORYX.Core.Node) || ((node instanceof ORYX.Core.Edge) && !noEdges))
&& (!(this.currentShapes.member(node) ||
this.currentShapes.any(function(shape) {
return (shape.children.length > 0 && shape.getChildNodes(true).member(node));
}))));
}).bind(this));
if (checkIfAttachable && typeof this.containmentParentNode !== "undefined") {
this.isAttachingAllowed = this.facade.getRules().canConnect({
sourceShape: this.containmentParentNode,
edgeShape: this.toMoveShapes[0],
targetShape: this.toMoveShapes[0]
});
if (this.isAttachingAllowed) {
var point = this.facade.eventCoordinates(event);
this.isAttachingAllowed = this.containmentParentNode.isPointOverOffset(point.x, point.y);
}
}
if( !this.isAttachingAllowed ){
//check all selected shapes, if they can be added to containmentParentNode
this.isAddingAllowed = this.toMoveShapes.all((function(currentShape) {
if(currentShape instanceof ORYX.Core.Edge ||
currentShape instanceof ORYX.Core.Controls.Docker ||
this.containmentParentNode === currentShape.parent) {
return true;
} else if(this.containmentParentNode !== currentShape) {
if(!(this.containmentParentNode instanceof ORYX.Core.Edge) || !noEdges) {
if(this.facade.getRules().canContain({containingShape:this.containmentParentNode,
containedShape:currentShape})) {
return true;
}
}
}
return false;
}).bind(this));
}
if(!this.isAttachingAllowed && !this.isAddingAllowed &&
(this.containmentParentNode instanceof ORYX.Core.Edge)) {
options.noEdges = true;
options.underlyingNodes.reverse();
this.checkRules(options);
}
},
onCanvasResizeShapesMoved: function(event) {
var oldShapePositionsWithOffset = {};
var oldPos;
var shapeId;
// add offsets to drag origin
if (typeof this.oldDragBounds !== "undefined") {
this.oldDragBounds.moveBy(event.offsetX, event.offsetY);
}
// add offsets to original shape positions
if (typeof this.oldShapePositions !== "undefined") {
for (shapeId in this.oldShapePositions) {
if (this.oldShapePositions.hasOwnProperty(shapeId)) {
oldPos = this.oldShapePositions[shapeId];
oldShapePositionsWithOffset[shapeId] = { x: oldPos.x + event.offsetX,
y: oldPos.y + event.offsetY };
}
}
this.oldShapePositions = oldShapePositionsWithOffset;
}
// update selection rectangle visuals
if (this.dragEnable && (typeof this.dragBounds !== "undefined")) {
// update bounds
this.dragBounds.moveBy(event.offsetX, event.offsetY);
this.resizeRectangle(this.dragBounds);
// update highlighting
this.facade.raiseEvent({ type: ORYX.CONFIG.EVENT_CANVAS_RESIZE_UPDATE_HIGHLIGHTS,
elements: this.toMoveShapes });
}
},
/**
* Redraw the selected Shapes.
*
*/
refreshSelectedShapes: function() {
// If the selection bounds not initialized, return
if(!this.dragBounds) {return}
// Calculate the offset between the selection's new drag bounds and old drag bounds:
var newDragBoundsCenter = this.dragBounds.center();
var oldDragBoundsCenter = this.oldDragBounds.center();
var offset = {
x: newDragBoundsCenter.x - oldDragBoundsCenter.x,
y: newDragBoundsCenter.y - oldDragBoundsCenter.y
};
var getTargetPosition = function getTargetPosition(shape, offset) {
// Add the calculated drag bounds offset to the shape bounds to get the target position for the shape:
var oldShapeCenter = this.oldShapePositions[shape.id];
return { x: oldShapeCenter.x + offset.x, y: oldShapeCenter.y + offset.y };
}.bind(this);
var aliveMoveShapes = this.removeDeadShapes(this.toMoveShapes);
if (aliveMoveShapes.length > 0) {
// Instantiate the Move Command
var moveShapes = aliveMoveShapes.map(function addTargetPositionToShapes(shape) {
return { shape: shape,
origin: this.oldShapePositions[shape.id],
target: getTargetPosition(shape, offset) };
}.bind(this));
var commands = [new ORYX.Core.Commands["DragDropResize.MoveCommand"](moveShapes, this.containmentParentNode, this.currentShapes, this.facade)];
// If the undocked edges command is setted, add this command
if( this._undockedEdgesCommand instanceof ORYX.Core.Command ){
commands.unshift( this._undockedEdgesCommand );
}
// Execute the commands
this.facade.executeCommands( commands );
// copy the bounds to the old bounds
if( this.dragBounds )
this.oldDragBounds = this.dragBounds.clone();
}
},
removeDeadShapes: function removeDeadShapes(moveShapes) {
var canvas = this.facade.getCanvas();
var getShape = function getShape(resourceId) {
var shape = canvas.getChildShapeByResourceId(resourceId);
return shape;
};
var getDocker = function getDocker(shape, dockerId) {
var docker = undefined;
for (var i = 0; i < shape.dockers.length; i++) {
if (shape.dockers[i].id == dockerId) {
docker = shape.dockers[i];
}
}
return docker;
};
var aliveMoveShapes = [];
for (var i = 0; i < moveShapes.length; i++) {
var currentShape = moveShapes[i];
if (currentShape instanceof ORYX.Core.Node || currentShape instanceof ORYX.Core.Edge) {
var currentShapeOnCanvas = getShape(currentShape.resourceId);
if (typeof currentShapeOnCanvas !== "undefined") {
aliveMoveShapes.push(moveShapes[i]);
}
} else if (currentShape instanceof ORYX.Core.Controls.Docker) {
var parentShapeOnCanvas = getShape(currentShape.parent.resourceId);
if (typeof parentShapeOnCanvas === "undefined") {
continue;
} else {
var dockerOnCanvas = getDocker(parentShapeOnCanvas, currentShape.id);
if (typeof dockerOnCanvas !== "undefined") {
aliveMoveShapes.push(moveShapes[i]);
}
}
}
}
return aliveMoveShapes;
},
/**
* Callback for Resize
*
*/
onResize: function(bounds) {
// If the selection bounds not initialized, return
if(!this.dragBounds) {return}
this.dragBounds = bounds;
this.isResizing = true;
// Update the rectangle
this.resizeRectangle(this.dragBounds);
},
onResizeStart: function() {
this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_RESIZE_START});
},
onResizeEnd: function(orientation) {
if (!(this.currentShapes instanceof Array)||this.currentShapes.length<=0) {
return;
}
// If Resizing finished, the Shapes will be resize
if (this.isResizing) {
if (((orientation === "southeast") && (this.dragBounds.b.x === this.oldDragBounds.b.x) && (this.dragBounds.b.y === this.oldDragBounds.b.y)) || ((orientation === "northwest") && (this.dragBounds.a.x == this.oldDragBounds.a.x) && (this.dragBounds.a.y == this.oldDragBounds.a.y))) {
var bounds = this.dragBounds.clone();
var shape = this.currentShapes[0];
if (shape.parent) {
var parentPosition = shape.parent.absoluteXY();
bounds.moveBy(-parentPosition.x, -parentPosition.y);
}
var aliveShapeArray = this.removeDeadShapes([shape]);
if (aliveShapeArray.length > 0) {
var oldBounds = shape.bounds.clone();
var command = new ORYX.Core.Commands["DragDropResize.ResizeCommand"](shape, bounds, oldBounds, this.facade, orientation);
this.facade.executeCommands([command]);
this.isResizing = false;
this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_RESIZE_END});
}
}
}
},
/**
* Prepare the Dragging
*
*/
beforeDrag: function(){
this._undockedEdgesCommand = new ORYX.Core.Commands["DragDropResize.UndockEdgeCommand"](this.toMoveShapes, this.facade);
this._undockedEdgesCommand.execute();
},
hideAllLabels: function(shape) {
// Hide all labels from the shape
shape.getLabels().each(function(label) {
label.hide();
});
// Hide all labels from docked shapes
shape.getAllDockedShapes().each(function(dockedShape) {
var labels = dockedShape.getLabels();
if(labels.length > 0) {
labels.each(function(label) {
label.hide();
});
}
});
// Do this recursive for all child shapes
// EXP-NICO use getShapes
shape.getChildren().each((function(value) {
if(value instanceof ORYX.Core.Shape)
this.hideAllLabels(value);
}).bind(this));
},
/**
* Finished the Dragging
*
*/
afterDrag: function(){
},
/**
* Show all Labels at these shape
*
*/
showAllLabels: function(shape) {
// Show the label of these shape
//shape.getLabels().each(function(label) {
for(var i=0; i<shape.length ;i++){
var label = shape[i];
label.show();
}//);
// Show all labels at docked shapes
//shape.getAllDockedShapes().each(function(dockedShape) {
var allDockedShapes = shape.getAllDockedShapes()
for(var i=0; i<allDockedShapes.length ;i++){
var dockedShape = allDockedShapes[i];
var labels = dockedShape.getLabels();
if(labels.length > 0) {
labels.each(function(label) {
label.show();
});
}
}//);
// Do this recursive
//shape.children.each((function(value) {
for(var i=0; i<shape.children.length ;i++){
var value = shape.children[i];
if(value instanceof ORYX.Core.Shape)
this.showAllLabels(value);
}//).bind(this));
},
/**
* Intialize Method, if there are new Plugins
*
*/
/*registryChanged: function(pluginsData) {
// Save all new Plugin, sorted by group and index
this.pluginsData = pluginsData.sortBy( function(value) {
return (value.group + "" + value.index);
});
},*/
/**
* On the Selection-Changed
*
*/
onSelectionChanged: function(event) {
var elements = event.elements;
// Reset the drag-variables
this.dragEnable = false;
this.dragIntialized = false;
this.resizerSE.hide();
this.resizerNW.hide();
// If there is no elements
if(!elements || elements.length == 0) {
// Hide all things and reset all variables
this.selectedRect.hide();
this.currentShapes = [];
this.toMoveShapes = [];
this.dragBounds = undefined;
this.oldDragBounds = undefined;
this.oldShapePositions = {};
} else {
// Set the current Shapes
this.currentShapes = elements;
// Get all shapes with the highest parent in object hierarchy (canvas is the top most parent)
var topLevelElements = this.facade.getCanvas().getShapesWithSharedParent(elements);
this.toMoveShapes = topLevelElements;
this.toMoveShapes = this.toMoveShapes.findAll( function(shape) { return shape instanceof ORYX.Core.Node &&
(shape.dockers.length === 0 || !elements.member(shape.dockers.first().getDockedShape()))});
elements.each((function(shape){
if(!(shape instanceof ORYX.Core.Edge)) {return}
var dks = shape.getDockers()
var hasF = elements.member(dks.first().getDockedShape());
var hasL = elements.member(dks.last().getDockedShape());
// if(!hasL) {
// this.toMoveShapes.push(dks.last());
// }
// if(!hasF){
// this.toMoveShapes.push(dks.first())
// }
/* Enable movement of undocked edges */
if(!hasF && !hasL) {
var isUndocked = !dks.first().getDockedShape() && !dks.last().getDockedShape()
if(isUndocked) {
this.toMoveShapes = this.toMoveShapes.concat(dks);
}
}
if( shape.dockers.length > 2 && hasF && hasL){
this.toMoveShapes = this.toMoveShapes.concat(dks.findAll(function(el,index){ return index > 0 && index < dks.length-1}))
}
}).bind(this));
// store old shape positions to cope with the problem that remote collaborators
// could remove these shapes while they are being dragged around
this.oldShapePositions = {};
this.toMoveShapes.each(function storeShapePosition(shape) {
this.oldShapePositions[shape.id] = shape.absoluteBounds().center();
}.bind(this));
// Calculate the new area-bounds of the selection
var newBounds = undefined;
this.toMoveShapes.each(function(value) {
var shape = value;
if(value instanceof ORYX.Core.Controls.Docker) {
/* Get the Shape */
shape = value.parent;
}
if(!newBounds){
newBounds = shape.absoluteBounds();
}
else {
newBounds.include(shape.absoluteBounds());
}
}.bind(this));
if(!newBounds){
elements.each(function(value){
if(!newBounds) {
newBounds = value.absoluteBounds();
} else {
newBounds.include(value.absoluteBounds());
}
});
}
// Set the new bounds
this.dragBounds = newBounds;
this.oldDragBounds = newBounds.clone();
// Update and show the rectangle
this.resizeRectangle(newBounds);
this.selectedRect.show();
// Show the resize button, if there is only one element and this is resizeable
if(elements.length == 1 && elements[0].isResizable) {
var aspectRatio = elements[0].getStencil().fixedAspectRatio() ? elements[0].bounds.width() / elements[0].bounds.height() : undefined;
this.resizerSE.setBounds(this.dragBounds, elements[0].minimumSize, elements[0].maximumSize, aspectRatio);
this.resizerSE.show();
this.resizerNW.setBounds(this.dragBounds, elements[0].minimumSize, elements[0].maximumSize, aspectRatio);
this.resizerNW.show();
} else {
this.resizerSE.setBounds(undefined);
this.resizerNW.setBounds(undefined);
}
// If Snap-To-Grid is enabled, the Snap-Point will be calculate
if(ORYX.CONFIG.GRID_ENABLED) {
// Reset all points
this.distPoints = [];
if (this.distPointTimeout)
window.clearTimeout(this.distPointTimeout)
this.distPointTimeout = window.setTimeout(function(){
// Get all the shapes, there will consider at snapping
// Consider only those elements who shares the same parent element
var distShapes = this.facade.getCanvas().getChildShapes(true).findAll(function(value){
var parentShape = value.parent;
while(parentShape){
if(elements.member(parentShape)) return false;
parentShape = parentShape.parent
}
return true;
})
// The current selection will delete from this array
//elements.each(function(shape) {
// distShapes = distShapes.without(shape);
//});
// For all these shapes
distShapes.each((function(value) {
if(!(value instanceof ORYX.Core.Edge)) {
var ul = value.absoluteXY();
var width = value.bounds.width();
var height = value.bounds.height();
// Add the upperLeft, center and lowerRight - Point to the distancePoints
this.distPoints.push({
ul: {
x: ul.x,
y: ul.y
},
c: {
x: ul.x + (width / 2),
y: ul.y + (height / 2)
},
lr: {
x: ul.x + width,
y: ul.y + height
}
});
}
}).bind(this));
}.bind(this), 10)
}
}
},
/**
* Adjust an Point to the Snap Points
*
*/
snapToGrid: function(position) {
// Get the current Bounds
var bounds = this.dragBounds;
var point = {};
var ulThres = 6;
var cThres = 10;
var lrThres = 6;
var scale = this.vLine ? this.vLine.getScale() : 1;
var ul = { x: (position.x/scale), y: (position.y/scale)};
var c = { x: (position.x/scale) + (bounds.width()/2), y: (position.y/scale) + (bounds.height()/2)};
var lr = { x: (position.x/scale) + (bounds.width()), y: (position.y/scale) + (bounds.height())};
var offsetX, offsetY;
var gridX, gridY;
// For each distant point
this.distPoints.each(function(value) {
var x, y, gx, gy;
if (Math.abs(value.c.x-c.x) < cThres){
x = value.c.x-c.x;
gx = value.c.x;
}/* else if (Math.abs(value.ul.x-ul.x) < ulThres){
x = value.ul.x-ul.x;
gx = value.ul.x;
} else if (Math.abs(value.lr.x-lr.x) < lrThres){
x = value.lr.x-lr.x;
gx = value.lr.x;
} */
if (Math.abs(value.c.y-c.y) < cThres){
y = value.c.y-c.y;
gy = value.c.y;
}/* else if (Math.abs(value.ul.y-ul.y) < ulThres){
y = value.ul.y-ul.y;
gy = value.ul.y;
} else if (Math.abs(value.lr.y-lr.y) < lrThres){
y = value.lr.y-lr.y;
gy = value.lr.y;
} */
if (x !== undefined) {
offsetX = offsetX === undefined ? x : (Math.abs(x) < Math.abs(offsetX) ? x : offsetX);
if (offsetX === x)
gridX = gx;
}
if (y !== undefined) {
offsetY = offsetY === undefined ? y : (Math.abs(y) < Math.abs(offsetY) ? y : offsetY);
if (offsetY === y)
gridY = gy;
}
});
if (offsetX !== undefined) {
ul.x += offsetX;
ul.x *= scale;
if (this.vLine&&gridX)
this.vLine.update(gridX);
} else {
ul.x = (position.x - (position.x % (ORYX.CONFIG.GRID_DISTANCE/2)));
if (this.vLine)
this.vLine.hide()
}
if (offsetY !== undefined) {
ul.y += offsetY;
ul.y *= scale;
if (this.hLine&&gridY)
this.hLine.update(gridY);
} else {
ul.y = (position.y - (position.y % (ORYX.CONFIG.GRID_DISTANCE/2)));
if (this.hLine)
this.hLine.hide();
}
return ul;
},
showGridLine: function(){
},
/**
* Redraw of the Rectangle of the SelectedArea
* @param {Object} bounds
*/
resizeRectangle: function(bounds) {
// Resize the Rectangle
this.selectedRect.resize(bounds);
}
});
ORYX.Plugins.SelectedRect = Clazz.extend({
construct: function(parentId) {
this.parentId = parentId;
this.node = ORYX.Editor.graft("http://www.w3.org/2000/svg", $(parentId),
['g']);
this.dashedArea = ORYX.Editor.graft("http://www.w3.org/2000/svg", this.node,
['rect', {x: 0, y: 0,
'stroke-width': 1, stroke: '#777777', fill: 'none',
'stroke-dasharray': '2,2',
'pointer-events': 'none'}]);
this.hide();
},
hide: function() {
this.node.setAttributeNS(null, 'display', 'none');
},
show: function() {
this.node.setAttributeNS(null, 'display', '');
},
resize: function(bounds) {
var upL = bounds.upperLeft();
var padding = ORYX.CONFIG.SELECTED_AREA_PADDING;
this.dashedArea.setAttributeNS(null, 'width', bounds.width() + 2*padding);
this.dashedArea.setAttributeNS(null, 'height', bounds.height() + 2*padding);
this.node.setAttributeNS(null, 'transform', "translate("+ (upL.x - padding) +", "+ (upL.y - padding) +")");
}
});
ORYX.Plugins.GridLine = Clazz.extend({
construct: function(parentId, direction) {
if (ORYX.Plugins.GridLine.DIR_HORIZONTAL !== direction && ORYX.Plugins.GridLine.DIR_VERTICAL !== direction) {
direction = ORYX.Plugins.GridLine.DIR_HORIZONTAL
}
this.parent = $(parentId);
this.direction = direction;
this.node = ORYX.Editor.graft("http://www.w3.org/2000/svg", this.parent,
['g']);
this.line = ORYX.Editor.graft("http://www.w3.org/2000/svg", this.node,
['path', {
'stroke-width': 1, stroke: 'silver', fill: 'none',
'stroke-dasharray': '5,5',
'pointer-events': 'none'}]);
this.hide();
},
hide: function() {
this.node.setAttributeNS(null, 'display', 'none');
},
show: function() {
this.node.setAttributeNS(null, 'display', '');
},
getScale: function(){
try {
return this.parent.parentNode.transform.baseVal.getItem(0).matrix.a;
} catch(e) {
return 1;
}
},
update: function(pos) {
if (this.direction === ORYX.Plugins.GridLine.DIR_HORIZONTAL) {
var y = pos instanceof Object ? pos.y : pos;
var cWidth = this.parent.parentNode.parentNode.width.baseVal.value/this.getScale();
this.line.setAttributeNS(null, 'd', 'M 0 '+y+ ' L '+cWidth+' '+y);
} else {
var x = pos instanceof Object ? pos.x : pos;
var cHeight = this.parent.parentNode.parentNode.height.baseVal.value/this.getScale();
this.line.setAttributeNS(null, 'd', 'M'+x+ ' 0 L '+x+' '+cHeight);
}
this.show();
}
});
ORYX.Plugins.GridLine.DIR_HORIZONTAL = "hor";
ORYX.Plugins.GridLine.DIR_VERTICAL = "ver";
ORYX.Plugins.Resizer = Clazz.extend({
construct: function(parentId, orientation, facade) {
this.parentId = parentId;
this.orientation = orientation;
this.facade = facade;
this.node = ORYX.Editor.graft("http://www.w3.org/1999/xhtml", $(this.parentId),
['div', {'class': 'resizer_'+ this.orientation, style:'left:0px; top:0px;'}]);
this.node.addEventListener(ORYX.CONFIG.EVENT_MOUSEDOWN, this.handleMouseDown.bind(this), true);
document.documentElement.addEventListener(ORYX.CONFIG.EVENT_MOUSEUP, this.handleMouseUp.bind(this), true);
document.documentElement.addEventListener(ORYX.CONFIG.EVENT_MOUSEMOVE, this.handleMouseMove.bind(this), false);
this.dragEnable = false;
this.offSetPosition = {x: 0, y: 0};
this.bounds = undefined;
this.canvasNode = this.facade.getCanvas().node;
this.minSize = undefined;
this.maxSize = undefined;
this.aspectRatio = undefined;
this.resizeCallbacks = [];
this.resizeStartCallbacks = [];
this.resizeEndCallbacks = [];
this.hide();
// Calculate the Offset
this.scrollNode = this.node.parentNode.parentNode.parentNode;
},
handleMouseDown: function(event) {
this.dragEnable = true;
this.offsetScroll = {x:this.scrollNode.scrollLeft,y:this.scrollNode.scrollTop};
this.offSetPosition = {
x: Event.pointerX(event) - this.position.x,
y: Event.pointerY(event) - this.position.y};
this.resizeStartCallbacks.each((function(value) {
value(this.bounds);
}).bind(this));
},
handleMouseUp: function(event) {
this.dragEnable = false;
this.containmentParentNode = null;
this.resizeEndCallbacks.each((function(value) {
value(this.bounds);
}).bind(this));
},
handleMouseMove: function(event) {
if(!this.dragEnable) { return }
if(event.shiftKey || event.ctrlKey) {
this.aspectRatio = this.bounds.width() / this.bounds.height();
} else {
this.aspectRatio = undefined;
}
var position = {
x: Event.pointerX(event) - this.offSetPosition.x,
y: Event.pointerY(event) - this.offSetPosition.y}
position.x -= this.offsetScroll.x - this.scrollNode.scrollLeft;
position.y -= this.offsetScroll.y - this.scrollNode.scrollTop;
position.x = Math.min( position.x, this.facade.getCanvas().bounds.width())
position.y = Math.min( position.y, this.facade.getCanvas().bounds.height())
var offset = {
x: position.x - this.position.x,
y: position.y - this.position.y
}
if(this.aspectRatio) {
// fixed aspect ratio
newAspectRatio = (this.bounds.width()+offset.x) / (this.bounds.height()+offset.y);
if(newAspectRatio>this.aspectRatio) {
offset.x = this.aspectRatio * (this.bounds.height()+offset.y) - this.bounds.width();
} else if(newAspectRatio<this.aspectRatio) {
offset.y = (this.bounds.width()+offset.x) / this.aspectRatio - this.bounds.height();
}
}
// respect minimum and maximum sizes of stencil
if(this.orientation==="northwest") {
if(this.bounds.width()-offset.x > this.maxSize.width) {
offset.x = -(this.maxSize.width - this.bounds.width());
if(this.aspectRatio)
offset.y = this.aspectRatio * offset.x;
}
if(this.bounds.width()-offset.x < this.minSize.width) {
offset.x = -(this.minSize.width - this.bounds.width());
if(this.aspectRatio)
offset.y = this.aspectRatio * offset.x;
}
if(this.bounds.height()-offset.y > this.maxSize.height) {
offset.y = -(this.maxSize.height - this.bounds.height());
if(this.aspectRatio)
offset.x = offset.y / this.aspectRatio;
}
if(this.bounds.height()-offset.y < this.minSize.height) {
offset.y = -(this.minSize.height - this.bounds.height());
if(this.aspectRatio)
offset.x = offset.y / this.aspectRatio;
}
} else { // defaults to southeast
if(this.bounds.width()+offset.x > this.maxSize.width) {
offset.x = this.maxSize.width - this.bounds.width();
if(this.aspectRatio)
offset.y = this.aspectRatio * offset.x;
}
if(this.bounds.width()+offset.x < this.minSize.width) {
offset.x = this.minSize.width - this.bounds.width();
if(this.aspectRatio)
offset.y = this.aspectRatio * offset.x;
}
if(this.bounds.height()+offset.y > this.maxSize.height) {
offset.y = this.maxSize.height - this.bounds.height();
if(this.aspectRatio)
offset.x = offset.y / this.aspectRatio;
}
if(this.bounds.height()+offset.y < this.minSize.height) {
offset.y = this.minSize.height - this.bounds.height();
if(this.aspectRatio)
offset.x = offset.y / this.aspectRatio;
}
}
if(this.orientation==="northwest") {
var oldLR = {x: this.bounds.lowerRight().x, y: this.bounds.lowerRight().y};
this.bounds.extend({x:-offset.x, y:-offset.y});
this.bounds.moveBy(offset);
} else { // defaults to southeast
this.bounds.extend(offset);
}
this.update();
this.resizeCallbacks.each((function(value) {
value(this.bounds);
}).bind(this));
Event.stop(event);
},
registerOnResizeStart: function(callback) {
if(!this.resizeStartCallbacks.member(callback)) {
this.resizeStartCallbacks.push(callback);
}
},
unregisterOnResizeStart: function(callback) {
if(this.resizeStartCallbacks.member(callback)) {
this.resizeStartCallbacks = this.resizeStartCallbacks.without(callback);
}
},
registerOnResizeEnd: function(callback) {
if(!this.resizeEndCallbacks.member(callback)) {
this.resizeEndCallbacks.push(callback);
}
},
unregisterOnResizeEnd: function(callback) {
if(this.resizeEndCallbacks.member(callback)) {
this.resizeEndCallbacks = this.resizeEndCallbacks.without(callback);
}
},
registerOnResize: function(callback) {
if(!this.resizeCallbacks.member(callback)) {
this.resizeCallbacks.push(callback);
}
},
unregisterOnResize: function(callback) {
if(this.resizeCallbacks.member(callback)) {
this.resizeCallbacks = this.resizeCallbacks.without(callback);
}
},
hide: function() {
this.node.style.display = "none";
},
show: function() {
if(this.bounds)
this.node.style.display = "";
},
setBounds: function(bounds, min, max, aspectRatio) {
this.bounds = bounds;
if(!min)
min = {width: ORYX.CONFIG.MINIMUM_SIZE, height: ORYX.CONFIG.MINIMUM_SIZE};
if(!max)
max = {width: ORYX.CONFIG.MAXIMUM_SIZE, height: ORYX.CONFIG.MAXIMUM_SIZE};
this.minSize = min;
this.maxSize = max;
this.aspectRatio = aspectRatio;
this.update();
},
update: function() {
if(!this.bounds) { return; }
var upL = this.bounds.upperLeft();
if(this.bounds.width() < this.minSize.width) { this.bounds.set(upL.x, upL.y, upL.x + this.minSize.width, upL.y + this.bounds.height())};
if(this.bounds.height() < this.minSize.height) { this.bounds.set(upL.x, upL.y, upL.x + this.bounds.width(), upL.y + this.minSize.height)};
if(this.bounds.width() > this.maxSize.width) { this.bounds.set(upL.x, upL.y, upL.x + this.maxSize.width, upL.y + this.bounds.height())};
if(this.bounds.height() > this.maxSize.height) { this.bounds.set(upL.x, upL.y, upL.x + this.bounds.width(), upL.y + this.maxSize.height)};
var a = this.canvasNode.getScreenCTM();
// a is undefined when canvas is not displayed (happens during loading). In this case we pray and hope that a.a and a.d equal 1 (zoom level 100%).
if (!a) {
a = {
'a': 1,
'd': 1
};
}
upL.x *= a.a;
upL.y *= a.d;
if(this.orientation==="northwest") {
upL.x -= 13;
upL.y -= 26;
} else { // defaults to southeast
upL.x += (a.a * this.bounds.width()) + 3 ;
upL.y += (a.d * this.bounds.height()) + 3;
}
this.position = upL;
this.node.style.left = this.position.x + "px";
this.node.style.top = this.position.y + "px";
}
});
/**
* Implements a Command to move shapes
*
*/
ORYX.Core.Commands["DragDropResize.MoveCommand"] = ORYX.Core.AbstractCommand.extend({
/**
* @param {Array} moveShapes An array of { shape: <shape object>, origin: <origin position>, target: <target position> } objects
*/
construct: function(moveShapes, parent, selectedShapes, facade){
// super constructor call
arguments.callee.$.construct.call(this, facade);
this.moveShapes = moveShapes;
this.selectedShapes = selectedShapes;
this.parent = parent;
// Defines the old/new parents for the particular shape
this.newParents = moveShapes.collect(function(t){ return parent || t.shape.parent });
this.oldParents = moveShapes.collect(function(shape){ return shape.shape.parent });
this.dockedNodes= moveShapes.findAll(function(shape) {
return shape.shape instanceof ORYX.Core.Node && shape.shape.dockers.length == 1
}).collect(function(shape) {
return {
docker: shape.shape.dockers[0],
dockedShape: shape.shape.dockers[0].getDockedShape(),
refPoint: shape.shape.dockers[0].referencePoint
}
});
},
getAffectedShapes: function getAffectedShapes() {
// return only the shapes from the objects inside the moveShapes Array
var getShapes = function getShapes(obj) {
if (obj.shape instanceof ORYX.Core.Controls.Docker) {
return obj.shape.parent;
}
return obj.shape;
}
var allShapes = this.moveShapes.collect(getShapes);
var flows = [];
for (var i = 0; i < allShapes.length; i++) {
var shape = allShapes[i];
if (shape instanceof ORYX.Core.Node) {
flows = flows.concat(shape.outgoing).concat(shape.incoming);
}
}
return allShapes.concat(flows);
},
getCommandName: function getCommandName() {
return "DragDropResize.MoveCommand";
},
getDisplayName: function getDisplayName() {
return "Shape moved";
},
getCommandData: function getCommandData() {
var mapShapeToId = function convertShapeToId(obj) {
var shapeData = {
origin: obj.origin,
target: obj.target
};
if (obj.shape instanceof ORYX.Core.Controls.Docker) {
/* A docker does not have a resourceId and therefore cannot be found via getChildShapeOrCanvasByResourceId.
Thus, we have to additonally store a reference to the Edge, i.e. the parent of the docker. */
shapeData.shapeId = obj.shape.parent.resourceId;
shapeData.dockerId = obj.shape.id;
} else {
shapeData.shapeId = obj.shape.resourceId;
}
return shapeData;
};
var parentId = null;
if (this.parent) {
parentId = this.parent.resourceId;
}
var cmdData = {
parentId : parentId,
shapeTargetPositions : this.moveShapes.map(mapShapeToId)
};
return cmdData;
},
createFromCommandData: function createFromCommandData(facade, cmdData) {
var i;
var canvas = facade.getCanvas();
var getShape = canvas.getChildShapeByResourceId.bind(canvas);
var mapIdToShape = function mapIdToShape(obj) {
return { shape: getShape(obj.shapeId), origin: obj.origin, target: obj.target }
};
var getDocker = function getDocker(shape, dockerId) {
var docker;
for (var i = 0; i < shape.dockers.length; i++) {
if (shape.dockers[i].id == dockerId) {
docker = shape.dockers[i];
}
}
return docker;
};
var parent = facade.getCanvas().getChildShapeOrCanvasByResourceId(cmdData.parentId);
// There seems to be no map for the parsed array, so we'll just iterate over it.
var moveShapes = [];
for (i = 0; i < cmdData.shapeTargetPositions.length; i++) {
var shape = mapIdToShape(cmdData.shapeTargetPositions[i]);
if (shape.shape instanceof ORYX.Core.Edge) {
var docker = getDocker(shape.shape, cmdData.shapeTargetPositions[i].dockerId);
if (typeof docker!== "undefined") {
var newShape = {
shape: docker,
origin: shape.origin,
target: shape.target
};
moveShapes.push(newShape);
}
} else {
if (typeof shape.shape !== "undefined") {
moveShapes.push(shape);
} else {
ORYX.Log.warn("Trying to move deleted shape");
}
}
}
// Checking if any of the shapes to be moved still exists.
// If not, we don't want to instantiate a command and return undefined instead.
var shapesExist = false;
for (var i = 0; i < moveShapes.length; i++) {
var movingShape = moveShapes[i].shape;
if (movingShape instanceof ORYX.Core.Controls.Docker) {
var resourceId = movingShape.parent.resourceId;
var parentShape = facade.getCanvas().getChildShapeByResourceId(resourceId);
if (typeof parentShape !== 'undefined') {
var docker = getDocker(parentShape, movingShape.id);
if (typeof docker !== "undefined") {
shapesExist = true;
break;
}
}
} else {
var resourceId = movingShape.resourceId;
if (typeof facade.getCanvas().getChildShapeByResourceId(resourceId) !== 'undefined') {
shapesExist = true;
break;
}
}
}
if (!shapesExist) {
return undefined;
}
var selectedShapes = []; // We don't want a remote move to change the current selection.
return new ORYX.Core.Commands["DragDropResize.MoveCommand"](moveShapes, parent, selectedShapes, facade);
},
execute: function(){
var aliveMoveShapesWithParents = this.removeDeadShapes(this.moveShapes, this.newParents);
var aliveMoveShapes = aliveMoveShapesWithParents.moveShapes;
var newParents = aliveMoveShapesWithParents.parents;
this.dockAllShapes();
// Moves all shapes in moveShapes to their targets
this.move(aliveMoveShapes);
// Addes to the new parents
this.addShapeToParent(aliveMoveShapes, newParents);
// Set the selection to the current selection
this.selectCurrentShapes();
this.facade.getCanvas().update();
this.facade.updateSelection(this.isLocal());
},
rollback: function(){
// Moves by the inverted offset
var invertedMoveShapes = this.moveShapes.map(function setTargetToOrigin(obj) {
return { shape: obj.shape, target: obj.origin }
});
var aliveInvertedMoveShapesWithParents = this.removeDeadShapes(invertedMoveShapes, this.oldParents);
var aliveInvertedMoveShapes = aliveInvertedMoveShapesWithParents.moveShapes;
var oldParents = aliveInvertedMoveShapesWithParents.parents;
this.move(invertedMoveShapes);
// Addes to the old parents
this.addShapeToParent(aliveInvertedMoveShapes, oldParents);
this.dockAllShapes(true);
// Set the selection to the current selection
this.selectCurrentShapes();
this.facade.getCanvas().update();
this.facade.updateSelection(this.isLocal());
},
removeDeadShapes: function removeDeadShapes(moveShapes, parents) {
var canvas = this.facade.getCanvas();
var getShape = function getShape(resourceId) {
var shape = canvas.getChildShapeByResourceId(resourceId);
return shape;
};
var getDocker = function getDocker(shape, dockerId) {
var docker = undefined;
for (var i = 0; i < shape.dockers.length; i++) {
if (shape.dockers[i].id == dockerId) {
docker = shape.dockers[i];
}
}
return docker;
};
var aliveMoveShapes = [];
var newParents = [];
for (var i = 0; i < moveShapes.length; i++) {
var currentShape = moveShapes[i].shape;
if (currentShape instanceof ORYX.Core.Node || currentShape instanceof ORYX.Core.Edge) {
var currentShapeOnCanvas = getShape(currentShape.resourceId);
if (typeof currentShapeOnCanvas !== "undefined") {
aliveMoveShapes.push(moveShapes[i]);
newParents.push(parents[i]);
}
} else if (currentShape instanceof ORYX.Core.Controls.Docker) {
var parentShapeOnCanvas = getShape(currentShape.parent.resourceId);
if (typeof parentShapeOnCanvas === "undefined") {
continue;
} else {
var dockerOnCanvas = getDocker(parentShapeOnCanvas, currentShape.id);
if (typeof dockerOnCanvas !== "undefined") {
aliveMoveShapes.push(moveShapes[i]);
newParents.push(parents[i]);
}
}
}
}
return {"moveShapes": aliveMoveShapes, "parents": newParents};
},
/**
* @param {Array} moveShapes An array of { shape: <shape instance to move>, target: <target point> } objects
*/
move: function(moveShapes) {
for(var i = 0; i < moveShapes.length ; i++){
var movingShape = moveShapes[i].shape;
var oldCenter = movingShape.absoluteBounds().center();
var targetCenter = moveShapes[i].target;
// Calculate the offset between the target bounds and the current bounds
var offset = {
x: (targetCenter.x - oldCenter.x),
y: (targetCenter.y - oldCenter.y)
};
movingShape.bounds.moveBy(offset);
if (movingShape instanceof ORYX.Core.Node) {
(movingShape.dockers||[]).each(function(d){
d.bounds.moveBy(offset);
});
// handleLayoutEdges results in inconsistent results between local and remote version - remote version moves undocked (added) docker twice the intended offset
// when it is in line with a start or enddocker
/*var allEdges = [].concat(movingShape.getIncomingShapes())
.concat(movingShape.getOutgoingShapes())
// Remove all edges which are included in the selection from the list
.findAll(function(r){ return r instanceof ORYX.Core.Edge && !moveShapes.any(function(d){ return d == r || (d instanceof ORYX.Core.Controls.Docker && d.parent == r)}) }.bind(this))
// Remove all edges which are between the node and a node contained in the selection from the list
.findAll(function(r){ return (r.dockers.first().getDockedShape() == movingShape || !moveShapes.include(r.dockers.first().getDockedShape())) &&
(r.dockers.last().getDockedShape() == movingShape || !moveShapes.include(r.dockers.last().getDockedShape()))}.bind(this))
// Layout all outgoing/incoming edges
// this.plugin.layoutEdges(node, allEdges, offset);
this.facade.raiseEvent({
type : ORYX.CONFIG.EVENT_LAYOUT_EDGES,
node : movingShape,
edges : allEdges,
offset : offset
});*/
}
}
},
dockAllShapes: function(shouldDocked){
// Undock all Nodes
for (var i = 0; i < this.dockedNodes.length; i++) {
var docker = this.dockedNodes[i].docker;
docker.setDockedShape( shouldDocked ? this.dockedNodes[i].dockedShape : undefined )
if (docker.getDockedShape()) {
docker.setReferencePoint(this.dockedNodes[i].refPoint);
//docker.update();
}
}
},
addShapeToParent:function addShapeToParent(moveShapes, parents) {
// For every Shape, add this and reset the position
for(var i=0; i < moveShapes.length ;i++){
var currentShape = moveShapes[i].shape;
var currentParent = parents[i];
if((currentShape instanceof ORYX.Core.Node) && (currentShape.parent !== parents[i])) {
// Calc the new position
var unul = parents[i].absoluteXY();
var csul = currentShape.absoluteXY();
var x = csul.x - unul.x;
var y = csul.y - unul.y;
// Add the shape to the new contained shape
parents[i].add(currentShape);
// Add all attached shapes as well
currentShape.getOutgoingShapes((function(shape) {
if(shape instanceof ORYX.Core.Node && !moveShapes.member(shape)) {
parents[i].add(shape);
}
}).bind(this));
// Set the new position
if(currentShape.dockers.length == 1){
var b = currentShape.bounds;
x += b.width()/2;y += b.height()/2
currentShape.dockers.first().bounds.centerMoveTo(x, y);
} else {
currentShape.bounds.moveTo(x, y);
}
}
}
},
selectCurrentShapes: function selectCurrentShapes() {
var canvas = this.facade.getCanvas();
var getShape = function getShape(resourceId) {
var shape = canvas.getChildShapeByResourceId(resourceId);
return shape;
};
var getDocker = function getDocker(shape, dockerId) {
for (var i = 0; i < shape.dockers.length; i++) {
if (shape.dockers[i].id == dockerId) {
docker = shape.dockers[i];
}
}
};
if (this.isLocal()) {
//remove dead shapes from selection
var newSelection = [];
for (var i = 0; i < this.selectedShapes.length; i++) {
var currentShape = this.selectedShapes[i];
if (currentShape instanceof ORYX.Core.Node || currentShape instanceof ORYX.Core.Edge) {
var currentShapeOnCanvas = getShape(currentShape.resourceId);
if (typeof currentShapeOnCanvas !== "undefined") {
newSelection.push(this.selectedShapes[i]);
}
} else if (currentShape instanceof ORYX.Core.Controls.Docker) {
var parentShapeOnCanvas = getShape(currentShape.parent.resourceId);
if (typeof parentShapeOnCanvas === "undefined") {
continue;
} else {
var dockerOnCanvas = getDocker(parentShapeOnCanvas, currentShape.id);
if (typeof dockerOnCanvas !== "undefined") {
newSelection.push(this.selectedShapes[i]);
}
}
}
}
this.facade.setSelection(newSelection);
}
}
});
ORYX.Core.Commands["DragDropResize.UndockEdgeCommand"] = ORYX.Core.AbstractCommand.extend({
construct: function construct(moveShapes, facade) {
arguments.callee.$.construct.call(this, facade);
this.dockers = moveShapes.collect(function(shape){ return shape instanceof ORYX.Core.Controls.Docker ? {docker:shape, dockedShape:shape.getDockedShape(), refPoint:shape.referencePoint} : undefined }).compact();
},
getCommandData: function getCommandData() {
var dockerParents = this.dockers.map(function (docker) {
return docker.parent;
}.bind(this));
var getId = function getId(docker) {
return docker.id;
};
var getResourceId = function getResourceId(shape) {
return shape.resourceId;
};
var cmd = {
"dockerIds": this.dockers.map(getId),
"dockerParentsResourceIds": dockerParents.map(getResourceId)
};
return cmd;
},
createFromCommandData: function createFromCommandData(facade, commandObject) {
var getShape = function getShape(resourceId) {
var shape = facade.getCanvas().getChildShapeByResourceId(resourceId);
return shape;
};
var getDocker = function getDocker(shape, dockerId) {
for (var i = 0; i < shape.dockers.length; i++) {
if (shape.dockers[i].id == dockerId) {
docker = shape.dockers[i];
}
}
};
var moveShapes = [];
for (var i = 0; i < commandObject.dockerIds; i++) {
var shape = getShape(dockerParentsResourceIds[i]);
moveShapes.push(getDocker(shape, dockerIds[i]));
}
return new ORYX.Core.Commands["DragDropResize.UndockEdgeCommand"](moveShapes, facade);
},
getCommandName: function getCommandName() {
return "DragDropResize.UndockEdgeCommand";
},
getAffectedShapes: function getAffectedShapes() {
//only DockerObjects should be affected
return [];
},
execute: function execute() {
this.dockers.each(function(el){
el.docker.setDockedShape(undefined);
})
},
rollback: function execute() {
this.dockers.each(function(el){
el.docker.setDockedShape(el.dockedShape);
el.docker.setReferencePoint(el.refPoint);
//el.docker.update();
})
}
});
/**
* Implements a command class for the Resize Command.
*/
ORYX.Core.Commands["DragDropResize.ResizeCommand"] = ORYX.Core.AbstractCommand.extend({
construct: function construct(shape, newBounds, oldBounds, facade, orientation) {
arguments.callee.$.construct.call(this, facade);
this.orientation = orientation;
this.shape = shape;
this.newBounds = newBounds;
this.oldBounds = oldBounds;
},
getCommandData: function getCommandData() {
var cmd = {
"shapeId": this.shape.resourceId,
"newBounds": {
"width": this.newBounds.b.x - this.newBounds.a.x,
"height": this.newBounds.b.y - this.newBounds.a.y
},
"oldBounds": {
"a": this.oldBounds.upperLeft(),
"b": this.oldBounds.lowerRight()
},
"orientation": this.orientation
};
return cmd;
},
createFromCommandData: function createFromCommandData(facade, commandObject) {
var shape = facade.getCanvas().getChildShapeByResourceId(commandObject.shapeId);
// if shape is undefined (i.e. has been deleted) we cannot instantiate the command
if (typeof shape === 'undefined') {
return undefined;
}
var newBoundsObj = shape.bounds.clone();
newBoundsObj.resize(commandObject.orientation, commandObject.newBounds);
var oldBoundsObj = shape.absoluteBounds().clone();
oldBoundsObj.set(commandObject.oldBounds);
return new ORYX.Core.Commands["DragDropResize.ResizeCommand"](shape, newBoundsObj, oldBoundsObj, facade);
},
getCommandName: function getCommandName() {
return "DragDropResize.ResizeCommand";
},
getDisplayName: function getDisplayName() {
return "Shape resized";
},
getAffectedShapes: function getAffectedShapes() {
return [this.shape];
},
execute: function execute() {
this.shape.bounds.set(this.newBounds.a, this.newBounds.b);
this.update(this.getOffset(this.oldBounds, this.newBounds));
},
rollback: function rollback(){
this.shape.bounds.set(this.oldBounds.a, this.oldBounds.b);
this.update(this.getOffset(this.newBounds, this.oldBounds))
},
getOffset: function getOffset(b1, b2){
return {
x: b2.a.x - b1.a.x,
y: b2.a.y - b1.a.y,
xs: b2.width() / b1.width(),
ys: b2.height() / b1.height()
}
},
update: function update(offset) {
this.shape.getLabels().each(function(label) {
label.changed();
});
var allEdges = [];
allEdges.concat(this.shape.getIncomingShapes());
allEdges.concat(this.shape.getOutgoingShapes());
// Remove all edges which are included in the selection from the list
allEdges.findAll(function(r){ return r instanceof ORYX.Core.Edge }.bind(this));
// Layout all outgoing/incoming edges
/*this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_LAYOUT_EDGES,
node: this.shape,
edges: allEdges,
offset: offset
});*/
this.facade.getCanvas().update();
if (this.isLocal()) {
this.facade.setSelection([this.shape]);
}
this.facade.updateSelection(this.isLocal());
}
});
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if(!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Plugins.BPMN2_0 = {
/**
* Constructor
* @param {Object} Facade: The Facade of the Editor
*/
construct: function(facade){
this.facade = facade;
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_DRAGDOCKER_DOCKED, this.handleDockerDocked.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_PROPWINDOW_PROP_CHANGED, this.handlePropertyChanged.bind(this));
this.facade.registerOnEvent('layout.bpmn2_0.pool', this.handleLayoutPool.bind(this));
this.facade.registerOnEvent('layout.bpmn2_0.subprocess', this.handleSubProcess.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_AFTER_COMMANDS_EXECUTED, this.onCommandExecuted.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LOADED, this.afterLoad.bind(this));
//this.facade.registerOnEvent('layout.bpmn11.lane', this.handleLayoutLane.bind(this));
},
/**
* Force to update every pool
*/
afterLoad: function(){
this.facade.getCanvas().getChildNodes().each(function(shape){
if (shape.getStencil().id().endsWith("Pool")) {
this.handleLayoutPool({
shape: shape
});
}
}.bind(this))
},
onCommandExecuted: function(event) {
if (event.commands.length < 1) {
return;
}
var command = event.commands[0];
if ((typeof command.metadata !== "undefined") && (command.metadata.name === "ShapeRepository.DropCommand")) {
var shape = command.shape;
if ((typeof shape !== "undefined") && (shape.getStencil().idWithoutNs() === "Pool")) {
if(shape.getChildNodes().length === 0) {
// create a lane inside the selected pool
var option = {
type: "http://b3mn.org/stencilset/bpmn2.0#Lane",
position: {x:0,y:0},
namespace: shape.getStencil().namespace(),
parent: shape,
shapeOptions: {
id: shape.id + "_lane",
resourceId: shape.resourceId + "_lane"
}
};
var newLane = this.facade.createShape(option);
newLane.metadata.changedBy.push(command.getCreatorId());
newLane.metadata.changedAt.push(command.getCreatedAt());
newLane.metadata.commands.push(command.getDisplayName());
this.facade.raiseEvent({
'type': ORYX.CONFIG.EVENT_SHAPE_METADATA_CHANGED,
'shape': newLane
});
this.facade.getCanvas().update();
}
}
}
},
/**
* If a pool is selected and contains no lane,
* a lane is created automagically
*/
/*onSelectionChanged: function(event) {
if(event.elements && event.elements.length === 1) {
var shape = event.elements[0];
if(shape.getStencil().idWithoutNs() === "Pool") {
if(shape.getChildNodes().length === 0) {
// create a lane inside the selected pool
var option = {
type: "http://b3mn.org/stencilset/bpmn2.0#Lane",
position: {x:0,y:0},
namespace: shape.getStencil().namespace(),
parent: shape,
shapeOptions: {
id: shape.id + "_lane",
resourceId: shape.resourceId + "_lane"
}
};
this.facade.createShape(option);
this.facade.getCanvas().update();
}
}
}
},*/
hashedSubProcesses: {},
handleSubProcess : function(option) {
var sh = option.shape;
if (!this.hashedSubProcesses[sh.resourceId]) {
this.hashedSubProcesses[sh.resourceId] = sh.bounds.clone();
return;
}
var offset = sh.bounds.upperLeft();
offset.x -= this.hashedSubProcesses[sh.resourceId].upperLeft().x;
offset.y -= this.hashedSubProcesses[sh.resourceId].upperLeft().y;
this.hashedSubProcesses[sh.resourceId] = sh.bounds.clone();
this.moveChildDockers(sh, offset);
},
moveChildDockers: function(shape, offset){
if (!offset.x && !offset.y) {
return;
}
// Get all nodes
shape.getChildNodes(true)
// Get all incoming and outgoing edges
.map(function(node){
return [].concat(node.getIncomingShapes())
.concat(node.getOutgoingShapes())
})
// Flatten all including arrays into one
.flatten()
// Get every edge only once
.uniq()
// Get all dockers
.map(function(edge){
return edge.dockers.length > 2 ?
edge.dockers.slice(1, edge.dockers.length-1) :
[];
})
// Flatten the dockers lists
.flatten()
.each(function(docker){
if (docker.isChanged){ return }
docker.bounds.moveBy(offset);
})
},
/**
* DragDocker.Docked Handler
*
*/
handleDockerDocked: function(options) {
var edge = options.parent;
var edgeSource = options.target;
if(edge.getStencil().id() === "http://b3mn.org/stencilset/bpmn2.0#SequenceFlow") {
var isGateway = edgeSource.getStencil().groups().find(function(group) {
if(group == "Gateways")
return group;
});
if(!isGateway && (edge.properties["oryx-conditiontype"] == "Expression"))
// show diamond on edge source
edge.setProperty("oryx-showdiamondmarker", true);
else
// do not show diamond on edge source
edge.setProperty("oryx-showdiamondmarker", false);
// update edge rendering
//edge.update();
this.facade.getCanvas().update();
}
},
/**
* PropertyWindow.PropertyChanged Handler
*/
handlePropertyChanged: function(option) {
var shapes = option.elements;
var propertyKey = option.key;
var propertyValue = option.value;
var changed = false;
shapes.each(function(shape){
if((shape.getStencil().id() === "http://b3mn.org/stencilset/bpmn2.0#SequenceFlow") &&
(propertyKey === "oryx-conditiontype")) {
if(propertyValue != "Expression")
// Do not show the Diamond
shape.setProperty("oryx-showdiamondmarker", false);
else {
var incomingShapes = shape.getIncomingShapes();
if(!incomingShapes) {
shape.setProperty("oryx-showdiamondmarker", true);
}
var incomingGateway = incomingShapes.find(function(aShape) {
var foundGateway = aShape.getStencil().groups().find(function(group) {
if(group == "Gateways")
return group;
});
if(foundGateway)
return foundGateway;
});
if(!incomingGateway)
// show diamond on edge source
shape.setProperty("oryx-showdiamondmarker", true);
else
// do not show diamond
shape.setProperty("oryx-showdiamondmarker", false);
}
changed = true;
}
});
if(changed) {this.facade.getCanvas().update();}
},
hashedPoolPositions : {},
hashedLaneDepth : {},
hashedBounds : {},
/**
* Handler for layouting event 'layout.bpmn2_0.pool'
* @param {Object} event
*/
handleLayoutPool: function(event){
var pool = event.shape;
var selection = this.facade.getSelection();
var currentShape = selection.first();
currentShape = currentShape || pool;
this.currentPool = pool;
// Check if it is a pool or a lane
if (!(currentShape.getStencil().id().endsWith("Pool") || currentShape.getStencil().id().endsWith("Lane"))) {
return;
}
if (!this.hashedBounds[pool.resourceId]) {
this.hashedBounds[pool.resourceId] = {};
}
// Find all child lanes
var lanes = this.getLanes(pool);
if (lanes.length <= 0) {
return
}
// Show/hide caption regarding the number of lanes
if (lanes.length === 1 && this.getLanes(lanes.first()).length <= 0) {
// TRUE if there is a caption
lanes.first().setProperty("oryx-showcaption", lanes.first().properties["oryx-name"].trim().length > 0);
var rect = lanes.first().node.getElementsByTagName("rect");
rect[0].setAttributeNS(null, "display", "none");
} else {
lanes.invoke("setProperty", "oryx-showcaption", true);
lanes.each(function(lane){
var rect = lane.node.getElementsByTagName("rect");
rect[0].removeAttributeNS(null, "display");
})
}
var allLanes = this.getLanes(pool, true);
var deletedLanes = [];
var addedLanes = [];
// Get all new lanes
var i=-1;
while (++i<allLanes.length) {
if (!this.hashedBounds[pool.resourceId][allLanes[i].resourceId]){
addedLanes.push(allLanes[i])
}
}
if (addedLanes.length > 0){
currentShape = addedLanes.first();
}
// Get all deleted lanes
var resourceIds = $H(this.hashedBounds[pool.resourceId]).keys();
var i=-1;
while (++i<resourceIds.length) {
if (!allLanes.any(function(lane){ return lane.resourceId == resourceIds[i]})){
deletedLanes.push(this.hashedBounds[pool.resourceId][resourceIds[i]]);
selection = selection.without(function(r){ return r.resourceId == resourceIds[i] });
}
}
var height, width;
if (deletedLanes.length > 0 || addedLanes.length > 0) {
// Set height from the pool
height = this.updateHeight(pool);
// Set width from the pool
width = this.adjustWidth(lanes, pool.bounds.width());
pool.update();
}
/**
* Set width/height depending on the pool
*/
else if (pool == currentShape) {
// Set height from the pool
height = this.adjustHeight(lanes, undefined, pool.bounds.height());
// Set width from the pool
width = this.adjustWidth(lanes, pool.bounds.width());
}
/**‚
* Set width/height depending on containing lanes
*/
else {
// Get height and adjust child heights
height = this.adjustHeight(lanes, currentShape);
// Set width from the current shape
width = this.adjustWidth(lanes, currentShape.bounds.width()+(this.getDepth(currentShape,pool)*30));
}
this.setDimensions(pool, width, height);
// Update all dockers
this.updateDockers(allLanes, pool);
this.hashedBounds[pool.resourceId] = {};
var i=-1;
while (++i < allLanes.length) {
// Cache positions
this.hashedBounds[pool.resourceId][allLanes[i].resourceId] = allLanes[i].absoluteBounds();
this.hashedLaneDepth[allLanes[i].resourceId] = this.getDepth(allLanes[i], pool);
this.forceToUpdateLane(allLanes[i]);
}
this.hashedPoolPositions[pool.resourceId] = pool.bounds.clone();
// Update selection
//this.facade.setSelection(selection);
},
forceToUpdateLane: function(lane){
if (lane.bounds.height() !== lane._svgShapes[0].height) {
lane.isChanged = true;
lane.isResized = true;
lane._update();
}
},
getDepth: function(child, parent){
var i=0;
while(child && child.parent && child !== parent){
child = child.parent;
++i
}
return i;
},
updateDepth: function(lane, fromDepth, toDepth){
var xOffset = (fromDepth - toDepth) * 30;
lane.getChildNodes().each(function(shape){
shape.bounds.moveBy(xOffset, 0);
[].concat(children[j].getIncomingShapes())
.concat(children[j].getOutgoingShapes())
})
},
setDimensions: function(shape, width, height){
var isLane = shape.getStencil().id().endsWith("Lane");
// Set the bounds
shape.bounds.set(
isLane ? 30 : shape.bounds.a.x,
shape.bounds.a.y,
width ? shape.bounds.a.x + width - (isLane?30:0) : shape.bounds.b.x,
height ? shape.bounds.a.y + height : shape.bounds.b.y
);
},
setLanePosition: function(shape, y){
shape.bounds.moveTo(30, y);
},
adjustWidth: function(lanes, width) {
// Set width to each lane
(lanes||[]).each(function(lane){
this.setDimensions(lane, width);
this.adjustWidth(this.getLanes(lane), width-30);
}.bind(this));
return width;
},
adjustHeight: function(lanes, changedLane, propagateHeight){
var oldHeight = 0;
if (!changedLane && propagateHeight){
var i=-1;
while (++i<lanes.length){
oldHeight += lanes[i].bounds.height();
}
}
var i=-1;
var height = 0;
// Iterate trough every lane
while (++i<lanes.length){
if (lanes[i] === changedLane) {
// Propagate new height down to the children
this.adjustHeight(this.getLanes(lanes[i]), undefined, lanes[i].bounds.height());
lanes[i].bounds.set({x:30, y:height}, {x:lanes[i].bounds.width()+30, y:lanes[i].bounds.height()+height})
} else if (!changedLane && propagateHeight) {
var tempHeight = (lanes[i].bounds.height() * propagateHeight) / oldHeight;
// Propagate height
this.adjustHeight(this.getLanes(lanes[i]), undefined, tempHeight);
// Set height propotional to the propagated and old height
this.setDimensions(lanes[i], null, tempHeight);
this.setLanePosition(lanes[i], height);
} else {
// Get height from children
var tempHeight = this.adjustHeight(this.getLanes(lanes[i]), changedLane, propagateHeight);
if (!tempHeight) {
tempHeight = lanes[i].bounds.height();
}
this.setDimensions(lanes[i], null, tempHeight);
this.setLanePosition(lanes[i], height);
}
height += lanes[i].bounds.height();
}
return height;
},
updateHeight: function(root){
var lanes = this.getLanes(root);
if (lanes.length == 0){
return root.bounds.height();
}
var height = 0;
var i=-1;
while (++i < lanes.length) {
this.setLanePosition(lanes[i], height);
height += this.updateHeight(lanes[i]);
}
this.setDimensions(root, null, height);
return height;
},
getOffset: function(lane, includePool, pool){
var offset = {x:0,y:0};
/*var parent = lane;
while(parent) {
var offParent = this.hashedBounds[pool.resourceId][parent.resourceId] ||(includePool === true ? this.hashedPoolPositions[parent.resourceId] : undefined);
if (offParent){
var ul = parent.bounds.upperLeft();
var ulo = offParent.upperLeft();
offset.x += ul.x-ulo.x;
offset.y += ul.y-ulo.y;
}
if (parent.getStencil().id().endsWith("Pool")) {
break;
}
parent = parent.parent;
} */
var offset = lane.absoluteXY();
var hashed = this.hashedBounds[pool.resourceId][lane.resourceId] ||(includePool === true ? this.hashedPoolPositions[lane.resourceId] : undefined);
if (hashed) {
offset.x -= hashed.upperLeft().x;
offset.y -= hashed.upperLeft().y;
} else {
return {x:0,y:0}
}
return offset;
},
getNextLane: function(shape){
while(shape && !shape.getStencil().id().endsWith("Lane")){
if (shape instanceof ORYX.Core.Canvas) {
return null;
}
shape = shape.parent;
}
return shape;
},
getParentPool: function(shape){
while(shape && !shape.getStencil().id().endsWith("Pool")){
if (shape instanceof ORYX.Core.Canvas) {
return null;
}
shape = shape.parent;
}
return shape;
},
updateDockers: function(lanes, pool){
var absPool = pool.absoluteBounds();
var oldPool = (this.hashedPoolPositions[pool.resourceId]||absPool).clone();
var i=-1, j=-1, k=-1, l=-1, docker;
var dockers = {};
while (++i < lanes.length) {
if (!this.hashedBounds[pool.resourceId][lanes[i].resourceId]) {
continue;
}
var children = lanes[i].getChildNodes();
var absBounds = lanes[i].absoluteBounds();
var oldBounds = (this.hashedBounds[pool.resourceId][lanes[i].resourceId]||absBounds);
//oldBounds.moveBy((absBounds.upperLeft().x-lanes[i].bounds.upperLeft().x), (absBounds.upperLeft().y-lanes[i].bounds.upperLeft().y));
var offset = this.getOffset(lanes[i], true, pool);
var xOffsetDepth = 0;
var depth = this.getDepth(lanes[i], pool);
if ( this.hashedLaneDepth[lanes[i].resourceId] !== undefined && this.hashedLaneDepth[lanes[i].resourceId] !== depth) {
xOffsetDepth = (this.hashedLaneDepth[lanes[i].resourceId] - depth) * 30;
offset.x += xOffsetDepth;
}
j=-1;
while (++j < children.length) {
if (xOffsetDepth) {
children[j].bounds.moveBy(xOffsetDepth, 0);
}
if (children[j].getStencil().id().endsWith("Subprocess")) {
this.moveChildDockers(children[j], offset);
}
var edges = [].concat(children[j].getIncomingShapes())
.concat(children[j].getOutgoingShapes())
// Remove all edges which are included in the selection from the list
.findAll(function(r){ return r instanceof ORYX.Core.Edge })
k=-1;
while (++k < edges.length) {
if (edges[k].getStencil().id().endsWith("MessageFlow")) {
this.layoutEdges(children[j], [edges[k]], offset);
continue;
}
l=-1;
while (++l < edges[k].dockers.length) {
docker = edges[k].dockers[l];
if (docker.getDockedShape()||docker.isChanged){
continue;
}
pos = docker.bounds.center();
// Check if the modified center included the new position
var isOverLane = oldBounds.isIncluded(pos);
// Check if the original center is over the pool
var isOutSidePool = !oldPool.isIncluded(pos);
var previousIsOverLane = l == 0 ? isOverLane : oldBounds.isIncluded(edges[k].dockers[l-1].bounds.center());
var nextIsOverLane = l == edges[k].dockers.length-1 ? isOverLane : oldBounds.isIncluded(edges[k].dockers[l+1].bounds.center());
// Check if the previous dockers docked shape is from this lane
// Otherwise, check if the docker is over the lane OR is outside the lane
// but the previous/next was over this lane
if (isOverLane){
dockers[docker.id] = {docker: docker, offset:offset};
}
/*else if (l == 1 && edges[k].dockers.length>2 && edges[k].dockers[l-1].isDocked()){
var dockedLane = this.getNextLane(edges[k].dockers[l-1].getDockedShape());
if (dockedLane != lanes[i])
continue;
dockers[docker.id] = {docker: docker, offset:offset};
}
// Check if the next dockers docked shape is from this lane
else if (l == edges[k].dockers.length-2 && edges[k].dockers.length>2 && edges[k].dockers[l+1].isDocked()){
var dockedLane = this.getNextLane(edges[k].dockers[l+1].getDockedShape());
if (dockedLane != lanes[i])
continue;
dockers[docker.id] = {docker: docker, offset:offset};
}
else if (isOutSidePool) {
dockers[docker.id] = {docker: docker, offset:this.getOffset(lanes[i], true, pool)};
}*/
}
}
}
}
// Set dockers
i=-1;
var keys = $H(dockers).keys();
while (++i < keys.length) {
dockers[keys[i]].docker.bounds.moveBy(dockers[keys[i]].offset);
}
},
moveBy: function(pos, offset){
pos.x += offset.x;
pos.y += offset.y;
return pos;
},
getHashedBounds: function(shape){
return this.currentPool && this.hashedBounds[this.currentPool.resourceId][shape.resourceId] ? this.hashedBounds[this.currentPool.resourceId][shape.resourceId] : shape.bounds.clone();
},
/**
* Returns a set on all child lanes for the given Shape. If recursive is TRUE, also indirect children will be returned (default is FALSE)
* The set is sorted with first child the lowest y-coordinate and the last one the highest.
* @param {ORYX.Core.Shape} shape
* @param {boolean} recursive
*/
getLanes: function(shape, recursive){
var lanes = shape.getChildNodes(recursive||false).findAll(function(node) { return (node.getStencil().id() === "http://b3mn.org/stencilset/bpmn2.0#Lane"); });
lanes = lanes.sort(function(a, b){
// Get y coordinate
var ay = Math.round(a.bounds.upperLeft().y);
var by = Math.round(b.bounds.upperLeft().y);
// If equal, than use the old one
if (ay == by) {
ay = Math.round(this.getHashedBounds(a).upperLeft().y);
by = Math.round(this.getHashedBounds(b).upperLeft().y);
}
return ay < by ? -1 : (ay > by ? 1 : 0)
}.bind(this))
return lanes;
}
};
ORYX.Plugins.BPMN2_0 = ORYX.Plugins.AbstractPlugin.extend(ORYX.Plugins.BPMN2_0);
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if (!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Plugins.FarbrauschShadow = Clazz.extend({
excludedTags: Array.from(["defs", "text", "g", "a"]),
construct: function construct(facade) {
this.users = {}; // maps user ids to user objects, which contain colors
this.facade = facade;
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_FARBRAUSCH_NEW_INFOS, this.updateFarbrauschInfos.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_SHAPE_METADATA_CHANGED, this.handleShapeChanged.bind(this));
},
updateFarbrauschInfos: function updateFarbrauschInfos(evt) {
this.users = evt.users;
},
handleShapeChanged: function handleShapeChanged(evt) {
var shape = evt.shape;
if (typeof shape.metadata !== "undefined") {
var color = this.getColorForUserId(shape.getLastChangedBy());
this.setShadow(color, shape);
}
},
getColorForUserId: function getColorForUserId(userId) {
var user = this.users[userId];
if(typeof user === 'undefined' || typeof user.color === 'undefined') {
return ORYX.CONFIG.FARBRAUSCH_DEFAULT_COLOR;
}
return user.color;
},
setShadow: function setShadow(color, shape) {
var defsNode = this.facade.getCanvas().getDefsNode();
// if filter not already defined, define filter
if (!this.existsShadowFilterFor(color, defsNode)) {
this.createShadowFilter(color, defsNode);
}
this.applyShadowFilter(color, shape);
},
existsShadowFilterFor: function existsShadowFilterFor(color, defsNode) {
var filterNode;
var defsNodeChildren = defsNode.children;
// in Chrome .children can return undefined
if (typeof defsNodeChildren !== "undefined") {
for (var i = 0; i < defsNodeChildren.length; i++) {
if (defsNodeChildren[i].id === color) {
filterNode = defsNodeChildren[i];
break;
}
}
}
return (typeof filterNode !== "undefined");
},
createShadowFilter: function createShadowFilter(color, defsNode) {
if (this.isChrome()) {
//filterUnits does not work with chrome properly
filterNode = ORYX.Editor.graft("http://www.w3.org/2000/svg", defsNode,
['filter', {"id": color}]
);
} else {
filterNode = ORYX.Editor.graft("http://www.w3.org/2000/svg", defsNode,
['filter', {"id": color, "filterUnits": "userSpaceOnUse"}]
);
}
ORYX.Editor.graft("http://www.w3.org/2000/svg", filterNode,
['feFlood', {"style": "flood-color:" + color + ";flood-opacity:0.3", "result": "ColoredFilter"}]
);
ORYX.Editor.graft("http://www.w3.org/2000/svg", filterNode,
['feGaussianBlur', {"in": "SourceAlpha", "stdDeviation": "1", "result": "BlurFilter"}]
);
ORYX.Editor.graft("http://www.w3.org/2000/svg", filterNode,
['feComposite', {"in": "ColoredFilter", "in2": "BlurFilter", "operator": "in", "result": "ColoredBlurFilter"}]
);
ORYX.Editor.graft("http://www.w3.org/2000/svg", filterNode,
['feOffset', {"in": "ColoredBlurFilter", "dx": "3", "dy": "3", "result": "FinalShadowFilter"}]
);
ORYX.Editor.graft("http://www.w3.org/2000/svg", filterNode,
['feMerge', {},
['feMergeNode', {"in": "FinalShadowFilter"}],
['feMergeNode', {"in": "SourceGraphic"}]
]
);
},
isChrome: function isChrome() {
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
return true;
} else {
return false;
}
},
applyShadowFilter: function applyShadowFilter(color, shape) {
var svgNode = shape.node;
var meNode = svgNode.getElementsByClassName("me")[0];
var firstChild = meNode.firstChild;
if (typeof firstChild !== "undefined") {
if (shape instanceof ORYX.Core.Node) {
var childNodes = firstChild.childNodes;
for (var i = 0; i < childNodes.length; i++) {
var childNode = childNodes[i];
var tagName = childNode.tagName;
if ((typeof tagName !== "undefined") && !this.excludedTags.include(tagName)) {
childNode.setAttribute("filter", "url(#" + color + ")");
}
}
} else if(shape instanceof ORYX.Core.Edge) {
if (!this.isChrome()) {
//Chrome has problems with setting the bounding box for filters on edges
firstChild.setAttribute("filter", "url(#" + color + ")");
}
}
}
}
});
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if (!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Stacks = {
"undo": [],
"redo": [],
"trash": []
};
ORYX.Plugins.WaveGlobalUndo = Clazz.extend({
facade: undefined,
construct: function(facade){
this.facade = facade;
this.facade.offer({
name: ORYX.I18N.Undo.undo,
description: ORYX.I18N.Undo.undoDesc,
iconCls: 'pw-toolbar-button pw-toolbar-undo',
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: 90,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.doGlobalUndo.bind(this),
group: ORYX.I18N.Undo.group,
isEnabled: function() { return !this.facade.isReadOnlyMode() && ORYX.Stacks.undo.length > 0; }.bind(this),
index: 0,
visibleInViewMode: false
});
this.facade.offer({
name: ORYX.I18N.Undo.redo,
description: ORYX.I18N.Undo.redoDesc,
iconCls: 'pw-toolbar-button pw-toolbar-redo',
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: 89,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}
],
functionality: this.doGlobalRedo.bind(this),
group: ORYX.I18N.Undo.group,
isEnabled: function(){ return !this.facade.isReadOnlyMode() && ORYX.Stacks.redo.length > 0; }.bind(this),
index: 1,
visibleInViewMode: false
});
// Register on event for executing commands --> store all commands in a stack
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_EXECUTE_COMMANDS, this.handleExecuteCommands.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_AFTER_COMMANDS_ROLLBACK, this.handleRollbackCommands.bind(this));
},
handleExecuteCommands: function handleExecuteCommands(evt) {
if (!evt.commands || !evt.commands[0].metadata.putOnStack) {
return;
}
ORYX.Stacks.undo.push(evt.commands);
this.facade.raiseEvent({
'type' : ORYX.CONFIG.EVENT_COMMAND_ADDED_TO_UNDO_STACK,
'commands': evt.commands,
'forceExecution': true
});
ORYX.Stacks.trash = ORYX.Stacks.trash.concat(ORYX.Stacks.redo);
ORYX.Stacks.redo = [];
},
handleRollbackCommands: function handleRollbackCommands(evt) {
if (!evt.commands || !evt.commands[0].metadata.putOnStack) {
return;
}
ORYX.Stacks.undo = this._deleteCommand(evt.commands[0], ORYX.Stacks.undo);
},
_deleteCommand: function _deleteCommand(command, array) {
var returnArray = array;
for (var i = 0; i < array.length; i++) {
var cmdArray = array[i];
var cmd = cmdArray[0];
if (cmd.getCommandId() === command.getCommandId()) {
returnArray = array.without(cmdArray);
break;
}
}
return returnArray;
},
doGlobalUndo: function doGlobalUndo() {
var commandsToUndo = ORYX.Stacks.undo[ORYX.Stacks.undo.length - 1];
var undoCommand = new ORYX.Core.Commands["WaveGlobalUndo.undoCommand"](commandsToUndo, this.facade);
this.facade.executeCommands([undoCommand]);
},
doGlobalRedo: function doGlobalRedo() {
var commandsToRedo = ORYX.Stacks.redo[ORYX.Stacks.redo.length - 1];
var redoCommand = new ORYX.Core.Commands["WaveGlobalUndo.redoCommand"](commandsToRedo, this.facade);
this.facade.executeCommands([redoCommand]);
}
});
ORYX.Core.Commands["WaveGlobalUndo.undoCommand"] = ORYX.Core.AbstractCommand.extend({
construct: function construct(commands, facade) {
arguments.callee.$.construct.call(this, facade, true);
this.metadata.putOnStack = false;
this.commands = commands;
},
execute: function execute() {
var ids = this.commands.collect(function getIds(command) {
return command.getCommandId();
});
if (this._getCommandsByIds(ORYX.Stacks.undo, ids)) {
ORYX.Stacks.undo = ORYX.Stacks.undo.without(this.commands);
ORYX.Stacks.redo.push(this.commands);
this.commands.each(function doRollback(command) {
command.metadata.local = this.isLocal();
command.rollback();
}.bind(this));
this.facade.raiseEvent({
'type' : ORYX.CONFIG.EVENT_COMMAND_MOVED_FROM_UNDO_STACK,
'commands': this.commands,
'forceExecution': true
});
}
},
rollback: function rollback() {
var ids = this.commands.collect(function getIds(command) {
return command.getCommandId();
});
if (this._getCommandsByIds(ORYX.Stacks.redo, ids) || this._getCommandsByIds(ORYX.Stacks.trash, ids)) {
ORYX.Stacks.redo = ORYX.Stacks.redo.without(this.commands);
ORYX.Stacks.trash = ORYX.Stacks.trash.without(this.commands);
ORYX.Stacks.undo.push(this.commands);
this.commands.each(function doExecute(command) {
command.execute();
});
this.facade.raiseEvent({
'type' : ORYX.CONFIG.EVENT_COMMAND_MOVED_FROM_REDO_STACK,
'commands': this.commands,
'forceExecution': true
});
}
},
getAffectedShapes: function getAffectedShapes() {
/*return this.commands.collect(function collectShapes(command) {
return command.getAffectedShapes();
});*/
return [];
},
getCommandName: function getCommandName() {
return "WaveGlobalUndo.undoCommand";
},
_getCommandsByIds: function _getCommandsByIds(stack, ids) {
for (var i = 0; i < stack.length; i++) {
var result = ids.detect(function findCommand(id) {
return stack[i][0].getCommandId() === id;
});
if (result) {
return stack[i];
}
}
return null;
},
createFromCommandData: function createFromCommandData(facade, cmdData) {
var allStacks = ORYX.Stacks.undo.concat(ORYX.Stacks.redo, ORYX.Stacks.trash);
var toUndoCommands = this._getCommandsByIds(allStacks, cmdData.toUndoCommandIds);
// If the command cannot be found on the undo stack, we have a double undo that should not be executed.
var ids = toUndoCommands.collect(function getIds(command) {
return command.getCommandId();
});
var commandsExist = this._getCommandsByIds(ORYX.Stacks.undo, ids);
if (!commandsExist) {
return undefined;
}
return new ORYX.Core.Commands["WaveGlobalUndo.undoCommand"](toUndoCommands, facade);
},
getCommandData: function getCommandData() {
var ids = this.commands.map(function getIds(command) {
return command.getCommandId();
});
var names = this.commands.map(function getIds(command) {
return command.getCommandName();
});
var cmd = {"toUndoCommandIds": ids, "toUndoCommandNames": names};
return cmd;
}
});
ORYX.Core.Commands["WaveGlobalUndo.redoCommand"] = ORYX.Core.AbstractCommand.extend({
construct: function construct(commands, facade) {
arguments.callee.$.construct.call(this, facade);
this.metadata.putOnStack = false;
this.commands = commands;
},
execute: function execute() {
var ids = this.commands.collect(function getIds(command) {
return command.getCommandId();
});
if (this._getCommandsByIds(ORYX.Stacks.redo, ids) || this._getCommandsByIds(ORYX.Stacks.trash, ids)) {
ORYX.Stacks.redo = ORYX.Stacks.redo.without(this.commands);
ORYX.Stacks.trash = ORYX.Stacks.trash.without(this.commands);
ORYX.Stacks.undo.push(this.commands);
this.commands.each(function doExecute(command) {
command.metadata.local = this.isLocal();
command.execute();
}.bind(this));
this.facade.raiseEvent({
'type' : ORYX.CONFIG.EVENT_COMMAND_MOVED_FROM_REDO_STACK,
'commands': this.commands,
'forceExecution': true
});
}
},
rollback: function rollback() {
var ids = this.commands.collect(function getIds(command) {
return command.getCommandId();
});
if (this._getCommandsByIds(ORYX.Stacks.undo, ids)) {
ORYX.Stacks.undo = ORYX.Stacks.undo.without(this.commands);
ORYX.Stacks.redo.push(this.commands);
this.commands.each(function doRollback(command) {
command.rollback();
});
this.facade.raiseEvent({
'type' : ORYX.CONFIG.EVENT_COMMAND_MOVED_FROM_UNDO_STACK,
'commands': this.commands,
'forceExecution': true
});
}
},
getAffectedShapes: function getAffectedShapes() {
return [];
},
getCommandName: function getCommandName() {
return "WaveGlobalUndo.redoCommand";
},
_getCommandsByIds: function _getCommandsByIds(stack, ids) {
for (var i = 0; i < stack.length; i++) {
var result = ids.detect(function findCommand(id) {
return stack[i][0].getCommandId() === id;
});
if (result) {
return stack[i];
}
}
return null;
},
createFromCommandData: function createFromCommandData(facade, cmdData) {
var allStacks = ORYX.Stacks.undo.concat(ORYX.Stacks.redo, ORYX.Stacks.trash);
var toRedoCommands = this._getCommandsByIds(allStacks, cmdData.toRedoCommandIds);
// If the command cannot be found on the redo stack, we have a double redo that should not be executed.
var ids = toRedoCommands.collect(function getIds(command) {
return command.getCommandId();
});
var commandsExist = this._getCommandsByIds(ORYX.Stacks.redo, ids);
if (!commandsExist) {
return undefined;
}
return new ORYX.Core.Commands["WaveGlobalUndo.redoCommand"](toRedoCommands, facade);
},
getCommandData: function getCommandData() {
var ids = this.commands.map(function getIds(command) {
return command.getCommandId();
});
var names = this.commands.map(function getIds(command) {
return command.getCommandName();
});
var cmd = {"toRedoCommandIds": ids, "toRedoCommandNames": names};
return cmd;
}
});
| JavaScript |
/**
* Copyright (c) 2009-2010
* processWave.org (Michael Goderbauer, Markus Goetz, Marvin Killing, Martin
* Kreichgauer, Martin Krueger, Christian Ress, Thomas Zimmermann)
*
* based on oryx-project.org (Martin Czuchra, Nicolas Peters, Daniel Polak,
* Willi Tscheschner, Oliver Kopp, Philipp Giese, Sven Wagner-Boysen, Philipp Berger, Jan-Felix Schwarz)
*
* 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.
**/
if (!ORYX.Plugins) {
ORYX.Plugins = new Object();
}
ORYX.Core.Commands["CanvasResize.CanvasResizeCommand"] = ORYX.Core.AbstractCommand.extend({
construct: function(position, extensionSize, facade) {
arguments.callee.$.construct.call(this, facade);
this.position = position;
this.extensionSize = extensionSize;
this.facade = facade;
},
getAffectedShapes: function getAffectedShapes() {
return [];
},
getCommandName: function getCommandName() {
return "CanvasResize.CanvasResizeCommand";
},
getDisplayName: function getDisplayName() {
return "Canvas resized";
},
getCommandData: function getCommandData() {
var commandData = {
"position": this.position,
"extensionSize": this.extensionSize
};
return commandData;
},
createFromCommandData: function createFromCommandData(facade, commandData) {
var position = commandData.position;
var extensionSize = commandData.extensionSize;
return new ORYX.Core.Commands["CanvasResize.CanvasResizeCommand"](position, extensionSize, facade);
},
resizeCanvas: function(position, extensionSize, facade) {
var canvas = facade.getCanvas();
var b = canvas.bounds;
var scrollNode = facade.getCanvas().getHTMLContainer().parentNode.parentNode;
if( position == "E" || position == "W") {
canvas.setSize({width: (b.width() + extensionSize)*canvas.zoomLevel, height: (b.height())*canvas.zoomLevel});
} else if( position == "S" || position == "N") {
canvas.setSize({width: (b.width())*canvas.zoomLevel, height: (b.height() + extensionSize)*canvas.zoomLevel});
}
if( position === "N" || position === "W") {
var move = position === "N" ? {x: 0, y: extensionSize}: {x: extensionSize, y: 0 };
// Move all children
canvas.getChildNodes(false, function(shape) { shape.bounds.moveBy(move); });
// Move all dockers, when the edge has at least one docked shape
var edges = canvas.getChildEdges().findAll(function(edge) { return edge.getAllDockedShapes().length > 0; });
var dockers = edges.collect(function(edge) { return edge.dockers.findAll(function(docker) { return !docker.getDockedShape(); }); }).flatten();
dockers.each(function(docker) { docker.bounds.moveBy(move); });
// scroll window
if (position === "N")
scrollNode.scrollTop += extensionSize * canvas.zoomLevel;
else if (extensionSize > 0)
scrollNode.scrollLeft += extensionSize * canvas.zoomLevel;
// notify the other plugins that we have moved the shapes
this.facade.raiseEvent({
type : ORYX.CONFIG.EVENT_CANVAS_RESIZE_SHAPES_MOVED,
offsetX : position === "W" ? extensionSize : 0,
offsetY : position === "N" ? extensionSize : 0
});
}
this.facade.raiseEvent({
type : ORYX.CONFIG.EVENT_CANVAS_RESIZED,
bounds : b
});
canvas.update();
//facade.updateSelection();
},
execute: function() {
this.resizeCanvas(this.position, this.extensionSize, this.facade);
this.facade.updateSelection(this.isLocal());
},
rollback: function() {
this.resizeCanvas(this.position, -this.extensionSize, this.facade);
this.facade.updateSelection(this.isLocal());
},
update:function() {
}
});
/**
* This plugin is responsible for resizing the canvas.
* @param {Object} facade The editor plugin facade to register enhancements with.
*/
ORYX.Plugins.CanvasResize = Clazz.extend({
construct: function(facade) {
this.facade = facade;
//new ORYX.Plugins.CanvasResizeButton( this.facade, "N", this.resize.bind(this));
//new ORYX.Plugins.CanvasResizeButton( this.facade, "W", this.resize.bind(this));
new ORYX.Plugins.CanvasResizeButton( this.facade, "E", this.resize.bind(this));
new ORYX.Plugins.CanvasResizeButton( this.facade, "S", this.resize.bind(this));
},
resize: function( position, shrink ) {
var extensionSize = ORYX.CONFIG.CANVAS_RESIZE_INTERVAL;
if(shrink) extensionSize = -extensionSize;
var command = new ORYX.Core.Commands["CanvasResize.CanvasResizeCommand"](position, extensionSize, this.facade);
this.facade.executeCommands([command]);
}
});
ORYX.Plugins.CanvasResizeButton = Clazz.extend({
offsetWidth: 60,
construct: function(facade, position, callback) {
this.facade = facade;
this.position = position;
this.canvas = facade.getCanvas();
this.parentNode = this.canvas.getHTMLContainer().parentNode.parentNode.parentNode;
this.scrollNode = this.parentNode.firstChild;
this.svgRootNode = this.scrollNode.firstChild.firstChild;
this.growButton = ORYX.Editor.graft("http://www.w3.org/1999/xhtml", this.parentNode,
['div',
{ 'class': 'canvas_resize_indicator canvas_resize_indicator_grow' + ' ' + this.position ,
'title': ORYX.I18N.RESIZE.tipGrow + ORYX.I18N.RESIZE[this.position]}]);
this.shrinkButton = ORYX.Editor.graft("http://www.w3.org/1999/xhtml", this.parentNode,
['div',
{ 'class': 'canvas_resize_indicator canvas_resize_indicator_shrink' + ' ' + this.position,
'title':ORYX.I18N.RESIZE.tipShrink + ORYX.I18N.RESIZE[this.position]}]);
// If the mouse move is over the button area, show the button
this.scrollNode.addEventListener(ORYX.CONFIG.EVENT_MOUSEMOVE, this.handleMouseMove.bind(this), false );
this.growButton.addEventListener(ORYX.CONFIG.EVENT_MOUSEOVER, this.showIfNotReadOnly.bind(this), true);
this.shrinkButton.addEventListener(ORYX.CONFIG.EVENT_MOUSEOVER, this.showIfNotReadOnly.bind(this), true);
this.parentNode.addEventListener(ORYX.CONFIG.EVENT_MOUSEOUT, function(event) { this.hideButtons(); }.bind(this) , true );
// Hide the button initialy
this.hideButtons();
// Add the callbacks
var growButtonCallback = this.getGrowButtonCallback(callback);
this.growButton.addEventListener('click', growButtonCallback, true);
var shrinkButtonCallback = this.getShrinkButtonCallback(callback);
this.shrinkButton.addEventListener('click', shrinkButtonCallback, true);
},
isOverOffset: function isOverOffset(event) {
if (event.target != this.parentNode && event.target != this.scrollNode && event.target != this.scrollNode.firstChild && event.target != this.svgRootNode) {
return false;
}
//if(inCanvas) {offSetWidth=30}else{offSetWidth=30*2}
//Safari work around
var X = event.layerX;
var Y = event.layerY;
if (X - this.scrollNode.scrollLeft < 0 || Ext.isSafari) {
X += this.scrollNode.scrollLeft;
}
if (Y - this.scrollNode.scrollTop < 0 || Ext.isSafari) {
Y += this.scrollNode.scrollTop;
}
if (this.position === "N") {
return Y < this.offsetWidth + this.scrollNode.firstChild.offsetTop;
} else if (this.position === "W") {
return X < this.offsetWidth + this.scrollNode.firstChild.offsetLeft;
} else if (this.position === "E") {
var offsetRight = this.scrollNode.offsetWidth - (this.scrollNode.firstChild.offsetLeft + this.scrollNode.firstChild.offsetWidth);
if (offsetRight < 0) {
offsetRight = 0;
}
return X > this.scrollNode.scrollWidth - offsetRight - this.offsetWidth;
} else if (this.position === "S") {
var offsetDown = this.scrollNode.offsetHeight - (this.scrollNode.firstChild.offsetTop + this.scrollNode.firstChild.offsetHeight);
if (offsetDown < 0) {
offsetDown = 0;
}
return Y > this.scrollNode.scrollHeight - offsetDown - this.offsetWidth;
}
return false;
},
showButtons: function showButtons() {
this.growButton.show();
var x1, y1, x2, y2;
try {
var bb = this.canvas.getRootNode().childNodes[1].getBBox();
x1 = bb.x;
y1 = bb.y;
x2 = bb.x + bb.width;
y2 = bb.y + bb.height;
} catch(e) {
this.canvas.getChildShapes(true).each(function(shape) {
var absBounds = shape.absoluteBounds();
var ul = absBounds.upperLeft();
var lr = absBounds.lowerRight()
if(x1 == undefined) {
x1 = ul.x;
y1 = ul.y;
x2 = lr.x;
y2 = lr.y;
} else {
x1 = Math.min(x1, ul.x);
y1 = Math.min(y1, ul.y);
x2 = Math.max(x2, lr.x);
y2 = Math.max(y2, lr.y);
}
});
}
var w = this.canvas.bounds.width();
var h = this.canvas.bounds.height();
var isEmpty = this.canvas.getChildNodes().size() === 0;
if (this.position === "N" && (y1 > ORYX.CONFIG.CANVAS_RESIZE_INTERVAL || (isEmpty && h > ORYX.CONFIG.CANVAS_RESIZE_INTERVAL))) {
this.shrinkButton.show();
} else if (this.position === "E" && (w - x2) > ORYX.CONFIG.CANVAS_RESIZE_INTERVAL) {
this.shrinkButton.show();
} else if (this.position === "S" && (h - y2) > ORYX.CONFIG.CANVAS_RESIZE_INTERVAL) {
this.shrinkButton.show();
} else if (this.position === "W" && (x1 > ORYX.CONFIG.CANVAS_RESIZE_INTERVAL || (isEmpty && w > ORYX.CONFIG.CANVAS_RESIZE_INTERVAL))) {
this.shrinkButton.show();
} else {
this.shrinkButton.hide();
}
},
hideButtons: function hideButtons() {
this.growButton.hide();
this.shrinkButton.hide();
},
handleMouseMove: function handleMouseMove(event) {
if (this.isOverOffset(event) && !this.facade.isReadOnlyMode()) {
this.showButtons();
} else {
this.hideButtons();
}
},
showIfNotReadOnly: function showIfNotReadOnly() {
if (!this.facade.isReadOnlyMode()) {
this.showButtons();
}
},
getGrowButtonCallback: function getGrowButtonCallback(buttonCallback) {
return function growButtonCallback() {
buttonCallback(this.position);
this.showButtons();
}.bind(this);
},
getShrinkButtonCallback: function getShrinkButtonCallback(buttonCallback) {
return function shrinkButtonCallback() {
buttonCallback(this.position, true);
this.showButtons();
}.bind(this);
}
});
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.