code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/**
* @file
* @author Danny Bickson
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* Tensor factorization with the Alternative Least Squares (ALS) algorithm.
* Algorithm is described in: Tensor Decompositions, Alternating Least Squares and other Tales. P. Comon, X. Luciani and A. L. F. de Almeida. Special issue, Journal of Chemometrics. In memory of R. Harshman.
* August 16, 2009
*
*/
#include "common.hpp"
#include "eigen_wrapper.hpp"
double lambda = 0.065;
bool is_user(vid_t id){ return id < M; }
bool is_item(vid_t id){ return id >= M && id < N; }
bool is_time(vid_t id){ return id >= M+N; }
struct vertex_data {
vec pvec;
vertex_data() {
pvec = zeros(D);
}
void set_val(int index, float val){
pvec[index] = val;
}
float get_val(int index){
return pvec[index];
}
};
struct edge_data {
double weight;
double time;
edge_data() { weight = time = 0; }
edge_data(double weight, double time) : weight(weight), time(time) { }
};
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vertex_data VertexDataType;
typedef edge_data EdgeDataType; // Edges store the "rating" of user->movie pair
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
graphchi_engine<VertexDataType, EdgeDataType> * pvalidation_engine = NULL;
std::vector<vertex_data> latent_factors_inmem;
#include "io.hpp"
#include "rmse.hpp"
#include "rmse_engine4.hpp"
float als_tensor_predict(const vertex_data& user,
const vertex_data& movie,
const float rating,
double & prediction,
void * extra){
vertex_data * time_node = (vertex_data*)extra;
assert(time_node != NULL && time_node->pvec.size() == D);
prediction = dot3(user.pvec, movie.pvec, time_node->pvec);
//truncate prediction to allowed values
prediction = std::min((double)prediction, maxval);
prediction = std::max((double)prediction, minval);
//return the squared error
float err = rating - prediction;
assert(!std::isnan(err));
return err*err;
}
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct ALSVerticesInMemProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/*
* Vertex update function - computes the least square step
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
vertex_data & vdata = latent_factors_inmem[vertex.id()];
mat XtX = mat::Zero(D, D);
vec Xty = vec::Zero(D);
bool compute_rmse = is_user(vertex.id());
// Compute XtX and Xty (NOTE: unweighted)
for(int e=0; e < vertex.num_edges(); e++){
float observation = vertex.edge(e)->get_data().weight;
uint time = (uint)vertex.edge(e)->get_data().time;
assert(time >= 0 && time < M+N+K);
assert(time != vertex.id());
vertex_data & nbr_latent = latent_factors_inmem[vertex.edge(e)->vertex_id()];
vertex_data & time_node = latent_factors_inmem[time];
assert(time != vertex.id() && time != vertex.edge(e)->vertex_id());
vec XY = nbr_latent.pvec.cwiseProduct(time_node.pvec);
Xty += XY * observation;
XtX.triangularView<Eigen::Upper>() += XY * XY.transpose();
if (compute_rmse) {
double prediction;
rmse_vec[omp_get_thread_num()] += als_tensor_predict(vdata, nbr_latent, observation, prediction, (void*)&time_node);
}
}
double regularization = lambda;
if (regnormal)
lambda *= vertex.num_edges();
for(int i=0; i < D; i++) XtX(i,i) += regularization;
// Solve the least squares problem with eigen using Cholesky decomposition
vdata.pvec = XtX.selfadjointView<Eigen::Upper>().ldlt().solve(Xty);
}
/**
* Called before an iteration is started.
*/
void before_iteration(int iteration, graphchi_context &gcontext) {
reset_rmse(gcontext.execthreads);
}
/**
* Called after an iteration has finished.
*/
void after_iteration(int iteration, graphchi_context &gcontext) {
training_rmse(iteration, gcontext);
run_validation4(pvalidation_engine, gcontext);
}
};
void output_als_result(std::string filename) {
MMOutputter_mat<vertex_data> user_mat(filename + "_U.mm", 0, M, "This file contains tensor-ALS output matrix U. In each row D factors of a single user node.", latent_factors_inmem);
MMOutputter_mat<vertex_data> item_mat(filename + "_V.mm", M ,M+N, "This file contains tensor-ALS output matrix V. In each row D factors of a single item node.", latent_factors_inmem);
MMOutputter_mat<vertex_data> time_mat(filename + "_T.mm", M+N ,M+N+K, "This file contains tensor-ALS output matrix T. In each row D factors of a single time node.", latent_factors_inmem);
logstream(LOG_INFO) << "tensor - ALS output files (in matrix market format): " << filename << "_U.mm" <<
", " << filename + "_V.mm " << filename + "_T.mm" << std::endl;
}
int main(int argc, const char ** argv) {
print_copyright();
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("als-tensor-inmemory-factors");
lambda = get_option_float("lambda", 0.065);
parse_command_line_args();
parse_implicit_command_line();
/* Preprocess data if needed, or discover preprocess files */
int nshards = convert_matrixmarket4<edge_data>(training, true);
init_feature_vectors<std::vector<vertex_data> >(M+N+K, latent_factors_inmem, !load_factors_from_file);
if (validation != ""){
int vshards = convert_matrixmarket4<EdgeDataType>(validation, true, M==N, VALIDATION);
init_validation_rmse_engine<VertexDataType, EdgeDataType>(pvalidation_engine, vshards, &als_tensor_predict, false, true, 1);
}
if (load_factors_from_file){
load_matrix_market_matrix(training + "_U.mm", 0, D);
load_matrix_market_matrix(training + "_V.mm", M, D);
load_matrix_market_matrix(training + "_T.mm", M+N, D);
}
/* Run */
ALSVerticesInMemProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m);
set_engine_flags(engine);
pengine = &engine;
engine.run(program, niters);
/* Output test predictions in matrix-market format */
output_als_result(training);
test_predictions3(&als_tensor_predict);
/* Report execution metrics */
if (!quiet)
metrics_report(m);
return 0;
}
| 09jijiangwen-download | toolkits/collaborative_filtering/als_tensor.cpp | C++ | asf20 | 7,287 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Danny Bickson, CMU
* Code for computing ranking metrics
*
* */
#include <algorithm>
#include "eigen_wrapper.hpp"
/* average_precision_at_k code based on Ben Hamer's Kaggle code:
* https://github.com/benhamner/Metrics/blob/master/MATLAB/metrics/averagePrecisionAtK.m
*/
double average_precision_at_k(vec & predictions, int prediction_size, vec & actual, int actual_size, int k){
double score = 0;
int num_hits = 0;
vec sorted_actual = actual;
actual_size = std::min(k, actual_size);
std::sort(sorted_actual.data(), sorted_actual.data()+ actual_size);
for (int i=0; i < std::min((int)predictions.size(), k); i++){
if (std::binary_search(sorted_actual.data(), sorted_actual.data()+ actual_size, predictions[i])){
num_hits++;
score += num_hits / (i+1.0);
}
}
score /= (double)std::min(actual_size, k);
return score;
}
| 09jijiangwen-download | toolkits/collaborative_filtering/metrics.hpp | C++ | asf20 | 1,538 |
#ifndef __CF_UTILS__
#define __CF_UTILS__
#include <omp.h>
#include <stdio.h>
#include <iostream>
int number_of_omp_threads(){
int num_threads = 0;
int id;
#pragma omp parallel private(id)
{
id = omp_get_thread_num();
if (id == 0)
num_threads = omp_get_num_threads();
}
return num_threads;
}
struct in_file{
FILE * outf;
in_file(std::string fname) {
outf = fopen(fname.c_str(), "r");
if (outf == NULL){
std::cerr<<"Failed to open file: " << fname << std::endl;
exit(1);
}
}
~in_file() {
if (outf != NULL) fclose(outf);
}
};
struct out_file{
FILE * outf;
out_file(const std::string fname){
outf = fopen(fname.c_str(), "w");
}
~out_file(){
if (outf != NULL) fclose(outf);
}
};
/*
template<typename T1>
void load_map_from_txt_file(T1 & map, const std::string filename, bool gzip, int fields){
logstream(LOG_INFO)<<"loading map from txt file: " << filename << std::endl;
gzip_in_file fin(filename, gzip);
char linebuf[1024];
char saveptr[1024];
bool mm_header = false;
int line = 0;
char * pch2 = NULL;
while (!fin.get_sp().eof() && fin.get_sp().good()){
fin.get_sp().getline(linebuf, 10000);
if (fin.get_sp().eof())
break;
if (linebuf[0] == '%'){
logstream(LOG_INFO)<<"Detected matrix market header: " << linebuf << " skipping" << std::endl;
mm_header = true;
continue;
}
if (mm_header){
mm_header = false;
continue;
}
char *pch = strtok_r(linebuf," \r\n\t",(char**)&saveptr);
if (!pch){
logstream(LOG_FATAL) << "Error when parsing file: " << filename << ":" << line <<std::endl;
}
if (fields == 2){
pch2 = strtok_r(NULL,"\n",(char**)&saveptr);
if (!pch2)
logstream(LOG_FATAL) << "Error when parsing file: " << filename << ":" << line <<std::endl;
}
if (fields == 1)
map[boost::lexical_cast<std::string>(line)] = pch;
else map[pch] = pch2;
line++;
}
logstream(LOG_INFO)<<"Map size is: " << map.size() << std::endl;
}*/
#endif
| 09jijiangwen-download | toolkits/collaborative_filtering/util.hpp | C++ | asf20 | 2,174 |
#!/bin/sh
# script for merging the output of the rating application into a single sorted file
# Written By Danny Bickson, CMU
if [ $# -ne 1 ]; then
echo "Usage: $0 <training file name>"
exit 1
fi
TRAINING=$1
pwd
FOUND=0
rm -f *.sorted
for i in `ls ${TRAINING}.out[0-9]*`
do
FOUND=1
echo "Sorting output file $i"
sort -r -g -k 1,1 -k 2,2 -k 3,3 $i > $i.sorted
done
if [ $FOUND -eq 0 ]; then
echo "Error: No input file found. Run itemcf again!"
exit
fi
echo "Merging sorted files:"
sort -r -g -k 1,1 -k 2,2 -k 3,3 -m `dirname $TRAINING`/*.sorted > $TRAINING-topk
if [ $? -ne 0 ]; then
echo "Error: Failed to merge!"
exit 1
fi
echo "File written: $TRAINING-topk"
echo "Total lines: `wc -l $TRAINING-topk | awk '{print $1}'`"
rm -f `dirname $TRAINING`/*.sorted
| 09jijiangwen-download | toolkits/collaborative_filtering/topk.sh | Shell | asf20 | 779 |
/**
* @file
* @author Danny Bickson
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* Matrix factorization with the Bias Stochastic Gradient Descent (BIASSGD) algorithm.
* Algorithm is described in the paper:
* Y. Koren. Factorization Meets the Neighborhood: a Multifaceted Collaborative Filtering Model. ACM SIGKDD 2008. Equation (5).
*
*/
#include "common.hpp"
#include "eigen_wrapper.hpp"
double biassgd_lambda = 1e-3; //sgd step size
double biassgd_gamma = 1e-3; //sgd regularization
double biassgd_step_dec = 0.9; //sgd step decrement
#define BIAS_POS -1
struct vertex_data {
vec pvec; //storing the feature vector
double bias;
vertex_data() {
pvec = zeros(D);
bias = 0;
}
void set_val(int index, float val){
if (index == BIAS_POS)
bias = val;
else pvec[index] = val;
}
float get_val(int index){
if (index== BIAS_POS)
return bias;
else return pvec[index];
}
};
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vertex_data VertexDataType;
typedef float EdgeDataType; // Edges store the "rating" of user->movie pair
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
graphchi_engine<VertexDataType, EdgeDataType> * pvalidation_engine = NULL;
std::vector<vertex_data> latent_factors_inmem;
#include "rmse.hpp"
#include "rmse_engine.hpp"
#include "io.hpp"
/** compute a missing value based on bias-SGD algorithm */
float bias_sgd_predict(const vertex_data& user,
const vertex_data& movie,
const float rating,
double & prediction,
void * extra = NULL){
prediction = globalMean + user.bias + movie.bias + dot_prod(user.pvec, movie.pvec);
//truncate prediction to allowed values
prediction = std::min((double)prediction, maxval);
prediction = std::max((double)prediction, minval);
//return the squared error
float err = rating - prediction;
if (std::isnan(err))
logstream(LOG_FATAL)<<"Got into numerical errors. Try to decrease step size using bias-SGD command line arugments)" << std::endl;
return err*err;
}
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct BIASSGDVerticesInMemProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Called before an iteration is started.
*/
void before_iteration(int iteration, graphchi_context &gcontext) {
reset_rmse(gcontext.execthreads);
}
/**
* Called after an iteration has finished.
*/
void after_iteration(int iteration, graphchi_context &gcontext) {
biassgd_gamma *= biassgd_step_dec;
training_rmse(iteration, gcontext);
run_validation(pvalidation_engine, gcontext);
}
/**
* Vertex update function.
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
if ( vertex.num_outedges() > 0){
vertex_data & user = latent_factors_inmem[vertex.id()];
for(int e=0; e < vertex.num_edges(); e++) {
float observation = vertex.edge(e)->get_data();
vertex_data & movie = latent_factors_inmem[vertex.edge(e)->vertex_id()];
double estScore = 0;
rmse_vec[omp_get_thread_num()] += bias_sgd_predict(user, movie, observation, estScore);
double err = observation - estScore;
if (std::isnan(err) || std::isinf(err))
logstream(LOG_FATAL)<<"BIASSGD got into numerical error. Please tune step size using --biassgd_gamma and biassgd_lambda" << std::endl;
user.bias += biassgd_gamma*(err - biassgd_lambda* user.bias);
movie.bias += biassgd_gamma*(err - biassgd_lambda* movie.bias);
//NOTE: the following code is not thread safe, since potentially several
//user nodes may update this item gradient vector concurrently. However in practice it
//did not matter in terms of accuracy on a multicore machine.
//if you like to defend the code, you can define a global variable
//mutex mymutex;
//
//and then do: mymutex.lock()
movie.pvec += biassgd_gamma*(err*user.pvec - biassgd_lambda*movie.pvec);
//here add: mymutex.unlock();
user.pvec += biassgd_gamma*(err*movie.pvec - biassgd_lambda*user.pvec);
}
}
}
};
void output_biassgd_result(std::string filename){
MMOutputter_mat<vertex_data> user_output(filename + "_U.mm", 0, M, "This file contains bias-SGD output matrix U. In each row D factors of a single user node.", latent_factors_inmem);
MMOutputter_mat<vertex_data> item_output(filename + "_V.mm", M, M+N , "This file contains bias-SGD output matrix V. In each row D factors of a single item node.", latent_factors_inmem);
MMOutputter_vec<vertex_data> user_bias_vec(filename + "_U_bias.mm", 0, M, BIAS_POS, "This file contains bias-SGD output bias vector. In each row a single user bias.", latent_factors_inmem);
MMOutputter_vec<vertex_data> item_bias_vec(filename + "_V_bias.mm",M ,M+N, BIAS_POS, "This file contains bias-SGD output bias vector. In each row a single item bias.", latent_factors_inmem);
MMOutputter_scalar gmean(filename + "_global_mean.mm", "This file contains SVD++ global mean which is required for computing predictions.", globalMean);
logstream(LOG_INFO) << "SVDPP output files (in matrix market format): " << filename << "_U.mm" <<
", " << filename + "_V.mm, " << filename << "_U_bias.mm, " << filename << "_V_bias.mm, " << filename << "_global_mean.mm" << std::endl;
}
int main(int argc, const char ** argv) {
print_copyright();
//* GraphChi initialization will read the command line arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("biassgd-inmemory-factors");
biassgd_lambda = get_option_float("biassgd_lambda", 1e-3);
biassgd_gamma = get_option_float("biassgd_gamma", 1e-3);
biassgd_step_dec = get_option_float("biassgd_step_dec", 0.9);
parse_command_line_args();
parse_implicit_command_line();
/* Preprocess data if needed, or discover preprocess files */
int nshards = convert_matrixmarket<EdgeDataType>(training, NULL, 0, 0, 3, TRAINING, false);
init_feature_vectors<std::vector<vertex_data> >(M+N, latent_factors_inmem, !load_factors_from_file);
if (validation != ""){
int vshards = convert_matrixmarket<EdgeDataType>(validation, NULL, 0, 0, 3, VALIDATION, false);
init_validation_rmse_engine<VertexDataType, EdgeDataType>(pvalidation_engine, vshards, &bias_sgd_predict);
}
/* load initial state from disk (optional) */
if (load_factors_from_file){
load_matrix_market_matrix(training + "_U.mm", 0, D);
load_matrix_market_matrix(training + "_V.mm", M, D);
vec user_bias = load_matrix_market_vector(training +"_U_bias.mm", false, true);
assert(user_bias.size() == M);
vec item_bias = load_matrix_market_vector(training +"_V_bias.mm", false, true);
assert(item_bias.size() == N);
for (uint i=0; i<M+N; i++){
latent_factors_inmem[i].bias = ((i<M)?user_bias[i] : item_bias[i-M]);
}
vec gm = load_matrix_market_vector(training + "_global_mean.mm", false, true);
globalMean = gm[0];
}
/* Run */
BIASSGDVerticesInMemProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m);
set_engine_flags(engine);
pengine = &engine;
engine.run(program, niters);
/* Output latent factor matrices in matrix-market format */
output_biassgd_result(training);
test_predictions(&bias_sgd_predict);
/* Report execution metrics */
if (!quiet)
metrics_report(m);
return 0;
}
| 09jijiangwen-download | toolkits/collaborative_filtering/biassgd.cpp | C++ | asf20 | 8,467 |
#ifndef DEF_IOHPP
#define DEF_IOHPP
/**
* @file
* @author Danny Bickson
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "types.hpp"
#include "implicit.hpp"
/*
* open a file and verify open success
*/
FILE * open_file(const char * name, const char * mode, bool optional = false){
FILE * f = fopen(name, mode);
if (f == NULL && !optional){
perror("fopen failed");
logstream(LOG_FATAL) <<" Failed to open file" << name << std::endl;
}
return f;
}
void set_matcode(MM_typecode & matcode, bool sparse = false){
mm_initialize_typecode(&matcode);
mm_set_matrix(&matcode);
if (sparse)
mm_set_coordinate(&matcode);
else
mm_set_array(&matcode);
mm_set_real(&matcode);
}
void read_matrix_market_banner_and_size(FILE * f, MM_typecode & matcode, uint & Me, uint & Ne, size_t & nz, const std::string & filename){
if (mm_read_banner(f, &matcode) != 0)
logstream(LOG_FATAL) << "Could not process Matrix Market banner. File: " << filename << std::endl;
/* This is how one can screen matrix types if their application */
/* only supports a subset of the Matrix Market data types. */
if (mm_is_complex(matcode) || !mm_is_sparse(matcode))
logstream(LOG_FATAL) << "Sorry, this application does not support complex values and requires a sparse matrix." << std::endl;
/* find out size of sparse matrix .... */
if (mm_read_mtx_crd_size(f, &Me, &Ne, &nz) != 0) {
logstream(LOG_FATAL) << "Failed reading matrix size: error" << std::endl;
}
}
void detect_matrix_size(std::string filename, FILE *&f, uint &_M, uint &_N, size_t & nz, uint nodes = 0, size_t edges = 0, int type = TRAINING){
MM_typecode matcode;
bool info_file = false;
if (nodes == 0 && edges == 0){
FILE * ff = NULL;
/* auto detect presence of file named base_filename.info to find out matrix market size */
if ((ff = fopen((filename + ":info").c_str(), "r")) != NULL) {
info_file = true;
read_matrix_market_banner_and_size(ff, matcode, _M, _N, nz, filename + ":info");
fclose(ff);
}
}
if ((f = fopen(filename.c_str(), "r")) == NULL) {
if (type == VALIDATION){
std::cout<<std::endl;
return; //missing validaiton data
}
else logstream(LOG_FATAL)<<"Failed to open input file: " << filename << std::endl;
}
if (!info_file && nodes == 0 && edges == 0){
read_matrix_market_banner_and_size(f, matcode, _M, _N, nz, filename);
}
else if (nodes > 0 && edges > 0){
_M = _N = nodes;
nz = edges;
}
}
void read_global_mean(std::string base_filename, int type){
FILE * inf = fopen((base_filename + ".gm").c_str(), "r");
int rc;
if (type == TRAINING)
rc = fscanf(inf,"%d\n%d\n%ld\n%lg\n%d\n",&M, &N, &L, &globalMean, &K);
else rc = fscanf(inf,"%d\n%d\n%ld\n%lg\n%d\n",&Me, &Ne, &Le, &globalMean2, &K);
if (rc != 5)
logstream(LOG_FATAL)<<"Failed to read global mean from file" << base_filename << ".gm" << std::endl;
fclose(inf);
if (type == TRAINING)
logstream(LOG_INFO) << "Opened matrix size: " <<M << " x " << N << " edges: " << L << " Global mean is: " << globalMean << " time bins: " << K << " Now creating shards." << std::endl;
else
logstream(LOG_INFO) << "Opened VLIDATION matrix size: " <<Me << " x " << Ne << " edges: " << Le << " Global mean is: " << globalMean2 << " time bins: " << K << " Now creating shards." << std::endl;
}
void write_global_mean(std::string base_filename, int type){
FILE * outf = fopen((base_filename + ".gm").c_str(), "w");
if (type == TRAINING)
fprintf(outf, "%d\n%d\n%ld\n%lg\n%d\n", M, N, L, globalMean, K);
else
fprintf(outf, "%d\n%d\n%ld\n%lg\n%d\n", Me, Ne, Le, globalMean2, K);
fclose(outf);
}
void compute_matrix_size(size_t nz, int type){
if (kfold_cross_validation > 0){
if (type == TRAINING)
L = (1 - 1.0/(double)kfold_cross_validation)*nz;
else Le = (1.0/(double)kfold_cross_validation)*nz;
}
else {
if (type == TRAINING)
L = nz;
else Le = nz;
}
if (type == TRAINING)
logstream(LOG_INFO) << "Starting to read matrix-market input. Matrix dimensions: "
<< M << " x " << N << ", non-zeros: " << L << std::endl;
else
logstream(LOG_INFO) << "Starting to read VALIDATION matrix-market input. Matrix dimensions: "
<< Me << " x " << Ne << ", non-zeros: " << Le << std::endl;
}
/** decide on training vs. validation split in case of k fold cross validation */
bool decide_if_edge_is_active(size_t i, int type){
bool active_edge = true;
if (type == TRAINING){
if (kfold_cross_validation > 0 && (((int)(i % kfold_cross_validation)) == kfold_cross_validation_index))
active_edge = false;
}
else if (type == VALIDATION){
if (kfold_cross_validation > 0){
if ((((int)(i % kfold_cross_validation)) == kfold_cross_validation_index))
active_edge = true;
else active_edge = false;
}
}
return active_edge;
}
template<typename vertex_data>
struct MMOutputter_vec{
MMOutputter_vec(std::string fname, uint start, uint end, int index, std::string comment, std::vector<vertex_data> & latent_factors_inmem) {
MM_typecode matcode;
set_matcode(matcode, R_output_format);
FILE * outf = open_file(fname.c_str(), "w");
mm_write_banner(outf, matcode);
if (comment != "")
fprintf(outf, "%%%s\n", comment.c_str());
if (R_output_format)
mm_write_mtx_crd_size(outf, end-start, 1, end-start);
else
mm_write_mtx_array_size(outf, end-start, 1);
for (uint i=start; i< end; i++)
if (R_output_format)
fprintf(outf, "%d %d %12.8g\n", i-start+input_file_offset, 1, latent_factors_inmem[i].get_val(index));
else
fprintf(outf, "%1.12e\n", latent_factors_inmem[i].get_val(index));
fclose(outf);
}
};
template<typename vertex_data>
struct MMOutputter_mat{
MMOutputter_mat(std::string fname, uint start, uint end, std::string comment, std::vector<vertex_data> & latent_factors_inmem, int size = 0) {
assert(start < end);
MM_typecode matcode;
set_matcode(matcode, R_output_format);
FILE * outf = open_file(fname.c_str(), "w");
mm_write_banner(outf, matcode);
if (comment != "")
fprintf(outf, "%%%s\n", comment.c_str());
int actual_Size = size > 0 ? size : latent_factors_inmem[start].pvec.size();
if (R_output_format)
mm_write_mtx_crd_size(outf, end-start, actual_Size, (end-start)*actual_Size);
else
mm_write_mtx_array_size(outf, end-start, actual_Size);
for (uint i=start; i < end; i++){
for(int j=0; j < actual_Size; j++) {
if (R_output_format)
fprintf(outf, "%d %d %12.8g\n", i-start+input_file_offset, j+input_file_offset, latent_factors_inmem[i].get_val(j));
else
fprintf(outf, "%1.12e\n", latent_factors_inmem[i].get_val(j));
}
}
fclose(outf);
}
};
struct MMOutputter_scalar {
MMOutputter_scalar(std::string fname, std::string comment, double val) {
MM_typecode matcode;
set_matcode(matcode, R_output_format);
FILE * outf = open_file(fname.c_str(), "w");
mm_write_banner(outf, matcode);
if (comment != "")
fprintf(outf, "%%%s\n", comment.c_str());
if (R_output_format)
mm_write_mtx_crd_size(outf, 1, 1, 1);
else
mm_write_mtx_array_size(outf, 1, 1);
if (R_output_format)
fprintf(outf, "%d %d %12.8g\n", 1, 1, val);
else
fprintf(outf, "%1.12e\n", val);
fclose(outf);
}
};
/**
* Create a bipartite graph from a matrix. Each row corresponds to vertex
* with the same id as the row number (0-based), but vertices correponsing to columns
* have id + num-rows.
* Line format of the type
* [user] [item] [time/weight] [rating]
*/
template <typename als_edge_type>
int convert_matrixmarket4(std::string base_filename, bool add_time_edges = false, bool square = false, int type = TRAINING, int matlab_time_offset = 1) {
// Note, code based on: http://math.nist.gov/MatrixMarket/mmio/c/example_read.c
FILE *f = NULL;
size_t nz;
/**
* Create sharder object
*/
int nshards;
if ((nshards = find_shards<als_edge_type>(base_filename, get_option_string("nshards", "auto")))) {
if (check_origfile_modification_earlier<als_edge_type>(base_filename, nshards)) {
logstream(LOG_INFO) << "File " << base_filename << " was already preprocessed, won't do it again. " << std::endl;
read_global_mean(base_filename, type);
}
return nshards;
}
sharder<als_edge_type> sharderobj(base_filename);
sharderobj.start_preprocessing();
detect_matrix_size(base_filename, f, type == TRAINING? M:Me, type == TRAINING? N:Ne, nz);
if (f == NULL){
if (type == VALIDATION){
logstream(LOG_INFO)<< "Did not find validation file: " << base_filename << std::endl;
return -1;
}
else if (type == TRAINING)
logstream(LOG_FATAL)<<"Failed to open training input file: " << base_filename << std::endl;
}
compute_matrix_size(nz, type);
uint I, J;
double val, time;
bool active_edge = true;
if (!sharderobj.preprocessed_file_exists()) {
for (size_t i=0; i<nz; i++)
{
int rc = fscanf(f, "%d %d %lg %lg\n", &I, &J, &time, &val);
if (rc != 4)
logstream(LOG_FATAL)<<"Error when reading input file - line " << i << std::endl;
if (time < 0)
logstream(LOG_FATAL)<<"Time (third columns) should be >= 0 " << std::endl;
I-=input_file_offset; /* adjust from 1-based to 0-based */
J-=input_file_offset;
if (I >= M)
logstream(LOG_FATAL)<<"Row index larger than the matrix row size " << I << " > " << M << " in line: " << i << std::endl;
if (J >= N)
logstream(LOG_FATAL)<<"Col index larger than the matrix col size " << J << " > " << N << " in line; " << i << std::endl;
K = std::max((int)time, (int)K);
time -= matlab_time_offset;
if (time < 0 && add_time_edges)
logstream(LOG_FATAL)<<"Time bins should be >= 1 in row " << i << std::endl;
//avoid self edges
if (square && I == J)
continue;
active_edge = decide_if_edge_is_active(i, type);
if (active_edge){
if (type == TRAINING)
globalMean += val;
else globalMean2 += val;
sharderobj.preprocessing_add_edge(I, (square? J : (M + J)), als_edge_type(val, time+M+N));
}
//in case of a tensor, add besides of the user-> movie edge also
//time -> user and time-> movie edges
if (add_time_edges){
sharderobj.preprocessing_add_edge((uint)time + M + N, I, als_edge_type(val, M+J));
sharderobj.preprocessing_add_edge((uint)time + M + N, M+J , als_edge_type(val, I));
}
}
if (type == TRAINING){
uint toadd = 0;
if (implicitratingtype == IMPLICIT_RATING_RANDOM)
toadd = add_implicit_edges4(implicitratingtype, sharderobj);
globalMean += implicitratingvalue * toadd;
L += toadd;
globalMean /= L;
logstream(LOG_INFO) << "Global mean is: " << globalMean << " time bins: " << K << " . Now creating shards." << std::endl;
}
else {
globalMean2 /= Le;
logstream(LOG_INFO) << "Global mean is: " << globalMean2 << " time bins: " << K << " . Now creating shards." << std::endl;
}
write_global_mean(base_filename, type);
sharderobj.end_preprocessing();
} else {
logstream(LOG_INFO) << "Matrix already preprocessed, just run sharder." << std::endl;
}
fclose(f);
logstream(LOG_INFO) << "Now creating shards." << std::endl;
// Shard with a specified number of shards, or determine automatically if not defined
nshards = sharderobj.execute_sharding(get_option_string("nshards", "auto"));
return nshards;
}
/**
* Create a bipartite graph from a matrix. Each row corresponds to vertex
* with the same id as the row number (0-based), but vertices correponsing to columns
* have id + num-rows.
*/
template <typename als_edge_type>
int convert_matrixmarket_and_item_similarity(std::string base_filename, std::string similarity_file, int tokens_per_row = 3) {
FILE *f = NULL, *fsim = NULL;
size_t nz, nz_sim;
/**
* Create sharder object
*/
int nshards;
if ((nshards = find_shards<als_edge_type>(base_filename, get_option_string("nshards", "auto")))) {
if (check_origfile_modification_earlier<als_edge_type>(base_filename, nshards)) {
logstream(LOG_INFO) << "File " << base_filename << " was already preprocessed, won't do it again. " << std::endl;
read_global_mean(base_filename, TRAINING);
return nshards;
}
}
sharder<als_edge_type> sharderobj(base_filename);
sharderobj.start_preprocessing();
detect_matrix_size(base_filename, f, M, N, nz);
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open training input file: " << base_filename << std::endl;
uint N_row = 0 ,N_col = 0;
detect_matrix_size(similarity_file, fsim, N_row, N_col, nz_sim);
if (fsim == NULL)
logstream(LOG_FATAL)<<"Failed to open item similarity input file: " << similarity_file << std::endl;
if (N_row != N || N_col != N)
logstream(LOG_FATAL)<<"Wrong item similarity file matrix size: " << N_row <<" x " << N_col << " Instead of " << N << " x " << N << std::endl;
L=nz + nz_sim;
uint I, J;
double val = 1.0;
if (!sharderobj.preprocessed_file_exists()) {
logstream(LOG_INFO) << "Starting to read matrix-market input. Matrix dimensions: "
<< M << " x " << N << ", non-zeros: " << nz << std::endl;
for (size_t i=0; i<nz; i++){
if (tokens_per_row == 3){
int rc = fscanf(f, "%u %u %lg\n", &I, &J, &val);
if (rc != 3)
logstream(LOG_FATAL)<<"Error when reading input file: " << i << std::endl;
}
else if (tokens_per_row == 2){
int rc = fscanf(f, "%u %u\n", &I, &J);
if (rc != 2)
logstream(LOG_FATAL)<<"Error when reading input file: " << i << std::endl;
}
else assert(false);
I-=input_file_offset; /* adjust from 1-based to 0-based */
J-=input_file_offset;
if (I >= M)
logstream(LOG_FATAL)<<"Row index larger than the matrix row size " << I << " > " << M << " in line: " << i << std::endl;
if (J >= N)
logstream(LOG_FATAL)<<"Col index larger than the matrix col size " << J << " > " << N << " in line; " << i << std::endl;
sharderobj.preprocessing_add_edge(I, M==N?J:M + J, als_edge_type((float)val, 0));
}
logstream(LOG_DEBUG)<<"Finished loading " << nz << " ratings from file: " << base_filename << std::endl;
for (size_t i=0; i<nz_sim; i++){
if (tokens_per_row == 3){
int rc = fscanf(fsim, "%u %u %lg\n", &I, &J, &val);
if (rc != 3)
logstream(LOG_FATAL)<<"Error when reading input file: " << similarity_file << " line: " << i << std::endl;
}
else if (tokens_per_row == 2){
int rc = fscanf(fsim, "%u %u\n", &I, &J);
if (rc != 2)
logstream(LOG_FATAL)<<"Error when reading input file: " << i << std::endl;
}
else assert(false);
I-=input_file_offset; /* adjust from 1-based to 0-based */
J-=input_file_offset;
if (I >= N)
logstream(LOG_FATAL)<<"Row index larger than the matrix row size " << I << " > " << M << " in line: " << i << std::endl;
if (J >= N)
logstream(LOG_FATAL)<<"Col index larger than the matrix col size " << J << " > " << N << " in line; " << i << std::endl;
sharderobj.preprocessing_add_edge(M+I, M+J, als_edge_type(I < J? val: 0, I>J? val: 0));
}
logstream(LOG_DEBUG)<<"Finished loading " << nz_sim << " ratings from file: " << similarity_file << std::endl;
write_global_mean(base_filename, TRAINING);
sharderobj.end_preprocessing();
} else {
logstream(LOG_INFO) << "Matrix already preprocessed, just run sharder." << std::endl;
}
fclose(f);
fclose(fsim);
logstream(LOG_INFO) << "Now creating shards." << std::endl;
// Shard with a specified number of shards, or determine automatically if not defined
nshards = sharderobj.execute_sharding(get_option_string("nshards", "auto"));
logstream(LOG_INFO) << "Successfully finished sharding for " << base_filename << std::endl;
logstream(LOG_INFO) << "Created " << nshards << " shards." << std::endl;
return nshards;
}
/**
* Create a bipartite graph from a matrix. Each row corresponds to vertex
* with the same id as the row number (0-based), but vertices correponsing to columns
* have id + num-rows.
*/
template <typename als_edge_type>
int convert_matrixmarket(std::string base_filename, SharderPreprocessor<als_edge_type> * preprocessor = NULL, size_t nodes = 0, size_t edges = 0, int tokens_per_row = 3, int type = TRAINING, int allow_square = true) {
// Note, code based on: http://math.nist.gov/MatrixMarket/mmio/c/example_read.c
FILE *f;
size_t nz;
/**
* Create sharder object
*/
int nshards;
if ((nshards = find_shards<als_edge_type>(base_filename, get_option_string("nshards", "auto")))) {
if (check_origfile_modification_earlier<als_edge_type>(base_filename, nshards)) {
logstream(LOG_INFO) << "File " << base_filename << " was already preprocessed, won't do it again. " << std::endl;
read_global_mean(base_filename, type);
return nshards;
}
}
sharder<als_edge_type> sharderobj(base_filename);
sharderobj.start_preprocessing();
detect_matrix_size(base_filename, f, type == TRAINING?M:Me, type == TRAINING?N:Ne, nz, nodes, edges, type);
if (f == NULL){
if (type == TRAINING){
logstream(LOG_FATAL)<<"Failed to open training input file: " << base_filename << std::endl;
}
else if (type == VALIDATION){
logstream(LOG_INFO)<<"Validation file: " << base_filename << " is not found. " << std::endl;
return -1;
}
}
compute_matrix_size(nz, type);
uint I, J;
double val = 1.0;
bool active_edge = true;
if (!sharderobj.preprocessed_file_exists()) {
for (size_t i=0; i<nz; i++)
{
if (tokens_per_row == 3){
int rc = fscanf(f, "%u %u %lg\n", &I, &J, &val);
if (rc != 3)
logstream(LOG_FATAL)<<"Error when reading input file: " << i << std::endl;
}
else if (tokens_per_row == 2){
int rc = fscanf(f, "%u %u\n", &I, &J);
if (rc != 2)
logstream(LOG_FATAL)<<"Error when reading input file: " << i << std::endl;
}
else assert(false);
if (I ==987654321 || J== 987654321) //hack - to be removed later
continue;
I-=(uint)input_file_offset; /* adjust from 1-based to 0-based */
J-=(uint)input_file_offset;
if (I >= M)
logstream(LOG_FATAL)<<"Row index larger than the matrix row size " << I+1 << " > " << M << " in line: " << i << std::endl;
if (J >= N)
logstream(LOG_FATAL)<<"Col index larger than the matrix col size " << J+1 << " > " << N << " in line; " << i << std::endl;
if (minval != -1e100 && val < minval)
logstream(LOG_FATAL)<<"Found illegal rating value: " << val << " where min value is: " << minval << std::endl;
if (maxval != 1e100 && val > maxval)
logstream(LOG_FATAL)<<"Found illegal rating value: " << val << " where max value is: " << maxval << std::endl;
active_edge = decide_if_edge_is_active(i, type);
if (active_edge){
if (type == TRAINING)
globalMean += val;
else globalMean2 += val;
sharderobj.preprocessing_add_edge(I, (M==N && allow_square)?J:M + J, als_edge_type((float)val));
}
}
if (type == TRAINING){
uint toadd = 0;
if (implicitratingtype == IMPLICIT_RATING_RANDOM)
toadd = add_implicit_edges(implicitratingtype, sharderobj);
globalMean += implicitratingvalue * toadd;
L += toadd;
globalMean /= L;
logstream(LOG_INFO) << "Global mean is: " << globalMean << " Now creating shards." << std::endl;
}
else {
globalMean2 /= Le;
logstream(LOG_INFO) << "Global mean is: " << globalMean2 << " Now creating shards." << std::endl;
}
write_global_mean(base_filename, type);
sharderobj.end_preprocessing();
if (preprocessor != NULL) {
preprocessor->reprocess(sharderobj.preprocessed_name(), base_filename);
}
} else {
logstream(LOG_INFO) << "Matrix already preprocessed, just run sharder." << std::endl;
}
fclose(f);
logstream(LOG_INFO) << "Now creating shards." << std::endl;
// Shard with a specified number of shards, or determine automatically if not defined
nshards = sharderobj.execute_sharding(get_option_string("nshards", "auto"));
logstream(LOG_INFO) << "Successfully finished sharding for " << base_filename<< std::endl;
logstream(LOG_INFO) << "Created " << nshards << " shards." << std::endl;
return nshards;
}
void load_matrix_market_vector(const std::string & filename, const bipartite_graph_descriptor & desc,
int type, bool optional_field, bool allow_zeros)
{
int ret_code;
MM_typecode matcode;
uint M, N;
size_t i,nz;
logstream(LOG_INFO) <<"Going to read matrix market vector from input file: " << filename << std::endl;
FILE * f = open_file(filename.c_str(), "r", optional_field);
//if optional file not found return
if (f== NULL && optional_field){
return;
}
if (mm_read_banner(f, &matcode) != 0)
logstream(LOG_FATAL) << "Could not process Matrix Market banner." << std::endl;
/* This is how one can screen matrix types if their application */
/* only supports a subset of the Matrix Market data types. */
if (mm_is_complex(matcode) && mm_is_matrix(matcode) &&
mm_is_sparse(matcode) )
logstream(LOG_FATAL) << "sorry, this application does not support " << std::endl <<
"Market Market type: " << mm_typecode_to_str(matcode) << std::endl;
/* find out size of sparse matrix .... */
if (mm_is_sparse(matcode)){
if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &nz)) !=0)
logstream(LOG_FATAL) << "failed to read matrix market cardinality size " << std::endl;
}
else {
if ((ret_code = mm_read_mtx_array_size(f, &M, &N))!= 0)
logstream(LOG_FATAL) << "failed to read matrix market vector size " << std::endl;
if (N > M){ //if this is a row vector, transpose
int tmp = N;
N = M;
M = tmp;
}
nz = M*N;
}
uint row,col;
double val;
for (i=0; i<nz; i++)
{
if (mm_is_sparse(matcode)){
int rc = fscanf(f, "%u %u %lg\n", &row, &col, &val);
if (rc != 3){
logstream(LOG_FATAL) << "Failed reading input file: " << filename << "Problm at data row " << i << " (not including header and comment lines)" << std::endl;
}
row--; /* adjust from 1-based to 0-based */
col--;
}
else {
int rc = fscanf(f, "%lg\n", &val);
if (rc != 1){
logstream(LOG_FATAL) << "Failed reading input file: " << filename << "Problm at data row " << i << " (not including header and comment lines)" << std::endl;
}
row = i;
col = 0;
}
//some users have gibrish in text file - better check both I and J are >=0 as well
assert(row >=0 && row< M);
assert(col == 0);
if (val == 0 && !allow_zeros)
logstream(LOG_FATAL)<<"Zero entries are not allowed in a sparse matrix market vector. Use --zero=true to avoid this error"<<std::endl;
//set observation value
vertex_data & vdata = latent_factors_inmem[row];
vdata.pvec[type] = val;
}
fclose(f);
}
vec load_matrix_market_vector(const std::string & filename, bool optional_field, bool allow_zeros)
{
int ret_code;
MM_typecode matcode;
uint M, N;
size_t i,nz;
logstream(LOG_INFO) <<"Going to read matrix market vector from input file: " << filename << std::endl;
FILE * f = open_file(filename.c_str(), "r", optional_field);
//if optional file not found return
if (f== NULL && optional_field){
return zeros(1);
}
if (mm_read_banner(f, &matcode) != 0)
logstream(LOG_FATAL) << "Could not process Matrix Market banner." << std::endl;
/* This is how one can screen matrix types if their application */
/* only supports a subset of the Matrix Market data types. */
if (mm_is_complex(matcode) && mm_is_matrix(matcode) &&
mm_is_sparse(matcode) )
logstream(LOG_FATAL) << "sorry, this application does not support " << std::endl <<
"Market Market type: " << mm_typecode_to_str(matcode) << std::endl;
/* find out size of sparse matrix .... */
if (mm_is_sparse(matcode)){
if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &nz)) !=0)
logstream(LOG_FATAL) << "failed to read matrix market cardinality size " << std::endl;
}
else {
if ((ret_code = mm_read_mtx_array_size(f, &M, &N))!= 0)
logstream(LOG_FATAL) << "failed to read matrix market vector size " << std::endl;
if (N > M){ //if this is a row vector, transpose
int tmp = N;
N = M;
M = tmp;
}
nz = M*N;
}
vec ret = zeros(M);
uint row,col;
double val;
for (i=0; i<nz; i++)
{
if (mm_is_sparse(matcode)){
int rc = fscanf(f, "%u %u %lg\n", &row, &col, &val);
if (rc != 3){
logstream(LOG_FATAL) << "Failed reading input file: " << filename << "Problm at data row " << i << " (not including header and comment lines)" << std::endl;
}
row--; /* adjust from 1-based to 0-based */
col--;
}
else {
int rc = fscanf(f, "%lg\n", &val);
if (rc != 1){
logstream(LOG_FATAL) << "Failed reading input file: " << filename << "Problm at data row " << i << " (not including header and comment lines)" << std::endl;
}
row = i;
col = 0;
}
//some users have gibrish in text file - better check both I and J are >=0 as well
assert(row >=0 && row< M);
assert(col == 0);
if (val == 0 && !allow_zeros)
logstream(LOG_FATAL)<<"Zero entries are not allowed in a sparse matrix market vector. Use --zero=true to avoid this error"<<std::endl;
//set observation value
ret[row] = val;
}
fclose(f);
logstream(LOG_INFO)<<"Succesfully read a vector of size: " << M << " [ " << nz << "]" << std::endl;
return ret;
}
inline void write_row(int row, int col, double val, FILE * f, bool issparse){
if (issparse)
fprintf(f, "%d %d %10.13g\n", row, col, val);
else fprintf(f, "%10.13g ", val);
}
inline void write_row(int row, int col, int val, FILE * f, bool issparse){
if (issparse)
fprintf(f, "%d %d %d\n", row, col, val);
else fprintf(f, "%d ", val);
}
template<typename T>
inline void set_typecode(MM_typecode & matcore);
template<>
inline void set_typecode<vec>(MM_typecode & matcode){
mm_set_real(&matcode);
}
template<>
inline void set_typecode<ivec>(MM_typecode & matcode){
mm_set_integer(&matcode);
}
template<typename vec>
void save_matrix_market_format_vector(const std::string datafile, const vec & output, bool issparse, std::string comment)
{
MM_typecode matcode;
mm_initialize_typecode(&matcode);
mm_set_matrix(&matcode);
mm_set_coordinate(&matcode);
if (issparse)
mm_set_sparse(&matcode);
else mm_set_dense(&matcode);
set_typecode<vec>(matcode);
FILE * f = fopen(datafile.c_str(),"w");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file: " << datafile << " for writing. " << std::endl;
mm_write_banner(f, matcode);
if (comment.size() > 0) // add a comment to the matrix market header
fprintf(f, "%c%s\n", '%', comment.c_str());
if (issparse)
mm_write_mtx_crd_size(f, output.size(), 1, output.size());
else
mm_write_mtx_array_size(f, output.size(), 1);
for (int j=0; j<(int)output.size(); j++){
write_row(j+1, 1, output[j], f, issparse);
if (!issparse)
fprintf(f, "\n");
}
fclose(f);
}
template<typename vec>
inline void write_output_vector(const std::string & datafile, const vec& output, bool issparse, std::string comment = ""){
logstream(LOG_INFO)<<"Going to write output to file: " << datafile << " (vector of size: " << output.size() << ") " << std::endl;
save_matrix_market_format_vector(datafile, output,issparse, comment);
}
/** load a matrix market file into a matrix */
void load_matrix_market_matrix(const std::string & filename, int offset, int D){
MM_typecode matcode;
uint i,I,J;
double val;
uint rows, cols;
size_t nnz;
FILE * f = open_file(filename.c_str() ,"r");
int rc = mm_read_banner(f, &matcode);
if (rc != 0)
logstream(LOG_FATAL)<<"Failed to load matrix market banner in file: " << filename << std::endl;
if (mm_is_sparse(matcode)){
int rc = mm_read_mtx_crd_size(f, &rows, &cols, &nnz);
if (rc != 0)
logstream(LOG_FATAL)<<"Failed to load matrix market banner in file: " << filename << std::endl;
}
else { //dense matrix
rc = mm_read_mtx_array_size(f, &rows, &cols);
if (rc != 0)
logstream(LOG_FATAL)<<"Failed to load matrix market banner in file: " << filename << std::endl;
nnz = rows * cols;
}
if (D != (int)cols)
logstream(LOG_FATAL)<<"Wrong matrix size detected, command line argument should be --D=" << D << " instead of : " << cols << std::endl;
for (i=0; i<nnz; i++){
if (mm_is_sparse(matcode)){
rc = fscanf(f, "%u %u %lg\n", &I, &J, &val);
if (rc != 3)
logstream(LOG_FATAL)<<"Error reading input line " << i << std::endl;
I--; J--;
assert(I >= 0 && I < rows);
assert(J >= 0 && J < cols);
//set_val(a, I, J, val);
latent_factors_inmem[I+offset].set_val(J,val);
}
else {
rc = fscanf(f, "%lg", &val);
if (rc != 1)
logstream(LOG_FATAL)<<"Error reading nnz " << i << std::endl;
I = i / cols;
J = i % cols;
latent_factors_inmem[I+offset].set_val(J, val);
}
}
logstream(LOG_INFO) << "Factors from file: loaded matrix of size " << rows << " x " << cols << " from file: " << filename << " total of " << nnz << " entries. "<< i << std::endl;
fclose(f);
}
#endif
| 09jijiangwen-download | toolkits/collaborative_filtering/io.hpp | C++ | asf20 | 30,477 |
#!/bin/sh
if [ ! -d "../../src/Eigen/" ]; then
echo "********************************************************************************"
echo "Failed to find Eigen linear algebra package!"
echo "Please follow step 3 of the instructions here: "
echo "http://bickson.blogspot.co.il/2012/08/collaborative-filtering-with-graphchi.html"
echo "********************************************************************************"
exit 1;
else
echo "Found Eigen linear algebra package!"
exit 0;
fi
| 09jijiangwen-download | toolkits/collaborative_filtering/test_eigen.sh | Shell | asf20 | 509 |
/* fix for MAC OS where sometime getline() is not supported */
#ifndef __GETLINE_GRAPHCHI_MAXOS_FIX
#define __GETLINE_GRAPHCHI_MAXOS_FIX
/* PASTE AT TOP OF FILE */
#include <stdio.h> /* flockfile, getc_unlocked, funlockfile */
#include <stdlib.h> /* malloc, realloc */
#include <errno.h> /* errno */
#include <unistd.h> /* ssize_t */
extern "C" ssize_t getline(char **lineptr, size_t *n, FILE *stream);
/* PASTE REMAINDER AT BOTTOM OF FILE */
ssize_t
getline(char **linep, size_t *np, FILE *stream)
{
char *p = NULL;
size_t i = 0;
if (!linep || !np) {
errno = EINVAL;
return -1;
}
if (!(*linep) || !(*np)) {
*np = 2400;
*linep = (char *)malloc(*np);
if (!(*linep)) {
return -1;
}
}
flockfile(stream);
p = *linep;
for (int ch = 0; (ch = getc_unlocked(stream)) != EOF;) {
if (i > *np) {
/* Grow *linep. */
size_t m = *np * 2;
char *s = (char *)realloc(*linep, m);
if (!s) {
int error = errno;
funlockfile(stream);
errno = error;
return -1;
}
*linep = s;
*np = m;
}
p[i] = ch;
if ('\n' == ch) break;
i += 1;
}
funlockfile(stream);
/* Null-terminate the string. */
if (i > *np) {
/* Grow *linep. */
size_t m = *np * 2;
char *s = (char *)realloc(*linep, m);
if (!s) {
return -1;
}
*linep = s;
*np = m;
}
p[i + 1] = '\0';
return ((i > 0)? i : -1);
}
#endif //__GETLINE_GRAPHCHI_MAXOS_FIX
| 09jijiangwen-download | toolkits/collaborative_filtering/getline.hpp | C++ | asf20 | 1,507 |
/**
* @file
* @author Danny Bickson, based on code by Aapo Kyrola
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* Matrix factorization with the Alternative Least Squares (ALS) algorithm.
* See the papers:
* H.-F. Yu, C.-J. Hsieh, S. Si, I. S. Dhillon, Scalable Coordinate Descent Approaches to Parallel Matrix Factorization for Recommender Systems. IEEE International Conference on Data Mining(ICDM), December 2012.
* Steffen Rendle, Zeno Gantner, Christoph Freudenthaler, and Lars Schmidt-Thieme. 2011. Fast context-aware recommendations with factorization machines. In Proceedings of the 34th international ACM SIGIR conference on Research and development in Information Retrieval (SIGIR '11). ACM, New York, NY, USA, 635-644. *
*/
#include "common.hpp"
#include "eigen_wrapper.hpp"
double lambda = 0.065;
struct vertex_data {
vec pvec;
vertex_data() {
pvec = zeros(D);
}
void set_val(int index, float val){
pvec[index] = val;
}
float get_val(int index){
return pvec[index];
}
};
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vertex_data VertexDataType;
typedef float EdgeDataType; // Edges store the "rating" of user->movie pair
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
graphchi_engine<VertexDataType, EdgeDataType> * pvalidation_engine = NULL;
std::vector<vertex_data> latent_factors_inmem;
#include "io.hpp"
#include "rmse.hpp"
#include "rmse_engine.hpp"
/** compute a missing value based on ALS algorithm */
float als_predict(const vertex_data& user,
const vertex_data& movie,
const float rating,
double & prediction,
void * extra = NULL){
prediction = dot_prod(user.pvec, movie.pvec);
//truncate prediction to allowed values
prediction = std::min((double)prediction, maxval);
prediction = std::max((double)prediction, minval);
//return the squared error
float err = rating - prediction;
assert(!std::isnan(err));
return err*err;
}
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct ALSVerticesInMemProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Vertex update function - computes the ICDM update function in parallel
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
vertex_data & vdata = latent_factors_inmem[vertex.id()];
double regularization = lambda;
if (regnormal)
regularization *= vertex.num_edges();
vec R_cache = zeros(vertex.num_edges());
for (int t=0; t<D; t++){
double numerator = 0;
double denominator = regularization;
bool compute_rmse = (vertex.num_outedges() > 0 && t == 0);
for (int j=0; j < vertex.num_edges(); j++) {
float observation = vertex.edge(j)->get_data();
vertex_data & nbr_latent = latent_factors_inmem[vertex.edge(j)->vertex_id()];
double prediction;
double rmse = 0;
if (t == 0){
rmse = als_predict(vdata, nbr_latent, observation, prediction);
R_cache[j] = observation - prediction;
}
//compute numerator of equation (5) in ICDM paper above
// (A_ij - w_i^T*h_j + wit * h_jt )*h_jt
numerator += (R_cache[j] + vdata.pvec[t]* nbr_latent.pvec[t])*nbr_latent.pvec[t];
//compute denominator of equation (5) in ICDM paper above
// h_jt^2
denominator += pow(nbr_latent.pvec[t],2);
//record rmse
if (compute_rmse)
rmse_vec[omp_get_thread_num()]+=rmse;
}
assert(denominator > 0);
double z = numerator/denominator;
vec old = vdata.pvec;
//if (t > 0){
for (int j=0; j< vertex.num_edges(); j++){
vertex_data & nbr_latent = latent_factors_inmem[vertex.edge(j)->vertex_id()];
//update using equation (7) in ICDM paper
//R_ij -= (z - w_it )*h_jt
R_cache[j] -= ((z - old[t])*nbr_latent.pvec[t]);
}
//}
//update using equation (8) in ICDM paper
//w_it = z;
vdata.pvec[t] = z;
}
}
/**
* Called before an iteration is started.
*/
void before_iteration(int iteration, graphchi_context &gcontext) {
reset_rmse(gcontext.execthreads);
}
/**
* Called after an iteration has finished.
*/
void after_iteration(int iteration, graphchi_context &gcontext) {
training_rmse(iteration, gcontext);
run_validation(pvalidation_engine, gcontext);
}
};
void output_als_result(std::string filename) {
MMOutputter_mat<vertex_data> user_mat(filename + "_U.mm", 0, M , "This file contains ALS output matrix U. In each row D factors of a single user node.", latent_factors_inmem);
MMOutputter_mat<vertex_data> item_mat(filename + "_V.mm", M ,M+N, "This file contains ALS output matrix V. In each row D factors of a single item node.", latent_factors_inmem);
logstream(LOG_INFO) << "ALS output files (in matrix market format): " << filename << "_U.mm" <<
", " << filename + "_V.mm " << std::endl;
}
int main(int argc, const char ** argv) {
print_copyright();
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("als-inmemory-factors");
lambda = get_option_float("lambda", 0.065);
parse_command_line_args();
parse_implicit_command_line();
/* Preprocess data if needed, or discover preprocess files */
int nshards = convert_matrixmarket<EdgeDataType>(training, NULL, 0, 0, 3, TRAINING, false);
init_feature_vectors<std::vector<vertex_data> >(M+N, latent_factors_inmem, !load_factors_from_file);
if (validation != ""){
int vshards = convert_matrixmarket<EdgeDataType>(validation, NULL, 0, 0, 3, VALIDATION, false);
init_validation_rmse_engine<VertexDataType, EdgeDataType>(pvalidation_engine, vshards, &als_predict);
}
/* load initial state from disk (optional) */
if (load_factors_from_file){
load_matrix_market_matrix(training + "_U.mm", 0, D);
load_matrix_market_matrix(training + "_V.mm", M, D);
}
/* Run */
ALSVerticesInMemProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m);
set_engine_flags(engine);
pengine = &engine;
engine.run(program, niters);
/* Output latent factor matrices in matrix-market format */
output_als_result(training);
test_predictions(&als_predict);
/* Report execution metrics */
if (!quiet)
metrics_report(m);
return 0;
}
| 09jijiangwen-download | toolkits/collaborative_filtering/als_coord.cpp | C++ | asf20 | 7,562 |
#ifndef TYPES_COMMON
#define TYPES_COMMON
typedef double real_type;
/*
* store a matrix is a bipartite graph. One side is the rows and the other is the column.
*/
struct bipartite_graph_descriptor {
int rows, cols;
size_t nonzeros;
bool force_non_square; //do not optimize, so each row and column will get its own graph node, even if the matrix is square
bipartite_graph_descriptor() : rows(0), cols(0), nonzeros(0), force_non_square(false) { }
// is the matrix square?
bool is_square() const { return rows == cols && !force_non_square; }
// get the position of the starting row/col node
int get_start_node(bool _rows) const { if (is_square()) return 0; else return (_rows?0:rows); }
// get the position of the ending row/col node
int get_end_node(bool _rows) const { if (is_square()) return rows; else return (_rows?rows:(rows+cols)); }
// get howmany row/column nodes
int num_nodes(bool _rows) const { if (_rows) return rows; else return cols; }
// how many total nodes
int total() const { if (is_square()) return rows; else return rows+cols; }
//is this a row node
bool is_row_node(int id) const { return id < rows; }
//debug print?
bool toprint(int id) const { return (id == 0) || (id == rows - 1) || (id == rows) || (id == rows+cols-1); }
}; // end of bipartite graph descriptor
#endif
| 09jijiangwen-download | toolkits/collaborative_filtering/types.hpp | C++ | asf20 | 1,341 |
#ifndef _CLIMF_HPP__
#define _CLIMF_HPP__
/**
* @file
* @author Mark Levy
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* CLiMF Collaborative Less-is-More Filtering, a variant of latent factor CF
* which optimises a lower bound of the smoothed reciprocal rank of "relevant"
* items in ranked recommendation lists. The intention is to promote diversity
* as well as accuracy in the recommendations. The method assumes binary
* relevance data, as for example in friendship or follow relationships.
*
* CLiMF: Learning to Maximize Reciprocal Rank with Collaborative Less-is-More Filtering
* Yue Shi, Martha Larson, Alexandros Karatzoglou, Nuria Oliver, Linas Baltrunas, Alan Hanjalic
* ACM RecSys 2012
*
*/
struct vertex_data {
vec pvec; //storing the feature vector
vertex_data()
{
pvec = zeros(D);
}
void set_val(int index, float val)
{
pvec[index] = val;
}
float get_val(int index) const
{
return pvec[index];
}
};
typedef vertex_data VertexDataType; // Vertices store the low-dimensional factorized feature vector
typedef float EdgeDataType; // Edges store the rating/observed count for a user->item pair
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
graphchi_engine<VertexDataType, EdgeDataType> * pvalidation_engine = NULL;
std::vector<vertex_data> latent_factors_inmem;
double sgd_gamma = 1e-3; // sgd step size
double sgd_step_dec = 0.9; // sgd step decrement
double sgd_lambda = 1e-3; // sgd regularization
double binary_relevance_thresh = 0; // min rating for binary relevance
int halt_on_mrr_decrease = 0; // whether to halt if smoothed MRR increases
int num_ratings = 10000; // number of top predictions over which we compute actual MRR
vec objective_vec; // cumulative sum of smoothed MRR per thread
double training_objective;
double last_training_objective;
/* other relevant global args defined in common.hpp:
uint M; // number of users
uint N; // number of items
uint Me; // number of users (validation file)
uint Ne; // number of items (validation file)
uint Le; // number of ratings (validation file)
size_t L; // number of ratings (training file)
int D = 20; // feature vector width
*/
// logistic function
double g(double x)
{
double ret = 1.0 / (1.0 + std::exp(-x));
if (std::isinf(ret) || std::isnan(ret))
{
logstream(LOG_FATAL) << "overflow in g()" << std::endl;
}
return ret;
}
// derivative of logistic function
double dg(double x)
{
double ret = std::exp(x) / ((1.0 + std::exp(x)) * (1.0 + std::exp(x)));
if (std::isinf(ret) || std::isnan(ret))
{
logstream(LOG_FATAL) << "overflow in dg()" << std::endl;
}
return ret;
}
bool is_relevant(graphchi_edge<EdgeDataType> * e)
{
return e->get_data() >= binary_relevance_thresh; // for some reason get_data() is non const :(
}
#endif
| 09jijiangwen-download | toolkits/collaborative_filtering/climf.hpp | C++ | asf20 | 3,655 |
/**
* @file
* @author Danny Bickson
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* Matrix factorization using weighted alternating least squares algorithm (WALS)
* The algorithm is explained in: Collaborative Filtering for Implicit Feedback Datasets Hu, Y.; Koren, Y.; Volinsky, C. IEEE International Conference on Data Mining (ICDM 2008), IEEE (2008).
* @section USAGE
*
*
*
*/
#include "common.hpp"
#include "eigen_wrapper.hpp"
double lambda = 1e-3;
struct vertex_data {
vec pvec;
vertex_data() {
pvec = zeros(D);
}
void set_val(int index, float val){
pvec[index] = val;
}
float get_val(int index){
return pvec[index];
}
};
struct edge_data {
double weight;
double time;
edge_data() { weight = time = 0; }
edge_data(double weight, double time) : weight(weight), time(time) { }
};
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vertex_data VertexDataType;
typedef edge_data EdgeDataType; // Edges store the "rating" of user->movie pair
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
graphchi_engine<VertexDataType, EdgeDataType> * pvalidation_engine = NULL;
std::vector<vertex_data> latent_factors_inmem;
#include "io.hpp"
#include "rmse.hpp"
#include "rmse_engine4.hpp"
/** compute a missing value based on WALS algorithm */
float wals_predict(const vertex_data& user,
const vertex_data& movie,
const float rating,
double & prediction,
void * extra = NULL){
prediction = dot_prod(user.pvec, movie.pvec);
//truncate prediction to allowed values
prediction = std::min((double)prediction, maxval);
prediction = std::max((double)prediction, minval);
//return the squared error
float err = rating - prediction;
assert(!std::isnan(err));
return err*err;
}
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct WALSVerticesInMemProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Vertex update function.
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
vertex_data & vdata = latent_factors_inmem[vertex.id()];
mat XtX = mat::Zero(D, D);
vec Xty = vec::Zero(D);
bool compute_rmse = (vertex.num_outedges() > 0);
// Compute XtX and Xty (NOTE: unweighted)
for(int e=0; e < vertex.num_edges(); e++) {
const edge_data & edge = vertex.edge(e)->get_data();
vertex_data & nbr_latent = latent_factors_inmem[vertex.edge(e)->vertex_id()];
Xty += nbr_latent.pvec * edge.weight * edge.time;
XtX.triangularView<Eigen::Upper>() += nbr_latent.pvec * nbr_latent.pvec.transpose() * edge.time;
if (compute_rmse) {
double prediction;
rmse_vec[omp_get_thread_num()] += wals_predict(vdata, nbr_latent, edge.weight, prediction) * edge.time;
}
}
double regularization = lambda;
if (regnormal)
lambda *= vertex.num_edges();
for(int i=0; i < D; i++) XtX(i,i) += regularization;
// Solve the least squares problem with eigen using Cholesky decomposition
vdata.pvec = XtX.selfadjointView<Eigen::Upper>().ldlt().solve(Xty);
}
/**
* Called before an iteration is started.
*/
void before_iteration(int iteration, graphchi_context &gcontext) {
reset_rmse(gcontext.execthreads);
}
/**
* Called after an iteration has finished.
*/
void after_iteration(int iteration, graphchi_context &gcontext) {
training_rmse(iteration, gcontext);
run_validation4(pvalidation_engine, gcontext);
}
};
void output_als_result(std::string filename) {
MMOutputter_mat<vertex_data> user_mat(filename + "_U.mm", 0, M, "This file contains WALS output matrix U. In each row D factors of a single user node.", latent_factors_inmem);
MMOutputter_mat<vertex_data> item_mat(filename + "_V.mm", M, M+N, "This file contains WALS output matrix V. In each row D factors of a single item node.", latent_factors_inmem);
logstream(LOG_INFO) << "WALS output files (in matrix market format): " << filename << "_U.mm" <<
", " << filename + "_V.mm " << std::endl;
}
int main(int argc, const char ** argv) {
print_copyright();
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("als-inmemory-factors");
lambda = get_option_float("lambda", 0.065);
parse_command_line_args();
parse_implicit_command_line();
if (unittest == 1){
if (training == "") training = "test_wals";
niters = 100;
}
/* Preprocess data if needed, or discover preprocess files */
int nshards = convert_matrixmarket4<edge_data>(training);
init_feature_vectors<std::vector<vertex_data> >(M+N, latent_factors_inmem, !load_factors_from_file);
if (validation != ""){
int vshards = convert_matrixmarket4<EdgeDataType>(validation, false, M==N, VALIDATION, 0);
init_validation_rmse_engine<VertexDataType, EdgeDataType>(pvalidation_engine, vshards, &wals_predict, true, false, 0);
}
if (load_factors_from_file){
load_matrix_market_matrix(training + "_U.mm", 0, D);
load_matrix_market_matrix(training + "_V.mm", M, D);
}
/* Run */
WALSVerticesInMemProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m);
set_engine_flags(engine);
pengine = &engine;
engine.run(program, niters);
/* Output latent factor matrices in matrix-market format */
output_als_result(training);
test_predictions(&wals_predict);
if (unittest == 1){
if (dtraining_rmse > 0.03)
logstream(LOG_FATAL)<<"Unit test 1 failed. Training RMSE is: " << training_rmse << std::endl;
if (dvalidation_rmse > 0.61)
logstream(LOG_FATAL)<<"Unit test 1 failed. Validation RMSE is: " << validation_rmse << std::endl;
}
/* Report execution metrics */
if (!quiet)
metrics_report(m);
return 0;
}
| 09jijiangwen-download | toolkits/collaborative_filtering/wals.cpp | C++ | asf20 | 6,863 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
#ifndef NPROB_HPP
#define NPROB_HPP
#include <cmath>
#define pi 3.14152965
/**
Porbability distribution helper functions written by Danny Bickson, CMU
*/
using namespace std;
//#define WISHART_TEST
//#define WISHART_TEST2
vec chi2rnd(vec v, int size){
vec ret = zeros(size);
for (int i=0; i<size; i++)
ret[i] = 2.0* gamma(v[i]/2.0);
#ifdef WISHART_TEST
ret = vec("9.3343 9.2811 9.3583 9.3652 9.3031");
ret*= 1e+04;
#elif defined(WISHART_TEST2)
ret = vec("4.0822e+03");
#endif
return ret;
}
void randv(int n, vec & ret){
assert(n>=1);
for (int i=0; i< n; i++)
ret[i] = drand48();
}
mat randn1(int Dx, int Dy, int col){
if (Dx == 0)
Dx = 1;
assert(Dy>=1);
mat ret = zeros(Dx,Dy);
vec us = zeros(ceil(Dx*Dy/2.0)*2);
randv(ceil(Dx*Dy/2.0)*2, us);
int k=0;
for (int i=0; i<Dx; i++){
for (int j=0; j< Dy; j++){
if (k % 2 == 0)
ret(i,j) = sqrt(-2.0*std::log(us[k/2]))*std::cos(2*pi*us[k/2+1]);
else
ret(i,j) = sqrt(-2.0*std::log(us[k/2]))*std::sin(2*pi*us[k/2+1]);
k++;
}
}
assert(k == Dx*Dy);
assert(ret.rows() == Dx && ret.cols() == Dy);
return ret;
}
vec randn1_vec(int Dx, int Dy, int col){
mat ret = randn1(Dx,Dy,col);
return get_col(ret, col);
}
vec mvnrndex(vec &mu, mat &sigma, int d, double regularization){
assert(mu.size() == d);
if (regularization > 0)
sigma = sigma+ regularization*eye(sigma.rows());
mat tmp;
bool ret = chol(sigma, tmp);
if (!ret)
logstream(LOG_FATAL)<<"Cholesky decomposition in mvnrned() got into numerical errors. Try to set --bptf_chol_diagonal_weighting command line argument to add regularization" << std::endl;
vec x = zeros(d);
vec col = randn1_vec(mu.size(), 1,0);
x = mu + transpose(tmp) * col;
assert(x.size() == d);
return x;
}
/* The following code is taken from the ACM paper:
* George Marsaglia and Wai Wan Tsang. 2000. A simple method for generating gamma variables. ACM Trans. Math. Softw. 26, 3 (September 2000), 363-372.
*/
float rgama(float a) {
float d,c,x,v,u;
d = a-1.0/3.0; c=1.0/sqrt(9.0*d);
for(;;) {
do {vec xvec = randn1_vec(1,1,0); x=xvec[0]; v=1.0+c*x;} while(v<=0.0);
v=v*v*v; u=drand48();
if( u<1.0-0.0331*(x*x)*(x*x) ) return (d*v);
if( log(u)<0.5*x*x+d*(1.0-v+log(v)) ) return (d*v);
}
}
float gamma(int alpha){
return rgama(alpha);
}
mat load_itiru(mat &a, mat& b){
assert(a.size() >= 1);
//nothing to do in case of a scalar
if (a.rows() == 1 && a.cols() == 1)
return a;
assert(b.cols() == 1);
assert(a.rows() == a.cols());
int n = a.rows();
int k = 0;
for (int i=0; i< n; i++)
for (int j=i+1; j< n; j++){
//a.set(i,j, b.get(k++,0));
set_val(a,i,j,get_val(b,k++,0));
}
assert(k == (n*(n-1))/2.0);
return a;
}
vec sequence(int df, int n){
assert(n >= 1);
assert(df>= 0);
vec ret(n);
for (int i=0; i<n; i++)
ret[i] = df - i;
return ret;
}
mat wishrnd(mat& sigma, double df){
mat d;
//cout<<sigma<<endl;
bool ret = chol(sigma, d);
//cout<<d<<endl;
assert(ret);
int n = sigma.rows();
mat x = zeros(n,n) ,a = zeros(n,n);
mat b;
if ((df <= 81+sigma.rows()) && (df == ::round(df))){
x = randn((int)df, d.rows())*d;
}
else {
vec seq = sequence(df, n);
//cout<<seq<<endl;
vec ret = chi2rnd(seq, n);
//cout<<ret<<endl;
ret = ::sqrt(ret);
//assert(ret.size() == n);
//cout<<ret<<endl;
if (ret.size() == 1) // a scalar variable
set_val(a,0,0, ret[0]);
else //a matrix
set_diag(a,ret);
assert(a.rows() == n && a.cols() == n);
//cout<<a<<endl;
if (ret.size() > 1){
b = randn(n*(n-1)/2,1);
assert(b.cols() == 1);
}
#ifdef WISHART_TEST
b=zeros(10,1); b = mat("0.1139 ; 1.0668 ; -0.0956 ; -1.3362; 0.0593 ; -0.8323 ; 0.7143; 0.2944 ; 1.6236; -0.6918");
//b = zeros(10,1); b = mat(" 1.1909 ; 1.1892 ; -0.0376; 0.3273; 0.1746; -0.1867; 0.7258; -0.5883; 2.1832; -0.1364");
#elif defined(WISHART_TEST2)
b = mat(0,0);
#endif
if (ret.size() > 1)
a = load_itiru(a,b);
//assert(a.rows() == n && a.cols() == n);
//cout<<a<<endl;
x = a*d;
//assert(x.cols() == x.rows() && x.cols() == n);
//cout<<x<<endl;
}
mat c= transpose(x)*x;
assert(c.rows() == n && c.cols() == n);
//cout<<a<<endl;
//
assert(abs_sum(c)!= 0);
return c;
}
void test_wishrnd(){
#ifndef WISHART_TEST
assert(false);
#endif
mat a = init_mat(" 0.2977 -0.0617 -0.1436 -0.0929 0.0136;"
"-0.0617 0.3489 -0.0736 -0.0581 -0.1337;"
"-0.1436 -0.0736 0.4457 -0.0348 -0.0301;"
"-0.0929 -0.0581 -0.0348 0.3165 0.0029;"
" 0.0136 -0.1337 -0.0301 0.0029 0.1862;", 5, 5);
assert(a.rows() == a.cols() && a.rows() == 5);
a *= 1.0e-03;
int df = 93531;
mat b = wishrnd(a,df);
mat trueret = init_mat(" 27.7883 -5.6442 -13.3231 -8.7063 1.2395;"
"-5.6442 32.3413 -6.8909 -5.3947 -12.4362;"
"-13.3231 -6.8909 41.5932 -3.3148 -2.6792;"
" -8.7063 -5.3947 -3.3148 29.6388 0.2115;"
" 1.2395 -12.4362 -2.6792 0.2115 17.3015;", 5, 5);
double diff = sumsum(b-trueret)/(25.0);
assert(fabs(diff) < 1e-2);
}
void test_wishrnd2(){
#ifndef WISHART_TEST2
assert(false);
#endif
mat a = init_mat("3", 1, 1);
assert(a.rows() == a.cols() && a.rows() == 1);
int df = 4122;
mat b = wishrnd(a,df);
mat trueret = init_mat("1.2247e+04",1,1);
double diff = sumsum(b-trueret);
assert(fabs(diff) < 1);
}
void test_randn(){
#if (defined(WISHART_TEST2) || defined(WISHART_TEST))
assert(false);
#endif
mat a = randn(10000000,1);
double ret = fabs(sumsum(a)/10000000);
assert(ret < 4e-3);
//ret = fabs(variance(get_col(a,0)) - 1);
//assert(ret < 1e-3);
//TODO
}
void test_mvnrndex(){
mat sigma = init_mat(
" 0.990566133945187 -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 ;" \
" -0.009433866054813 0.990566133945187 -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 ;" \
" -0.009433866054813 -0.009433866054813 0.990566133945187 -0.009433866054813 -0.009433866054813 -0.009433866054813 ;" \
" -0.009433866054813 -0.009433866054813 -0.009433866054813 0.990566133945187 -0.009433866054813 -0.009433866054813 ;" \
" -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 0.990566133945187 -0.009433866054813 ;" \
" -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 0.990566133945187 ", 6, 6);
vec mu = init_vec("95532 -1 2 3 0 22", 5);
vec ret = zeros(6);
for (int i=0; i<10000; i++){
ret+= mvnrndex(mu,sigma,6,0);
}
ret /= 10000;
vec ans = init_vec("95532.0115 -0.996855354 2.00914034 2.99521376 -0.0105874825 22.0127606", 6);
cout<<ret<<endl<<norm(ans-ret)<<endl;
}
void test_chi2rnd(){
vec ret = zeros(6);
vec v = init_vec("95532 95531 95530 95529 95528 95527", 6);
for (int i=0; i< 1000000; i++){
ret += chi2rnd(v, 6);
}
ret /= 1000000;
vec ans = init_vec("95531.99 95531.672 95530.016 95530.005 95527.495 95527.447", 6);
cout<<ret<<endl<<norm(ans-ret)<<endl;
}
void test_wishrnd3(){
mat sigma = init_mat(
" 0.990566133945187 -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 ;" \
" -0.009433866054813 0.990566133945187 -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 ;" \
" -0.009433866054813 -0.009433866054813 0.990566133945187 -0.009433866054813 -0.009433866054813 -0.009433866054813 ;" \
" -0.009433866054813 -0.009433866054813 -0.009433866054813 0.990566133945187 -0.009433866054813 -0.009433866054813 ;" \
" -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 0.990566133945187 -0.009433866054813 ;" \
" -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 -0.009433866054813 0.990566133945187 ", 6,6);
int df = 95532;
mat ret = zeros(6,6);
for (int i=0; i<10000; i++){
ret+= wishrnd(sigma, df);
}
ret /= 10000;
mat ans = init_mat("9.463425666451165 -0.090326102576222 -0.091016693707751 -0.089933822069320 -0.090108095540542 -0.089915220156678 ;\
-0.090326102576222 9.462305273959634 -0.090071105888907 -0.090355541326424 -0.090556802227637 -0.089887181087950 ;\
-0.091016693707751 -0.090071105888907 9.462973812711439 -0.090185140101184 -0.090013352917616 -0.089803917691135 ;\
-0.089933822069320 -0.090355541326424 -0.090185140101184 9.462292292298272 -0.090233918216433 -0.090557276073727 ;\
-0.090108095540542 -0.090556802227637 -0.090013352917616 -0.090233918216433 9.461377045031403 -0.089774502028808 ;\
-0.089915220156678 -0.089887181087950 -0.089803917691135 -0.090557276073727 -0.089774502028808 9.463220187604252", 6, 6);
ans *= 1.0e+04;
cout<<ret<<endl<<norm(ans-ret)<<endl;
}
#endif //NPROB_HPP
| 09jijiangwen-download | toolkits/collaborative_filtering/prob.hpp | C++ | asf20 | 10,046 |
#ifndef _DISTANCE_HPP__
#define _DISTANCE_HPP__
#include "graphchi_basic_includes.hpp"
typedef double flt_dbl;
typedef sparse_vec sparse_flt_dbl_vec;
typedef vec flt_dbl_vec;
extern int debug;
double safeLog(double d) {
return d <= 0.0 ? 0.0 : log(d);
}
double logL(double p, double k, double n) {
return k * safeLog(p) + (n - k) * safeLog(1.0 - p);
}
double twoLogLambda(double k1, double k2, double n1, double n2) {
double p = (k1 + k2) / (n1 + n2);
return 2.0 * (logL(k1 / n1, k1, n1) + logL(k2 / n2, k2, n2) - logL(p, k1, n1) - logL(p, k2, n2));
}
flt_dbl calc_loglikelihood_distance( sparse_flt_dbl_vec & datapoint, sparse_flt_dbl_vec & cluster, flt_dbl sqr_sum, flt_dbl sqr_sum_datapoint){
flt_dbl intersection = dot_prod(datapoint , cluster);
flt_dbl logLikelihood = twoLogLambda(intersection,
sqr_sum - intersection,
sqr_sum_datapoint,
datapoint.size() - sqr_sum_datapoint);
return 1.0 - 1.0 / (1.0 + logLikelihood);
}
flt_dbl calc_loglikelihood_distance( sparse_flt_dbl_vec & datapoint, flt_dbl_vec &cluster, flt_dbl sqr_sum, flt_dbl sqr_sum_datapoint){
flt_dbl intersection = dot_prod(datapoint, cluster);
flt_dbl logLikelihood = twoLogLambda(intersection,
sqr_sum - intersection,
sqr_sum_datapoint,
datapoint.size() - sqr_sum_datapoint);
return 1.0 - 1.0 / (1.0 + logLikelihood);
}
flt_dbl calc_tanimoto_distance( sparse_flt_dbl_vec & datapoint, sparse_flt_dbl_vec & cluster, flt_dbl sqr_sum, flt_dbl sqr_sum_datapoint){
flt_dbl a_mult_b = dot_prod(datapoint , cluster);
flt_dbl div = (sqr_sum + sqr_sum_datapoint - a_mult_b);
if (debug && (div == 0 || a_mult_b/div < 0)){
logstream(LOG_ERROR) << "divisor is zeo: " << sqr_sum<< " " << sqr_sum_datapoint << " " << a_mult_b << " " << std::endl;
print(datapoint);
print(cluster);
exit(1);
}
return 1.0 - a_mult_b/div;
}
flt_dbl calc_tanimoto_distance( sparse_flt_dbl_vec & datapoint, flt_dbl_vec &cluster, flt_dbl sqr_sum, flt_dbl sqr_sum_datapoint){
flt_dbl a_mult_b = dot_prod(datapoint, cluster);
flt_dbl div = (sqr_sum + sqr_sum_datapoint - a_mult_b);
if (debug && (div == 0 || a_mult_b/div < 0)){
logstream(LOG_ERROR) << "divisor is zeo: " << sqr_sum << " " << sqr_sum_datapoint << " " << a_mult_b << " " << std::endl;
print(datapoint);
debug_print_vec("cluster", cluster, cluster.size());
exit(1);
}
return 1.0 - a_mult_b/div;
}
flt_dbl calc_jaccard_weight_distance( sparse_flt_dbl_vec & datapoint, sparse_flt_dbl_vec & cluster, flt_dbl sqr_sum, flt_dbl sqr_sum_datapoint){
flt_dbl a_size = 0;
FOR_ITERATOR(i, datapoint){
a_size+= i.value();
}
flt_dbl b_size = 0;
FOR_ITERATOR(i, cluster){
b_size+= i.value();
}
flt_dbl intersection_size = sqr_sum;
assert(intersection_size != 0);
return intersection_size / (a_size+b_size-intersection_size);
}
flt_dbl calc_euclidian_distance( sparse_flt_dbl_vec & datapoint, sparse_flt_dbl_vec &cluster, flt_dbl sqr_sum, flt_dbl sqr_sum_datapoint){
//sparse_flt_dbl_vec diff = minus(datapoint , cluster);
//return sqrt(sum_sqr(diff));
sparse_flt_dbl_vec mult = elem_mult(datapoint, cluster);
flt_dbl diff = (sqr_sum + sqr_sum_datapoint - 2*sum(mult));
return sqrt(fabs(diff)); //because of numerical errors, diff may be negative
}
/*
flt_dbl calc_euclidian_distance( sparse_flt_dbl_vec & datapoint, flt_dbl_vec &cluster, flt_dbl sqr_sum, flt_dbl sqr_sum_datapoint){
flt_dbl dist = sqr_sum + sqr_sum_datapoint;
//for (int i=0; i< datapoint.nnz(); i++){
FOR_ITERATOR_(i, datapoint){
flt_dbl val = get_nz_data(datapoint, i);
int pos = get_nz_index(datapoint, i);
dist -= 2*val*cluster[pos];
}
if (debug && dist < 0 && fabs(dist) > 1e-8){
logstream(LOG_WARNING)<<"Found a negative distance: " << dist << " initial sum: " << sqr_sum_datapoint + sqr_sum << std::endl;
logstream(LOG_WARNING)<<"sqr sum: " << sqr_sum << " sqr_sum_datapoint: " <<sqr_sum_datapoint<<std::endl;
FOR_ITERATOR_(i, datapoint){
int pos = get_nz_index(datapoint, i);
logstream(LOG_WARNING)<<"Data: " << get_nz_data(datapoint, i) << " Pos: " << get_nz_index(datapoint, i) <<" cluster valu: " << cluster[pos]
<< "reduction: " << 2*get_nz_data(datapoint,i)*cluster[pos] << std::endl;
}
dist = 0;
}
return sqrt(fabs(dist)); //should not happen, but distance is sometime negative because of the shortcut we make to calculate it..
}
*/
flt_dbl calc_chebychev_distance( sparse_flt_dbl_vec & datapoint, sparse_flt_dbl_vec &cluster){
sparse_flt_dbl_vec diff = minus(datapoint , cluster);
flt_dbl ret = 0;
FOR_ITERATOR(i, diff){
ret = std::max(ret, (flt_dbl)fabs(get_nz_data(diff, i)));
}
return ret;
}
flt_dbl calc_chebychev_distance( sparse_flt_dbl_vec & datapoint, flt_dbl_vec &cluster){
flt_dbl_vec diff = minus(datapoint , cluster);
flt_dbl ret = 0;
for (int i=0; i< diff.size(); i++)
ret = std::max(ret, (flt_dbl)fabs(diff[i]));
return ret;
}
flt_dbl calc_manhatten_distance( sparse_flt_dbl_vec & datapoint, sparse_flt_dbl_vec &cluster){
sparse_flt_dbl_vec diff = minus(datapoint , cluster);
sparse_flt_dbl_vec absvec = fabs(diff);
flt_dbl ret = sum(absvec);
return ret;
}
flt_dbl calc_manhatten_distance( sparse_flt_dbl_vec & datapoint, flt_dbl_vec &cluster){
flt_dbl_vec diff = minus(datapoint , cluster);
flt_dbl ret = sum(fabs(diff));
return ret;
}
/* note that distance should be divided by intersection size */
flt_dbl calc_slope_one_distance( sparse_flt_dbl_vec & datapoint, sparse_flt_dbl_vec &cluster){
sparse_flt_dbl_vec diff = minus(datapoint , cluster);
flt_dbl ret = sum(diff);
return ret;
}
flt_dbl calc_cosine_distance( sparse_flt_dbl_vec & datapoint, sparse_flt_dbl_vec & cluster, flt_dbl sum_sqr, flt_dbl sum_sqr0){
flt_dbl dotprod = dot_prod(datapoint,cluster);
flt_dbl denominator = sqrt(sum_sqr0)*sqrt(sum_sqr);
return 1.0 - dotprod / denominator;
}
flt_dbl calc_cosine_distance( sparse_flt_dbl_vec & datapoint, flt_dbl_vec & cluster, flt_dbl sum_sqr, flt_dbl sum_sqr0){
flt_dbl dotprod = dot_prod(datapoint,cluster);
flt_dbl denominator = sqrt(sum_sqr0)*sqrt(sum_sqr);
return 1.0 - dotprod / denominator;
}
flt_dbl calc_dot_product_distance( sparse_flt_dbl_vec & datapoint, flt_dbl_vec & cluster){
return dot_prod(datapoint, cluster);
}
flt_dbl calc_dot_product_distance( sparse_flt_dbl_vec & datapoint, sparse_flt_dbl_vec & cluster){
return dot_prod(datapoint, cluster);
}
#endif //_DISTANCE_HPP__
| 09jijiangwen-download | toolkits/collaborative_filtering/distance.hpp | C++ | asf20 | 6,793 |
/**
* @file
* @author Danny Bickson, based on code by Aapo Kyrola <akyrola@cs.cmu.edu>
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file implements item based collaborative filtering by comparing all item pairs which
* are connected by one or more user nodes.
*
*
* For Pearson's correlation
*
* see: http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient
Cosine Similarity
See: http://en.wikipedia.org/wiki/Cosine_similarity
Manhattan Distance
See http://en.wikipedia.org/wiki/Taxicab_geometry
Log Similarity Distance
See http://tdunning.blogspot.co.il/2008/03/surprise-and-coincidence.html
Chebychev Distance
http://en.wikipedia.org/wiki/Chebyshev_distance
Tanimoto Distance
See http://en.wikipedia.org/wiki/Jaccard_index
*/
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <set>
#include <iostream>
#include "eigen_wrapper.hpp"
#include "distance.hpp"
#include "util.hpp"
#include "timer.hpp"
#include "common.hpp"
enum DISTANCE_METRICS{
JACKARD = 0,
AA = 1,
RA = 2,
PEARSON = 3,
COSINE = 4,
CHEBYCHEV = 5,
MANHATTEN = 6,
TANIMOTO = 7,
LOG_LIKELIHOOD = 8,
JACCARD_WEIGHT = 9
};
int min_allowed_intersection = 1;
size_t written_pairs = 0;
size_t item_pairs_compared = 0;
std::vector<FILE*> out_files;
timer mytimer;
vec mean;
vec stddev;
int grabbed_edges = 0;
int distance_metric;
int debug;
bool is_item(vid_t v){ return M == N ? true : v >= M; }
bool is_user(vid_t v){ return v < M; }
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef unsigned int VertexDataType;
typedef float EdgeDataType; // Edges store the "rating" of user->movie pair
struct vertex_data{
vec pvec;
vertex_data(){ }
void set_val(int index, float val){
pvec[index] = val;
}
float get_val(int index){
return pvec[index];
}
};
std::vector<vertex_data> latent_factors_inmem;
#include "io.hpp"
struct dense_adj {
sparse_vec edges;
dense_adj() { }
double intersect(const dense_adj & other){
sparse_vec x1 = edges.unaryExpr(std::ptr_fun(equal_greater));
sparse_vec x2 = other.edges.unaryExpr(std::ptr_fun(equal_greater));
sparse_vec x3 = x1.cwiseProduct(x2);
return sum(x3);
}
};
// This is used for keeping in-memory
class adjlist_container {
//mutex m;
public:
std::vector<dense_adj> adjs;
vid_t pivot_st, pivot_en;
adjlist_container() {
if (debug)
std::cout<<"setting pivot st and end to " << M << std::endl;
if (distance_metric == JACCARD_WEIGHT){
pivot_st = 0;
pivot_en = 0;
}
else {
pivot_st = M; //start pivor on item nodes (excluding user nodes)
pivot_en = M;
}
}
void clear() {
for(std::vector<dense_adj>::iterator it=adjs.begin(); it != adjs.end(); ++it) {
if (nnz(it->edges)) {
it->edges.resize(0);
}
}
adjs.clear();
if (debug)
std::cout<<"setting pivot end to " << pivot_en << std::endl;
pivot_st = pivot_en;
}
/**
* Extend the interval of pivot vertices to en.
*/
void extend_pivotrange(vid_t en) {
assert(en>pivot_en);
pivot_en = en;
adjs.resize(pivot_en - pivot_st);
}
/**
* Grab pivot's adjacency list into memory.
*/
int load_edges_into_memory(graphchi_vertex<VertexDataType, EdgeDataType> &v) {
//assert(is_pivot(v.id()));
//assert(is_item(v.id()));
int num_edges = v.num_edges();
//not enough user rated this item, we don't need to compare to it
if (num_edges < min_allowed_intersection){
if (debug)
logstream(LOG_DEBUG)<<"Skipping since num edges: " << num_edges << std::endl;
return 0;
}
// Count how many neighbors have larger id than v
dense_adj dadj;
for(int i=0; i<num_edges; i++)
set_new( dadj.edges, v.edge(i)->vertex_id(), v.edge(i)->get_data());
//std::sort(&dadj.adjlist[0], &dadj.adjlist[0] + num_edges);
adjs[v.id() - pivot_st] = dadj;
assert(v.id() - pivot_st < adjs.size());
__sync_add_and_fetch(&grabbed_edges, num_edges /*edges_to_larger_id*/);
return num_edges;
}
int acount(vid_t pivot) {
return nnz(adjs[pivot - pivot_st].edges);
}
/**
* calc distance between two items.
* Let a be all the users rated item 1
* Let b be all the users rated item 2
*
* 3) Using Pearson correlation
* Dist_ab = (a - mean)*(b- mean)' / (std(a)*std(b))
*
* 4) Using cosine similarity:
* Dist_ab = (a*b) / sqrt(sum_sqr(a)) * sqrt(sum_sqr(b)))
*
* 5) Using chebychev:
* Dist_ab = max(abs(a-b))
*
* 6) Using manhatten distance:
* Dist_ab = sum(abs(a-b))
*
* 7) Using tanimoto:
* Dist_ab = 1.0 - [(a*b) / (sum_sqr(a) + sum_sqr(b) - a*b)]
*
* 8) Using log likelihood similarity
* Dist_ab = 1.0 - 1.0/(1.0 + loglikelihood)
*
* 9) Using Jaccard:
* Dist_ab = intersect(a,b) / (size(a) + size(b) - intersect(a,b))
*/
double calc_distance(graphchi_vertex<VertexDataType, EdgeDataType> &v, vid_t pivot, int distance_metric) {
//assert(is_pivot(pivot));
//assert(is_item(pivot) && is_item(v.id()));
dense_adj &pivot_edges = adjs[pivot - pivot_st];
int num_edges = v.num_edges();
dense_adj item_edges;
for(int i=0; i < num_edges; i++){
set_new(item_edges.edges, v.edge(i)->vertexid, v.edge(i)->get_data());
}
if (distance_metric == JACCARD_WEIGHT){
return calc_jaccard_weight_distance(pivot_edges.edges, item_edges.edges, get_val( pivot_edges.edges, v.id()), 0);
}
return NAN;
}
inline bool is_pivot(vid_t vid) {
return vid >= pivot_st && vid < pivot_en;
}
};
adjlist_container * adjcontainer;
struct ItemDistanceProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Vertex update function.
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &v, graphchi_context &gcontext) {
if (debug)
printf("Entered iteration %d with %d - edges %d\n", gcontext.iteration, v.id(), v.num_edges());
/* even iteration numbers:
* 1) load a subset of items into memory (pivots)
* 2) Find which subset of items needs to compared to the users
*/
if (gcontext.iteration % 2 == 0) {
if (adjcontainer->is_pivot(v.id())){
adjcontainer->load_edges_into_memory(v);
if (debug)
printf("Loading pivot %d intro memory\n", v.id());
}
}
else {
for (vid_t i=adjcontainer->pivot_st; i< adjcontainer->pivot_en; i++){
//since metric is symmetric, compare only to pivots which are smaller than this item id
if (i >= v.id())
continue;
dense_adj &pivot_edges = adjcontainer->adjs[i - adjcontainer->pivot_st];
//pivot is not connected to this item, continue
if (get_val(pivot_edges.edges, v.id()) == 0)
continue;
double dist = adjcontainer->calc_distance(v, i, distance_metric);
item_pairs_compared++;
if (item_pairs_compared % 1000000 == 0)
logstream(LOG_INFO)<< std::setw(10) << mytimer.current_time() << ") " << std::setw(10) << item_pairs_compared << " pairs compared " << std::endl;
if (debug)
printf("comparing %d to pivot %d distance is %lg\n", i+ 1, v.id() + 1, dist);
if (dist != 0){
fprintf(out_files[omp_get_thread_num()], "%u %u %.12lg\n", v.id()+1, i+1, (double)dist);//write item similarity to file
//where the output format is:
//[item A] [ item B ] [ distance ]
written_pairs++;
}
}
}//end of iteration % 2 == 1
}//end of update function
/**
* Called before an iteration starts.
* On odd iteration, schedule both users and items.
* on even iterations, schedules only item nodes
*/
void before_iteration(int iteration, graphchi_context &gcontext) {
gcontext.scheduler->remove_tasks(0, (int) gcontext.nvertices - 1);
if (gcontext.iteration % 2 == 0){
for (vid_t i=0; i < M; i++){
gcontext.scheduler->add_task(i);
}
grabbed_edges = 0;
adjcontainer->clear();
} else { //iteration % 2 == 1
for (vid_t i=0; i< M; i++){
gcontext.scheduler->add_task(i);
}
}
}
/**
* Called after an iteration has finished.
*/
void after_iteration(int iteration, graphchi_context &gcontext) {
}
/**
* Called before an execution interval is started.
*
* On every even iteration, we load pivot's item connected user lists to memory.
* Here we manage the memory to ensure that we do not load too much
* edges into memory.
*/
void before_exec_interval(vid_t window_st, vid_t window_en, graphchi_context &gcontext) {
/* on even iterations, loads pivot items into memory base on the membudget_mb allowed memory size */
if ((gcontext.iteration % 2 == 0)) {
if (debug){
printf("entering iteration: %d on before_exec_interval\n", gcontext.iteration);
printf("pivot_st is %d window_en %d\n", adjcontainer->pivot_st, window_en);
}
if (adjcontainer->pivot_st <= window_en) {
size_t max_grab_edges = get_option_long("membudget_mb", 1024) * 1024 * 1024 / 8;
if (grabbed_edges < max_grab_edges * 0.8) {
logstream(LOG_DEBUG) << "Window init, grabbed: " << grabbed_edges << " edges" << " extending pivor_range to : " << window_en + 1 << std::endl;
adjcontainer->extend_pivotrange(window_en + 1);
logstream(LOG_DEBUG) << "Window en is: " << window_en << " vertices: " << gcontext.nvertices << std::endl;
if (window_en+1 == gcontext.nvertices) {
// every item was a pivot item, so we are done
logstream(LOG_DEBUG)<<"Setting last iteration to: " << gcontext.iteration + 2 << std::endl;
gcontext.set_last_iteration(gcontext.iteration + 2);
}
} else {
logstream(LOG_DEBUG) << "Too many edges, already grabbed: " << grabbed_edges << std::endl;
}
}
}
}
};
int main(int argc, const char ** argv) {
print_copyright();
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("item-cf2");
/* Basic arguments for application */
min_allowed_intersection = get_option_int("min_allowed_intersection", min_allowed_intersection);
distance_metric = get_option_int("distance", JACCARD_WEIGHT);
if (distance_metric != JACCARD_WEIGHT)
logstream(LOG_FATAL)<<"--distance_metrix=XX should be one of:9= JACCARD_WEIGHT" << std::endl;
debug = get_option_int("debug", 0);
parse_command_line_args();
//if (distance_metric != JACKARD && distance_metric != AA && distance_metric != RA)
// logstream(LOG_FATAL)<<"Wrong distance metric. --distance_metric=XX, where XX should be either 0) JACKARD, 1) AA, 2) RA" << std::endl;
mytimer.start();
int nshards = convert_matrixmarket<EdgeDataType>(training, NULL, 0, 0, 3, TRAINING, true);
assert(M > 0 && N > 0);
//initialize data structure which saves a subset of the items (pivots) in memory
adjcontainer = new adjlist_container();
/* Run */
ItemDistanceProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(training/*+orderByDegreePreprocessor->getSuffix()*/ ,nshards, true, m);
set_engine_flags(engine);
//open output files as the number of operating threads
out_files.resize(number_of_omp_threads());
for (uint i=0; i< out_files.size(); i++){
char buf[256];
sprintf(buf, "%s.out%d", training.c_str(), i);
out_files[i] = open_file(buf, "w");
}
//run the program
engine.run(program, niters);
/* Report execution metrics */
if (!quiet)
metrics_report(m);
std::cout<<"Total item pairs compared: " << item_pairs_compared << " total written to file: " << written_pairs << std::endl;
for (uint i=0; i< out_files.size(); i++)
fclose(out_files[i]);
std::cout<<"Created output files with the format: " << training << ".outXX, where XX is the output thread number" << std::endl;
return 0;
}
| 09jijiangwen-download | toolkits/collaborative_filtering/itemcf3.cpp | C++ | asf20 | 12,928 |
/**
* @file
* @author Danny Bickson, CMU
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* This program computes top K recommendations based on the linear model computed
* by one of: als,sparse_als,wals, sgd and nmf applications.
*
*/
#include "common.hpp"
#include "eigen_wrapper.hpp"
#include "timer.hpp"
int debug;
int num_ratings;
double knn_sample_percent = 1.0;
const double epsilon = 1e-16;
timer mytimer;
int tokens_per_row = 3;
int algo = 0;
enum {
ALS = 0, SPARSE_ALS = 1, SGD = 2, NMF = 3, WALS = 4
};
struct vertex_data {
vec ratings;
ivec ids;
vec pvec;
vertex_data() {
pvec = vec::Zero(D);
ids = ivec::Zero(num_ratings);
ratings = vec::Zero(num_ratings);
}
void set_val(int index, float val){
pvec[index] = val;
}
float get_val(int index){
return pvec[index];
}
};
struct edge_data {
double weight;
edge_data() { weight = 0; }
edge_data(double weight) : weight(weight) { }
};
struct edge_data4 {
double weight;
double time;
edge_data4() { weight = time = 0; }
edge_data4(double weight, double time) : weight(weight), time(time) { }
};
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vertex_data VertexDataType;
typedef edge_data EdgeDataType; // Edges store the "rating" of user->movie pair
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
std::vector<vertex_data> latent_factors_inmem;
float als_predict(const vertex_data& user,
const vertex_data& movie,
const float rating,
double & prediction){
prediction = dot_prod(user.pvec, movie.pvec);
//truncate prediction to allowed values
prediction = std::min((double)prediction, maxval);
prediction = std::max((double)prediction, minval);
//return the squared error
float err = rating - prediction;
assert(!std::isnan(err));
return err*err;
}
void rating_stats(){
double min=1e100, max=0, avg=0;
int cnt = 0;
int startv = 0;
int endv = M;
for (int i=startv; i< endv; i++){
vertex_data& data = latent_factors_inmem[i];
if (data.ratings.size() > 0){
min = std::min(min, data.ratings[0]);
max = std::max(max, data.ratings[0]);
if (std::isnan(data.ratings[0]))
printf("bug: nan on %d\n", i);
else {
avg += data.ratings[0];
cnt++;
}
}
}
printf("Distance statistics: min %g max %g avg %g\n", min, max, avg/cnt);
}
#include "io.hpp"
void read_factors(std::string base_filename){
load_matrix_market_matrix(training + "_U.mm", 0, D);
load_matrix_market_matrix(training + "_V.mm", M, D);
}
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
template<typename VertexDataType, typename EdgeDataType>
struct RatingVerticesInMemProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Vertex update function - computes the least square step
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
//compute only for user nodes
if (vertex.id() >= M)
return;
vertex_data & vdata = latent_factors_inmem[vertex.id()];
int howmany = (int)(N*knn_sample_percent);
assert(howmany > 0 );
vec distances = zeros(howmany);
ivec indices = ivec::Zero(howmany);
for (int i=0; i< howmany; i++){
indices[i]= -1;
}
std::vector<bool> curratings;
curratings.resize(N);
for(int e=0; e < vertex.num_edges(); e++) {
//no need to calculate this rating since it is given in the training data reference
assert(vertex.edge(e)->vertex_id() - M >= 0 && vertex.edge(e)->vertex_id() - M < N);
curratings[vertex.edge(e)->vertex_id() - M] = true;
}
if (knn_sample_percent == 1.0){
for (uint i=M; i< M+N; i++){
if (curratings[i-M])
continue;
vertex_data & other = latent_factors_inmem[i];
double dist;
als_predict(vdata, other, 0, dist);
indices[i-M] = i-M;
distances[i-M] = dist + 1e-10;
}
}
else for (int i=0; i<howmany; i++){
int random_other = ::randi(M, M+N-1);
vertex_data & other = latent_factors_inmem[random_other];
double dist;
als_predict(vdata, other, 0, dist);
indices[i] = random_other-M;
distances[i] = dist;
}
vec out_dist(num_ratings);
ivec indices_sorted = reverse_sort_index2(distances, indices, out_dist, num_ratings);
assert(indices_sorted.size() <= num_ratings);
assert(out_dist.size() <= num_ratings);
vdata.ids = indices_sorted;
vdata.ratings = out_dist;
if (debug)
printf("Closest is: %d with distance %g\n", (int)vdata.ids[0], vdata.ratings[0]);
if (vertex.id() % 1000 == 0)
printf("Computing recommendations for user %d at time: %g\n", vertex.id()+1, mytimer.current_time());
}
};
struct MMOutputter_ratings{
MMOutputter_ratings(std::string fname, uint start, uint end, std::string comment) {
assert(start < end);
MM_typecode matcode;
set_matcode(matcode);
FILE * outf = fopen(fname.c_str(), "w");
assert(outf != NULL);
mm_write_banner(outf, matcode);
if (comment != "")
fprintf(outf, "%%%s\n", comment.c_str());
mm_write_mtx_array_size(outf, end-start, num_ratings+1);
for (uint i=start; i < end; i++){
fprintf(outf, "%u ", i+1);
for(int j=0; j < latent_factors_inmem[i].ratings.size(); j++) {
fprintf(outf, "%1.12e ", latent_factors_inmem[i].ratings[j]);
}
fprintf(outf, "\n");
}
fclose(outf);
}
};
struct MMOutputter_ids{
MMOutputter_ids(std::string fname, uint start, uint end, std::string comment) {
assert(start < end);
MM_typecode matcode;
set_matcode(matcode);
FILE * outf = fopen(fname.c_str(), "w");
assert(outf != NULL);
mm_write_banner(outf, matcode);
if (comment != "")
fprintf(outf, "%%%s\n", comment.c_str());
mm_write_mtx_array_size(outf, end-start, num_ratings+1);
for (uint i=start; i < end; i++){
fprintf(outf, "%u ", i+1);
for(int j=0; j < latent_factors_inmem[i].ids.size(); j++) {
fprintf(outf, "%u ", (int)latent_factors_inmem[i].ids[j]+1);//go back to item ids starting from 1,2,3, (and not from zero as in c)
}
fprintf(outf, "\n");
}
fclose(outf);
}
};
void output_knn_result(std::string filename) {
MMOutputter_ratings ratings(filename + ".ratings", 0, M,"This file contains user scalar ratings. In each row i, num_ratings top scalar ratings of different items for user i. (First column: user id, next columns, top K ratings)");
MMOutputter_ids mmoutput_ids(filename + ".ids", 0, M ,"This file contains item ids matching the ratings. In each row i, num_ratings top item ids for user i. (First column: user id, next columns, top K ratings). Note: 0 item id means there are no more items to recommend for this user.");
std::cout << "Rating output files (in matrix market format): " << filename << ".ratings" <<
", " << filename + ".ids " << std::endl;
}
int main(int argc, const char ** argv) {
mytimer.start();
print_copyright();
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("nmf-inmemory-factors");
knn_sample_percent = get_option_float("knn_sample_percent", 1.0);
if (knn_sample_percent <= 0 || knn_sample_percent > 1)
logstream(LOG_FATAL)<<"Sample percente should be in the range (0, 1] " << std::endl;
num_ratings = get_option_int("num_ratings", 10);
if (num_ratings <= 0)
logstream(LOG_FATAL)<<"num_ratings, the number of recomended items for each user, should be >=1 " << std::endl;
debug = get_option_int("debug", 0);
std::string algorithm = get_option_string("algorithm");
if (algorithm == "als" || algorithm == "sparse_als" || algorithm == "sgd" || algorithm == "nmf")
tokens_per_row = 3;
else if (algorithm == "wals")
tokens_per_row = 4;
else logstream(LOG_FATAL)<<"--algorithms should be one of: als, sparse_als, sgd, nmf, wals" << std::endl;
parse_command_line_args();
/* Preprocess data if needed, or discover preprocess files */
int nshards = 0;
if (tokens_per_row == 3)
nshards = convert_matrixmarket<edge_data>(training, NULL, 0, 0, 3, TRAINING, false);
else if (tokens_per_row == 4)
nshards = convert_matrixmarket4<edge_data4>(training);
else logstream(LOG_FATAL)<<"--tokens_per_row should be either 3 or 4" << std::endl;
assert(M > 0 && N > 0);
latent_factors_inmem.resize(M+N); // Initialize in-memory vertices.
read_factors(training);
if ((uint)num_ratings > N){
logstream(LOG_WARNING)<<"num_ratings is too big - setting it to: " << N << std::endl;
num_ratings = N;
}
srand(time(NULL));
/* Run */
if (tokens_per_row == 3){
RatingVerticesInMemProgram<VertexDataType, EdgeDataType> program;
graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m);
set_engine_flags(engine);
engine.run(program, 1);
}
else if (tokens_per_row == 4){
RatingVerticesInMemProgram<VertexDataType, edge_data4> program;
graphchi_engine<VertexDataType, edge_data4> engine(training, nshards, false, m);
set_engine_flags(engine);
engine.run(program, 1);
}
/* Output latent factor matrices in matrix-market format */
output_knn_result(training);
rating_stats();
/* Report execution metrics */
if (!quiet)
metrics_report(m);
return 0;
}
| 09jijiangwen-download | toolkits/collaborative_filtering/rating.cpp | C++ | asf20 | 10,409 |
/**
* @file
* @author Danny Bickson
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* Implementation of the gensgd algorithm. A generalization of SGD algorithm when there are multiple features for each
* rating, in the form
* [from] [to] [feature1] [feature2] [feature3] ... [featureN] [rating]
* (It is also possible to dynamically specify column numbers which are relevant)
* Steffen Rendle (2010): Factorization Machines, in Proceedings of the 10th IEEE International Conference on Data Mining (ICDM 2010), Sydney, Australia.
* Original implementation by Qiang Yan, Chinese Academy of Science.
* note: this code version implements the SGD version of gensgd. In the original library there are also ALS and MCMC methods.
* Also the treatment of features is richer in gensgd. The code here can serve for a quick evaluation but the user
* is encouraged to try gensgd as well.
*/
#include <vector>
#include "common.hpp"
#include "eigen_wrapper.hpp"
#include "../parsers/common.hpp"
#include <omp.h>
#define MAX_FEATAURES 256
#define FEATURE_WIDTH 56//MAX NUMBER OF ALLOWED FEATURES IN TEXT FILE
double gensgd_rate1 = 1e-02;
double gensgd_rate2 = 1e-02;
double gensgd_rate3 = 1e-02;
double gensgd_rate4 = 1e-02;
double gensgd_rate5 = 1e-02;
double gensgd_mult_dec = 0.9;
double gensgd_regw = 1e-3;
double gensgd_regv = 1e-3;
double gensgd_reg0 = 1e-1;
bool debug = false;
std::string user_file; //optional file with user features
std::string item_file; //optional file with item features
std::string user_links; //optional file with user to user links
int limit_rating = 0;
size_t vertex_with_no_edges = 0;
int calc_error = 0;
int calc_roc = 0;
int binary = 1;
int round_float = 0;
std::vector<std::string> header_titles;
int has_header_titles = 0;
float cutoff = 0;
float val_cutoff = 0;
std::string format = "libsvm";
vec errors_vec;
struct single_map{
std::map<float,uint> string2nodeid;
single_map(){
}
};
struct feature_control{
std::vector<single_map> node_id_maps;
single_map val_map;
single_map index_map;
int rehash_value;
int feature_num;
int node_features;
int node_links;
int total_features;
const std::string default_feature_str;
std::vector<int> offsets;
bool hash_strings;
int from_pos;
int to_pos;
int val_pos;
feature_control(){
rehash_value = 0;
total_features = 0;
node_features = 0;
feature_num = FEATURE_WIDTH;
hash_strings = false;
from_pos = 0;
to_pos = 1;
val_pos = -1;
node_links = 0;
}
};
feature_control fc;
int num_feature_bins(){
int sum = 0;
if (fc.hash_strings){
assert(2+fc.total_features+fc.node_features == (int)fc.node_id_maps.size());
for (int i=2; i < 2+fc.total_features+fc.node_features; i++){
sum+= fc.node_id_maps[i].string2nodeid.size();
}
}
else assert(false);
return sum;
}
int calc_feature_num(){
return 2+fc.total_features+fc.node_features;
}
void get_offsets(std::vector<int> & offsets){
assert(offsets.size() > 3);
offsets[0] = 0;
offsets[1] = M;
offsets[2] = M+N;
for (uint i=3; i< offsets.size(); i++){
assert(fc.node_id_maps.size() > (uint)i);
offsets[i] += offsets[i-1] + fc.node_id_maps[i].string2nodeid.size();
}
}
bool is_user(vid_t id){ return id < M; }
bool is_item(vid_t id){ return id >= M && id < N; }
bool is_time(vid_t id){ return id >= M+N; }
#define BIAS_POS -1
struct vertex_data {
fvec pvec;
double bias;
vertex_data() {
bias = 0;
}
void set_val(int index, float val){
if (index == BIAS_POS)
bias = val;
else pvec[index] = val;
}
float get_val(int index){
if (index== BIAS_POS)
return bias;
else return pvec[index];
}
};
struct edge_data {
uint features[FEATURE_WIDTH];
uint index[FEATURE_WIDTH];
uint size;
float weight;
edge_data() {
weight = 0;
size = 0;
memset(features, 0, sizeof(uint)*FEATURE_WIDTH);
memset(index, 0, sizeof(uint)*FEATURE_WIDTH);
}
edge_data(float weight, uint * valarray, uint * _index, uint size): size(size), weight(weight) {
memcpy(features, valarray, sizeof(uint)*FEATURE_WIDTH);
memcpy(index, _index, sizeof(uint)*FEATURE_WIDTH);
}
};
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vertex_data VertexDataType;
typedef edge_data EdgeDataType; // Edges store the "rating" of user->movie pair
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
std::vector<vertex_data> latent_factors_inmem;
int calc_feature_node_array_size(uint node, uint item, uint edge_size){
assert(node <= M);
assert(item <= N);
assert(edge_size >= 0);
assert(node < latent_factors_inmem.size());
assert(fc.offsets[1]+item < latent_factors_inmem.size());
return 2+edge_size;
}
void assign_id(single_map& dmap, unsigned int & outval, const float name){
std::map<float,uint>::iterator it = dmap.string2nodeid.find(name);
//if an id was already assigned, return it
if (it != dmap.string2nodeid.end()){
outval = it->second - 1;
assert(outval < dmap.string2nodeid.size());
return;
}
mymutex.lock();
//assign a new id
outval = dmap.string2nodeid[name];
if (outval == 0){
dmap.string2nodeid[name] = dmap.string2nodeid.size();
outval = dmap.string2nodeid.size() - 1;
}
mymutex.unlock();
}
/**
* return a numeric node ID out of the string text read from file (training, validation or test)
*/
float get_node_id(char * pch, int pos, size_t i, bool read_only = false){
assert(pch != NULL);
assert(pch[0] != 0);
assert(i >= 0);
float ret;
//read numeric id
if (!fc.hash_strings){
ret = (pos < 2 ? atoi(pch) : atof(pch));
if (pos < 2)
ret--;
if (pos == 0 && ret >= M)
logstream(LOG_FATAL)<<"Row index larger than the matrix row size " << ret << " > " << M << " in line: " << i << std::endl;
else if (pos == 1 && ret >= N)
logstream(LOG_FATAL)<<"Col index larger than the matrix row size " << ret << " > " << N << " in line: " << i << std::endl;
}
//else read string id and assign numeric id
else {
uint id;
float val = atof(pch);
assert(!std::isnan(val));
if (round_float)
val = floorf(val * 10000 + 0.5) / 10000;
if (pos >= 0)
assert(pos < (int)fc.node_id_maps.size());
single_map * pmap = NULL;
if (pos == -1)
pmap = &fc.index_map;
else pmap = &fc.node_id_maps[pos];
if (read_only){ // find if node was in map
std::map<float,uint>::iterator it = pmap->string2nodeid.find(val);
if (it != pmap->string2nodeid.end()){
ret = it->second - 1;
assert(ret < pmap->string2nodeid.size());
}
else ret = -1;
}
else { //else enter node into map (in case it did not exist) and return its position
assign_id(*pmap, id, val);
if (pos == -1 && fc.index_map.string2nodeid.size() == id+1 && fc.node_id_maps.size() < fc.index_map.string2nodeid.size()+2){//TODO debug
single_map newmap;
fc.node_id_maps.push_back(newmap);
}
ret = id;
}
}
if (!read_only)
assert(ret != -1);
return ret;
}
#include "io.hpp"
#include "../parsers/common.hpp"
float get_value(char * pch, bool read_only){
float ret;
if (!fc.rehash_value){
ret = atof(pch);
}
else {
uint id;
if (read_only){ // find if node was in map
std::map<float,uint>::iterator it = fc.val_map.string2nodeid.find(atof(pch));
if (it != fc.val_map.string2nodeid.end()){
ret = it->second - 1;
}
else ret = -1;
}
else { //else enter node into map (in case it did not exist) and return its position
assign_id(fc.val_map, id, atof(pch));
ret = id;
}
}
if (std::isnan(ret) || std::isinf(ret))
logstream(LOG_FATAL)<<"Failed to read value" << std::endl;
return ret;
}
/* Read and parse one input line from file */
bool read_line(FILE * f, const std::string filename, size_t i, uint & I, uint & J, float &val, std::vector<uint>& valarray, std::vector<uint>& positions, int & index, int type, int & skipped_features){
char * linebuf = NULL;
size_t linesize;
char linebuf_debug[1024];
int token = 0;
index = 0;
int rc = getline(&linebuf, &linesize, f);
if (rc == -1)
logstream(LOG_FATAL)<<"Failed to get line: " << i << " in file: " << filename << std::endl;
char * linebuf_to_free = linebuf;
strncpy(linebuf_debug, linebuf, 1024);
while (index < FEATURE_WIDTH){
/* READ FROM */
if (token == fc.from_pos){
char *pch = strsep(&linebuf,"\t,\r\n: ");
if (pch == NULL)
logstream(LOG_FATAL)<<"Error reading line " << i << " [ " << linebuf_debug << " ] " << std::endl;
I = (uint)get_node_id(pch, 0, i, type != TRAINING);
uint pos = get_node_id(pch, -1, i, type != TRAINING);
token++;
if (type != TRAINING && pos == (uint)-1){ //this feature was not observed on training, skip
continue;
}
valarray[index] = 0;
positions[index] = pos;
index++;
}
else if (token == fc.to_pos){
/* READ TO */
char * pch = strsep(&linebuf, "\t,\r\n: ");
if (pch == NULL)
logstream(LOG_FATAL)<<"Error reading line " << i << " [ " << linebuf_debug << " ] " << std::endl;
J = (uint)get_node_id(pch, 1, i, type != TRAINING);
token++;
}
else if (token == fc.val_pos){
/* READ RATING */
char * pch = strsep(&linebuf, "\t,\r\n ");
if (pch == NULL)
logstream(LOG_FATAL)<<"Error reading line " << i << " [ " << linebuf_debug << " ] " << std::endl;
val = get_value(pch, type != TRAINING);
token++;
}
else {
/* READ FEATURES */
char * pch = strsep(&linebuf, "\t,\r\n:; ");
if (pch == NULL || pch[0] == 0)
break;
uint pos = get_node_id(pch, -1, i, type != TRAINING);
if (type != TRAINING && pos == (uint)-1){ //this feature was not observed on training, skip
char * pch2 = strsep(&linebuf, "\t\r\n ");
if (pch2 == NULL || pch2[0] == 0)
logstream(LOG_FATAL)<<"Error reading line " << i << " feature2 " << index << " [ " << linebuf_debug << " ] " << std::endl;
skipped_features++;
continue;
}
assert(pos != (uint)-1 && pos < fc.index_map.string2nodeid.size());
char * pch2 = strsep(&linebuf, "\t\r\n ");
if (pch2 == NULL || pch2[0] == 0)
logstream(LOG_FATAL)<<"Error reading line " << i << " feature2 " << index << " [ " << linebuf_debug << " ] " << std::endl;
uint second_index = get_node_id(pch2, pos, i, type != TRAINING);
if (type != TRAINING && second_index == (uint)-1){ //this value was not observed in training, skip
second_index = 0; //skipped_features++;
//continue;
}
assert(second_index != (uint)-1);
assert(index< (int)valarray.size());
assert(index< (int)positions.size());
valarray[index] = second_index;
positions[index] = pos;
index++;
token++;
}
}//end while
free(linebuf_to_free);
return true;
}//end read_line
/* compute an edge prediction based on input features */
float compute_prediction(
uint I,
uint J,
const float val,
double & prediction,
uint * valarray,
uint * positions,
uint edge_size,
float (*prediction_func)(std::vector<vertex_data*>& node_array, int arraysize, float rating, double & prediction, fvec * psumi, double * exp_prediction),
fvec * psum,
std::vector<vertex_data*>& node_array,
uint node_array_size,
double & exp_prediction){
/* COMPUTE PREDICTION */
/* USER NODE **/
int index = 0;
int loc = 0;
node_array[index] = &latent_factors_inmem[I+fc.offsets[index]];
assert(node_array[index]->pvec[0] < 1e5);
index++; loc++;
/* 1) ITEM NODE */
assert(J+fc.offsets[index] < latent_factors_inmem.size());
node_array[index] = &latent_factors_inmem[J+fc.offsets[index]];
assert(node_array[index]->pvec[0] < 1e5);
index++; loc++;
/* 2) FEATURES GIVEN IN RATING LINE */
for (int j=0; j< (int)edge_size; j++){
assert(fc.offsets.size() > positions[j]);
uint pos = fc.offsets[positions[j]] + valarray[j];
assert(pos >= 0 && pos < latent_factors_inmem.size());
assert(j+index < (int)node_array_size);
node_array[j+index] = & latent_factors_inmem[pos];
assert(node_array[j+index]->pvec[0] < 1e5);
}
index+= edge_size;
loc += edge_size;
assert(index == calc_feature_node_array_size(I,J, edge_size));
return (*prediction_func)(node_array, node_array_size, val, prediction, psum, &exp_prediction);
}
#include "rmse.hpp"
/**
* Create a bipartite graph from a matrix. Each row corresponds to vertex
* with the same id as the row number (0-based), but vertices correponsing to columns
* have id + num-rows.
* Line format of the type
* [user] [item] [feature1] [feature2] ... [featureN] [rating]
*/
/* Read input file, process it and save a binary representation for faster loading */
template <typename als_edge_type>
int convert_matrixmarket_N(std::string base_filename, bool square, feature_control & fc, int limit_rating = 0) {
// Note, code based on: http://math.nist.gov/MatrixMarket/mmio/c/example_read.c
FILE *f;
size_t nz;
/**
* Create sharder object
*/
int nshards;
sharder<als_edge_type> sharderobj(base_filename);
sharderobj.start_preprocessing();
detect_matrix_size(base_filename, f, M, N, nz);
/* if .info file is not present, try to find matrix market header inside the base_filename file */
if (format == "libsvm")
assert(!has_header_titles);
if (has_header_titles){
char * linebuf = NULL;
size_t linesize;
char linebuf_debug[1024];
/* READ LINE */
int rc = getline(&linebuf, &linesize, f);
if (rc == -1)
logstream(LOG_FATAL)<<"Error header line " << " [ " << linebuf_debug << " ] " << std::endl;
strncpy(linebuf_debug, linebuf, 1024);
/** READ [FROM] */
char *pch = strtok(linebuf,"\t,\r; ");
if (pch == NULL)
logstream(LOG_FATAL)<<"Error header line " << " [ " << linebuf_debug << " ] " << std::endl;
header_titles.push_back(pch);
/** READ USER FEATURES */
while (pch != NULL){
pch = strtok(NULL, "\t,\r; ");
if (pch == NULL)
break;
header_titles.push_back(pch);
//update stats if needed
}
}
if (M == 0 && N == 0)
logstream(LOG_FATAL)<<"Failed to detect matrix size. Please prepare a file named: " << base_filename << ":info with matrix market header, as explained here: http://bickson.blogspot.co.il/2012/12/collaborative-filtering-3rd-generation_14.html " << std::endl;
logstream(LOG_INFO) << "Starting to read matrix-market input. Matrix dimensions: " << M << " x " << N << ", non-zeros: " << nz << std::endl;
uint I, J;
std::vector<uint> valarray; valarray.resize(FEATURE_WIDTH);
std::vector<uint> positions; positions.resize(FEATURE_WIDTH);
float val;
if (limit_rating > 0)
nz = limit_rating;
int skipped_features = 0;
for (size_t i=0; i<nz; i++)
{
int index;
if (!read_line(f, base_filename, i,I, J, val, valarray, positions, index, TRAINING, skipped_features))
logstream(LOG_FATAL)<<"Failed to read line: " <<i<< " in file: " << base_filename << std::endl;
if (index < 1)
logstream(LOG_FATAL)<<"Failed to read line: " <<i<< " in file: " << base_filename << std::endl;
if (nz > 1000000 && (i % 1000000) == 0)
logstream(LOG_INFO)<< mytimer.current_time() << " Finished reading " << i << " lines " << std::endl;
//calc stats
L++;
globalMean += val;
sharderobj.preprocessing_add_edge(I, square?J:M+J, als_edge_type(val, &valarray[0], &positions[0], index));
}
sharderobj.end_preprocessing();
//calc stats
assert(L > 0);
assert(globalMean != 0);
globalMean /= L;
std::cout<<"Coputed global mean is: " << globalMean << std::endl;
fclose(f);
logstream(LOG_INFO) << "Now creating shards." << std::endl;
// Shard with a specified number of shards, or determine automatically if not defined
nshards = sharderobj.execute_sharding(get_option_string("nshards", "auto"));
return nshards;
}
static bool mySort(const std::pair<double, double> &p1,const std::pair<double, double> &p2)
{
return p1.second > p2.second;
}
/**
compute validation rmse
*/
void validation_rmse_N(
float (*prediction_func)(std::vector<vertex_data*>& array, int arraysize, float rating, double & prediction, fvec * psum, double * exp_prediction)
,graphchi_context & gcontext,
feature_control & fc,
bool square = false) {
if (validation == "")
return;
FILE * f = NULL;
size_t nz = 0;
detect_matrix_size(validation, f, Me, Ne, nz);
if (f == NULL){
logstream(LOG_WARNING)<<"Failed to open validation file: " << validation << " - skipping."<<std::endl;
return;
}
if ((M > 0 && N > 0) && (Me != M || Ne != N))
logstream(LOG_WARNING)<<"Input size of validation matrix must be identical to training matrix, namely " << M << "x" << N << std::endl;
Le = nz;
last_validation_rmse = dvalidation_rmse;
dvalidation_rmse = 0;
std::vector<uint> valarray; valarray.resize(FEATURE_WIDTH);
std::vector<uint> positions; positions.resize(FEATURE_WIDTH);
uint I, J;
float val;
int skipped_features = 0;
int skipped_nodes = 0;
int errors = 0;
//FOR ROC. ROC code thanks to Justin Yan.
double _M = 0;
double _N = 0;
std::vector<std::pair<double, double> > realPrediction;
double avg_pred = 0;
for (size_t i=0; i<nz; i++)
{
int index;
if (!read_line(f, validation, i, I, J, val, valarray, positions, index, VALIDATION, skipped_features))
logstream(LOG_FATAL)<<"Failed to read line: " << i << " in file: " << validation << std::endl;
if (I == (uint)-1 || J == (uint)-1){
skipped_nodes++;
continue;
}
double prediction;
int howmany = calc_feature_node_array_size(I,J, index);
std::vector<vertex_data*> node_array; node_array.resize(howmany);
for (int k=0; k< howmany; k++)
node_array[k] = NULL;
fvec sum;
double exp_prediction = 0;
dvalidation_rmse += compute_prediction(I, J, val, prediction, &valarray[0], &positions[0], index, prediction_func, &sum, node_array, howmany, exp_prediction);
avg_pred += prediction;
if (calc_roc)
realPrediction.push_back(std::make_pair(val, exp_prediction));
if (prediction < cutoff && val >= val_cutoff)
errors++;
else if (prediction >= cutoff && val < val_cutoff)
errors++;
}
fclose(f);
std::cout<<"avg validation prediction: " << avg_pred/(double)nz << std::endl;
assert(Le > 0);
dvalidation_rmse = finalize_rmse(dvalidation_rmse , (double)(Le-skipped_nodes));
std::cout<<" Validation " << error_names[loss_type] << " : " << std::setw(10) << dvalidation_rmse;
if (calc_error)
std::cout<<" Validation Err: " << std::setw(10) << ((double)errors/(double)(nz-skipped_nodes));
if (calc_roc){
double roc = 0;
double ret = 0;
std::vector<double> L;
std::sort(realPrediction.begin(), realPrediction.end(),mySort);
std::vector<std::pair<double, double> >::iterator iter;
for(iter=realPrediction.begin();iter!=realPrediction.end();iter++)
{
L.push_back(iter->first);
if(iter->first > cutoff) _M++;
else _N++;
}
std::vector<double>:: iterator iter2;
int i=0;
for(iter2=L.begin();iter2!=L.end();iter2++)
{
if(*iter2 > cutoff) ret += ((_M+_N) - i);
i++;
}
double ret2 = _M *(_M+1)/2;
roc= (ret-ret2)/(_M*_N);
std::cout<<" Validation ROC: " << roc << std::endl;
}
else std::cout<<std::endl;
if (halt_on_rmse_increase && dvalidation_rmse > last_validation_rmse && gcontext.iteration > 0){
logstream(LOG_WARNING)<<"Stopping engine because of validation RMSE increase" << std::endl;
gcontext.set_last_iteration(gcontext.iteration);
}
if (skipped_features > 0)
std::cout<<"Skipped " << skipped_features << " when reading from file. " << std::endl;
if (skipped_nodes > 0)
std::cout<<"Skipped " << skipped_nodes << " when reading from file. " << std::endl;
}
/* compute predictions for test data */
void test_predictions_N(
float (*prediction_func)(std::vector<vertex_data*>& node_array, int node_array_size, float rating, double & prediction, fvec * sum, double * exp_prediction),
feature_control & fc,
bool square = false) {
FILE *f = NULL;
uint Me, Ne;
size_t nz;
if (test == ""){
logstream(LOG_INFO)<<"No test file was found, skipping test predictions " << std::endl;
return;
}
detect_matrix_size(test, f, Me, Ne, nz);
if (f == NULL){
logstream(LOG_WARNING)<<"Failed to open test file " << test<< " skipping test predictions " << std::endl;
return;
}
if ((M > 0 && N > 0 ) && (Me != M || Ne != N))
logstream(LOG_FATAL)<<"Input size of test matrix must be identical to training matrix, namely " << M << "x" << N << std::endl;
FILE * fout = open_file((test + ".predict").c_str(),"w", false);
MM_typecode matcode;
mm_set_array(&matcode);
mm_write_banner(fout, matcode);
mm_write_mtx_array_size(fout ,nz, 1);
std::vector<uint> valarray; valarray.resize(FEATURE_WIDTH);
std::vector<uint> positions; positions.resize(FEATURE_WIDTH);
float val;
double prediction;
uint I,J;
int skipped_features = 0;
int skipped_nodes = 0;
for (uint i=0; i<nz; i++)
{
int index;
if (!read_line(f, test, i, I, J, val, valarray, positions, index, TEST, skipped_features))
logstream(LOG_FATAL)<<"Failed to read line: " <<i << " in file: " << test << std::endl;
if (I == (uint)-1 || J == (uint)-1){
skipped_nodes++;
fprintf(fout, "%d\n", 0); //features for this node are not found in the training set, write a default value
continue;
}
int howmany = calc_feature_node_array_size(I,J,index);
std::vector<vertex_data*> node_array; node_array.resize(howmany);
for (int k=0; k< howmany; k++)
node_array[k] = NULL;
fvec sum;
double exp_prediction = 0;
compute_prediction(I, J, val, prediction, &valarray[0], &positions[0], index, prediction_func, &sum, node_array, howmany, exp_prediction);
fprintf(fout, "%12.8lg\n", prediction);
}
fclose(f);
fclose(fout);
logstream(LOG_INFO)<<"Finished writing " << nz << " predictions to file: " << test << ".predict" << std::endl;
if (skipped_features > 0)
logstream(LOG_DEBUG)<<"Skipped " << skipped_features << " when reading from file. " << std::endl;
if (skipped_nodes > 0)
logstream(LOG_WARNING)<<"Skipped node in test dataset: " << skipped_nodes << std::endl;
}
float gensgd_predict(std::vector<vertex_data*> & node_array, int node_array_size,
const float rating, double& prediction, fvec* sum, double * extra){
fvec sum_sqr = fzeros(D);
*sum = fzeros(D);
prediction = globalMean/maxval;
assert(!std::isnan(prediction));
for (int i=0; i< node_array_size; i++)
prediction += node_array[i]->bias;
assert(!std::isnan(prediction));
for (int j=0; j< D; j++){
for (int i=0; i< node_array_size; i++){
sum->operator[](j) += node_array[i]->pvec[j];
assert(sum->operator[](j) < 1e5);
sum_sqr[j] += pow(node_array[i]->pvec[j],2);
}
prediction += 0.5 * (pow(sum->operator[](j),2) - sum_sqr[j]);
assert(!std::isnan(prediction));
}
//truncate prediction to allowed values
double exp_prediction = 1.0 / (1.0 + exp(-prediction));
prediction = minval + exp_prediction *(maxval-minval);
//prediction = std::min((double)prediction, maxval);
//prediction = std::max((double)prediction, minval);
//return the squared error
float err = rating - prediction;
if (extra != NULL)
*(double*)extra = exp_prediction;
return calc_loss(exp_prediction, err);
}
void init_gensgd(bool load_factors_from_file){
srand(time(NULL));
int nodes = M+N+num_feature_bins();
latent_factors_inmem.resize(nodes);
int howmany = calc_feature_num();
logstream(LOG_DEBUG)<<"Going to calculate: " << howmany << " offsets." << std::endl;
fc.offsets.resize(howmany);
get_offsets(fc.offsets);
assert(D > 0);
if (!load_factors_from_file){
double factor = 0.1/sqrt(D);
#pragma omp parallel for
for (int i=0; i< nodes; i++){
latent_factors_inmem[i].pvec = (debug ? 0.1*fones(D) : (::frandu(D)*factor));
}
}
}
void training_rmse_N(int iteration, graphchi_context &gcontext, bool items = false){
last_training_rmse = dtraining_rmse;
dtraining_rmse = 0;
size_t total_errors = 0;
int start = 0;
int end = M;
if (items){
start = M;
end = M+N;
}
dtraining_rmse = sum(rmse_vec);
if (calc_error){
total_errors = sum(errors_vec);
}
dtraining_rmse = finalize_rmse(dtraining_rmse, (double)pengine->num_edges());
if (calc_error)
std::cout<< std::setw(10) << mytimer.current_time() << ") Iteration: " << std::setw(3) <<iteration<<" Training " << error_names[loss_type] << " : " <<std::setw(10)<< dtraining_rmse << " Train err: " << std::setw(10) << (total_errors/(double)L);
else
std::cout<< std::setw(10) << mytimer.current_time() << ") Iteration: " << std::setw(3) <<iteration<<" Training " << error_names[loss_type] << " : " << std::setw(10)<< dtraining_rmse;
}
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct Sparse_GensgdVerticesInMemProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/*
* Vertex update function - computes the least square step
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
//go over all user nodes
if (is_user(vertex.id())){
//go over all observed ratings
for(int e=0; e < vertex.num_outedges(); e++) {
const edge_data & data = vertex.edge(e)->get_data();
int howmany = calc_feature_node_array_size(vertex.id(), vertex.edge(e)->vertex_id()-M, data.size);
std::vector<vertex_data*> node_array; node_array.resize(howmany);
for (int i=0; i< howmany; i++)
node_array[i] = NULL;
float rui = data.weight;
double pui;
fvec sum;
//compute current prediction
double exp_prediction = 0;
rmse_vec[omp_get_thread_num()] += compute_prediction(vertex.id(), vertex.edge(e)->vertex_id()-M, rui ,pui, (uint*)data.features, (uint*)data.index, data.size, gensgd_predict, &sum, node_array, howmany, exp_prediction);
if (calc_error){
if ((pui < cutoff && rui > cutoff) || (pui > cutoff && rui < cutoff))
errors_vec[omp_get_thread_num()]++;
}
float eui = pui - rui;
eui = calc_error_f(exp_prediction, eui);
//update global mean bias
globalMean -= gensgd_rate1 * (eui + gensgd_reg0 * globalMean);
//update node biases and vectors
for (int i=0; i < howmany; i++){
double gensgd_rate;
if (i == 0) //user
gensgd_rate = gensgd_rate1;
else if (i == 1) //item
gensgd_rate = gensgd_rate2;
else if (i < (int)(data.size+2)) //rating features
gensgd_rate = gensgd_rate3;
else if (i < (int)(2+data.size+fc.node_features)) //user and item features
gensgd_rate = gensgd_rate4;
else
gensgd_rate = gensgd_rate5; //last item
node_array[i]->bias -= gensgd_rate * (eui + gensgd_regw* node_array[i]->bias);
assert(!std::isnan(node_array[i]->bias));
assert(node_array[i]->bias < 1e3);
fvec grad = sum - node_array[i]->pvec;
node_array[i]->pvec -= gensgd_rate * (eui*grad + gensgd_regv * node_array[i]->pvec);
assert(!std::isnan(node_array[i]->pvec[0]));
assert(node_array[i]->pvec[0] < 1e3);
}
}
}
};
/**
* Called after an iteration has finished.
*/
void after_iteration(int iteration, graphchi_context &gcontext) {
if (iteration == 1 && vertex_with_no_edges > 0)
logstream(LOG_WARNING)<<"There are " << vertex_with_no_edges << " users without ratings" << std::endl;
gensgd_rate1 *= gensgd_mult_dec;
gensgd_rate2 *= gensgd_mult_dec;
gensgd_rate3 *= gensgd_mult_dec;
gensgd_rate4 *= gensgd_mult_dec;
gensgd_rate5 *= gensgd_mult_dec;
training_rmse_N(iteration, gcontext);
validation_rmse_N(&gensgd_predict, gcontext, fc);
};
/**
* Called before an iteration is started.
*/
void before_iteration(int iteration, graphchi_context &gcontext) {
rmse_vec = zeros(number_of_omp_threads());
if (calc_error)
errors_vec = zeros(number_of_omp_threads());
}
};
void output_gensgd_result(std::string filename) {
MMOutputter_mat<vertex_data> mmoutput(filename + "_U.mm", 0, M+N+num_feature_bins(), "This file contains Sparse_Gensgd output matrices. In each row D factors of a single user node, then item nodes, then features", latent_factors_inmem);
MMOutputter_vec<vertex_data> mmoutput_bias(filename + "_U_bias.mm", 0, num_feature_bins(), BIAS_POS,"This file contains Sparse_Gensgd output bias vector. In each row a single user bias.", latent_factors_inmem);
MMOutputter_scalar gmean(filename + "_global_mean.mm", "This file contains Sparse_Gensgd global mean which is required for computing predictions.", globalMean);
logstream(LOG_INFO) << " GENSGD output files (in matrix market format): " << filename << "_U.mm" << ", "<< filename << "_global_mean.mm, " << filename << "_U_bias.mm " <<std::endl;
}
int main(int argc, const char ** argv) {
print_copyright();
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("als-tensor-inmemory-factors");
//specific command line parameters for gensgd
gensgd_rate1 = get_option_float("gensgd_rate1", gensgd_rate1);
gensgd_rate2 = get_option_float("gensgd_rate2", gensgd_rate2);
gensgd_rate3 = get_option_float("gensgd_rate3", gensgd_rate3);
gensgd_rate4 = get_option_float("gensgd_rate4", gensgd_rate4);
gensgd_rate5 = get_option_float("gensgd_rate5", gensgd_rate5);
gensgd_regw = get_option_float("gensgd_regw", gensgd_regw);
gensgd_regv = get_option_float("gensgd_regv", gensgd_regv);
gensgd_reg0 = get_option_float("gensgd_reg0", gensgd_reg0);
gensgd_mult_dec = get_option_float("gensgd_mult_dec", gensgd_mult_dec);
fc.hash_strings = get_option_int("rehash", fc.hash_strings);
user_file = get_option_string("user_file", user_file);
user_links = get_option_string("user_links", user_links);
item_file = get_option_string("item_file", item_file);
D = get_option_int("D", D);
fc.from_pos = get_option_int("from_pos", fc.from_pos);
fc.to_pos = get_option_int("to_pos", fc.to_pos);
fc.val_pos = get_option_int("val_pos", fc.val_pos);
limit_rating = get_option_int("limit_rating", limit_rating);
calc_error = get_option_int("calc_error", calc_error);
calc_roc = get_option_int("calc_roc", calc_roc);
round_float = get_option_int("round_float", round_float);
has_header_titles = get_option_int("has_header_titles", has_header_titles);
fc.rehash_value = get_option_int("rehash_value", fc.rehash_value);
cutoff = get_option_float("cutoff", cutoff);
val_cutoff = get_option_float("val_cutoff", val_cutoff);
binary = get_option_int("binary", binary);
parse_command_line_args();
parse_implicit_command_line();
fc.node_id_maps.resize(2); //initial place for from/to map
//fc.stats_array.resize(fc.total_features);
if (format == "libsvm"){
fc.val_pos = 0;
fc.to_pos = 2;
fc.from_pos = 1;
binary = false;
fc.hash_strings = true;
}
int nshards = convert_matrixmarket_N<edge_data>(training, false, fc, limit_rating);
fc.total_features = fc.index_map.string2nodeid.size();
if (load_factors_from_file){
load_matrix_market_matrix(training + "_U.mm", 0, D);
vec user_bias = load_matrix_market_vector(training +"_U_bias.mm", false, true);
assert(user_bias.size() == num_feature_bins());
for (uint i=0; num_feature_bins(); i++){
latent_factors_inmem[i].bias = user_bias[i];
}
vec gm = load_matrix_market_vector(training + "_global_mean.mm", false, true);
globalMean = gm[0];
}
init_gensgd(load_factors_from_file);
if (has_header_titles && header_titles.size() == 0)
logstream(LOG_FATAL)<<"Please delete temp files (using : \"rm -f " << training << ".*\") and run again" << std::endl;
logstream(LOG_INFO)<<"Target variable " << std::setw(3) << fc.val_pos << " : " << (has_header_titles? header_titles[fc.val_pos] : "") <<std::endl;
logstream(LOG_INFO)<<"From " << std::setw(3) << fc.from_pos<< " : " << (has_header_titles? header_titles[fc.from_pos] : "") <<std::endl;
logstream(LOG_INFO)<<"To " << std::setw(3) << fc.to_pos << " : " << (has_header_titles? header_titles[fc.to_pos] : "") <<std::endl;
/* Run */
Sparse_GensgdVerticesInMemProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m);
set_engine_flags(engine);
pengine = &engine;
engine.run(program, niters);
/* Output test predictions in matrix-market format */
output_gensgd_result(training);
test_predictions_N(&gensgd_predict, fc);
/* Report execution metrics */
metrics_report(m);
return 0;
}
| 09jijiangwen-download | toolkits/collaborative_filtering/sparse_gensgd2.cpp | C++ | asf20 | 34,429 |
/**
* @file
* @author Mark Levy
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* CLiMF Collaborative Less-is-More Filtering, a variant of latent factor CF
* which optimises a lower bound of the smoothed reciprocal rank of "relevant"
* items in ranked recommendation lists. The intention is to promote diversity
* as well as accuracy in the recommendations. The method assumes binary
* relevance data, as for example in friendship or follow relationships.
*
* CLiMF: Learning to Maximize Reciprocal Rank with Collaborative Less-is-More Filtering
* Yue Shi, Martha Larson, Alexandros Karatzoglou, Nuria Oliver, Linas Baltrunas, Alan Hanjalic
* ACM RecSys 2012
*
*/
#include <string>
#include <algorithm>
#include "util.hpp"
#include "eigen_wrapper.hpp"
#include "common.hpp"
#include "climf.hpp"
#include "io.hpp"
#include "rmse.hpp" // just for test_predictions()
#include "mrr_engine.hpp"
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct SGDVerticesInMemProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Called before an iteration is started.
*/
void before_iteration(int iteration, graphchi_context &gcontext)
{
logstream(LOG_DEBUG) << "before_iteration: resetting MRR" << std::endl;
reset_mrr(gcontext.execthreads);
last_training_objective = training_objective;
objective_vec = zeros(gcontext.execthreads);
}
/**
* Called after an iteration has finished.
*/
void after_iteration(int iteration, graphchi_context &gcontext)
{
training_objective = sum(objective_vec);
std::cout<<" Training objective:" << std::setw(10) << training_objective << std::endl;
if (halt_on_mrr_decrease > 0 && halt_on_mrr_decrease < cur_iteration && training_objective < last_training_objective)
{
logstream(LOG_WARNING) << "Stopping engine because of validation objective decrease" << std::endl;
gcontext.set_last_iteration(gcontext.iteration);
}
logstream(LOG_DEBUG) << "after_iteration: running validation engine" << std::endl;
run_validation(pvalidation_engine, gcontext);
sgd_gamma *= sgd_step_dec;
}
/**
* Vertex update function.
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext)
{
double objective = -0.5*sgd_lambda*latent_factors_inmem[vertex.id()].pvec.squaredNorm();
// go over all user nodes
if (vertex.num_outedges() > 1) // can't compute with CLiMF if we have only 1 out edge!
{
vec & U = latent_factors_inmem[vertex.id()].pvec;
int Ni = vertex.num_edges();
// precompute f_{ij} = <U_i,V_j> for j = 1..N_i
std::vector<double> f(Ni);
int num_relevant = 0;
for (int j = 0; j < Ni; ++j)
{
if (is_relevant(vertex.edge(j)))
{
const vec & Vj = latent_factors_inmem[vertex.edge(j)->vertex_id()].pvec;
f[j] = dot(U, Vj);
++num_relevant;
}
}
if (num_relevant < 2)
{
return; // need at least 2 edges to compute updates with CLiMF!
}
// compute gradients
vec dU = -sgd_lambda*U;
for (int j = 0; j < Ni; ++j)
{
if (is_relevant(vertex.edge(j)))
{
vec & Vj = latent_factors_inmem[vertex.edge(j)->vertex_id()].pvec;
vec dVj = g(-f[j])*ones(D) - sgd_lambda*Vj;
for (int k = 0; k < Ni; ++k)
{
if (k != j && is_relevant(vertex.edge(k)))
{
dVj += dg(f[j]-f[k])*(1.0/(1.0-g(f[k]-f[j]))-1.0/(1.0-g(f[j]-f[k])))*U;
}
}
Vj += sgd_gamma*dVj; // not thread-safe
dU += g(-f[j])*Vj;
for (int k = 0; k < Ni; ++k)
{
if (k != j && is_relevant(vertex.edge(k)))
{
const vec & Vk = latent_factors_inmem[vertex.edge(k)->vertex_id()].pvec;
dU += (Vj-Vk)*dg(f[k]-f[j])/(1.0-g(f[k]-f[j]));
}
}
}
}
U += sgd_gamma*dU; // not thread-safe
// compute smoothed MRR
for(int j = 0; j < Ni; j++)
{
if (is_relevant(vertex.edge(j)))
{
objective += std::log(g(f[j]));
for(int k = 0; k < Ni; k++)
{
if (is_relevant(vertex.edge(k)))
{
objective += std::log(1.0-g(f[k]-f[j]));
}
}
}
}
}
assert(objective_vec.size() > omp_get_thread_num());
objective_vec[omp_get_thread_num()] += objective;
}
};
//dump output to file
void output_sgd_result(std::string filename) {
MMOutputter_mat<vertex_data> user_mat(filename + "_U.mm", 0, M, "This file contains SGD output matrix U. In each row D factors of a single user node.", latent_factors_inmem);
MMOutputter_mat<vertex_data> item_mat(filename + "_V.mm", M, M+N, "This file contains SGD output matrix V. In each row D factors of a single item node.", latent_factors_inmem);
logstream(LOG_INFO) << "CLiMF output files (in matrix market format): " << filename << "_U.mm" <<
", " << filename + "_V.mm " << std::endl;
}
// compute test prediction
float climf_predict(const vertex_data& user,
const vertex_data& movie,
const float rating,
double & prediction,
void * extra = NULL)
{
prediction = g(dot(user.pvec,movie.pvec)); // this is actually a predicted reciprocal rank, not a rating
return 0; // as we have to return something
}
int main(int argc, const char ** argv) {
//* GraphChi initialization will read the command line arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("climf-inmemory-factors");
/* Basic arguments for application. NOTE: File will be automatically 'sharded'. */
sgd_lambda = get_option_float("sgd_lambda", 1e-3);
sgd_gamma = get_option_float("sgd_gamma", 1e-4);
sgd_step_dec = get_option_float("sgd_step_dec", 1.0);
binary_relevance_thresh = get_option_float("binary_relevance_thresh", 0);
halt_on_mrr_decrease = get_option_int("halt_on_mrr_decrease", 0);
num_ratings = get_option_int("num_ratings", 10000); //number of top predictions over which we compute actual MRR
parse_command_line_args();
parse_implicit_command_line();
/* Preprocess data if needed, or discover preprocess files */
bool allow_square = false;
int nshards = convert_matrixmarket<EdgeDataType>(training, NULL, 0, 0, 3, TRAINING, allow_square);
init_feature_vectors<std::vector<vertex_data> >(M+N, latent_factors_inmem, !load_factors_from_file, 0.01);
if (validation != ""){
int vshards = convert_matrixmarket<EdgeDataType>(validation, NULL, 0, 0, 3, VALIDATION);
init_mrr_engine<VertexDataType, EdgeDataType>(pvalidation_engine, vshards);
}
if (load_factors_from_file)
{
load_matrix_market_matrix(training + "_U.mm", 0, D);
load_matrix_market_matrix(training + "_V.mm", M, D);
}
print_config();
/* Run */
SGDVerticesInMemProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m);
set_engine_flags(engine);
pengine = &engine;
engine.run(program, niters);
/* Output latent factor matrices in matrix-market format */
output_sgd_result(training);
test_predictions(&climf_predict);
/* Report execution metrics */
if (!quiet)
metrics_report(m);
return 0;
}
| 09jijiangwen-download | toolkits/collaborative_filtering/climf.cpp | C++ | asf20 | 8,279 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Danny Bickson, CMU
* Utility for computing ranking metrics - comparing between recommendations and actual
* ratings in test set.
* */
#include <cstdio>
#include <map>
#include <iostream>
#include <omp.h>
#include <assert.h>
#include "graphchi_basic_includes.hpp"
#include "timer.hpp"
#include "util.hpp"
#include "eigen_wrapper.hpp"
#include "metrics.hpp"
using namespace std;
using namespace graphchi;
timer mytime;
int K = 10;
int max_per_row = 1000;
std::string training, test;
double avg_train_size = 0;
double avg_test_size = 0;
//non word tokens that will be removed in the parsing
//it is possible to add additional special characters or remove ones you want to keep
const char spaces[] = {" \r\n\t;:"};
void get_one_line(FILE * pfile, int & index, vec & values, int & pos){
char * saveptr = NULL, * linebuf = NULL;
size_t linesize = 0;
int rc = getline(&linebuf, &linesize, pfile);
if (rc < 1){
index = -1;
return;
}
pos = 0;
bool first_time = true;
while(true){
//find from
char *pch = strtok_r(first_time ? linebuf : NULL, spaces, &saveptr);
if (!pch){
return;
}
float val = atof(pch);
if (first_time){
index = (int)val;
first_time = false;
}
else {
assert(pos < values.size());
values[pos] = val;
pos++;
}
}
}
void eval_metrics(){
in_file trf(training);
in_file testt(test);
vec train_vec = zeros(max_per_row);
vec test_vec = zeros(max_per_row);
size_t line = 0;
int train_index = 0, test_index = 0;
double ap = 0;
int train_size =0, test_size = 0;
while(true){
get_one_line(trf.outf, train_index, train_vec, train_size);
get_one_line(testt.outf, test_index, test_vec, test_size);
if (train_index == -1 || test_index == -1)
break;
while (test_index < train_index && test_index != -1){
logstream(LOG_WARNING)<<"Skipping over test index: " << test_index << " train: " << train_index << std::endl;
get_one_line(testt.outf, test_index, test_vec, test_size);
}
while (train_index < test_index && train_index != -1){
logstream(LOG_WARNING)<<"Skipping over train. test index: " << test_index << " train: " << train_index << std::endl;
get_one_line(trf.outf, train_index, train_vec, train_size);
}
if (train_index == test_index){
avg_train_size += train_size;
avg_test_size += test_size;
ap+= average_precision_at_k(train_vec, train_size, test_vec, test_size, K);
line++;
}
else {
logstream(LOG_WARNING)<<"Problem parsing file, got to train index: " << train_index << " test_index: " << test_index << std::endl;
break;
}
if (line % 100000 == 0)
logstream(LOG_INFO)<<mytime.current_time() <<" Finished evaluating " << line << " instances. " << std::endl;
}
logstream(LOG_INFO)<<"Computed AP@" << K << " metric: " << ap/(double)line << std::endl;
logstream(LOG_INFO)<<"Total compared: " << line << std::endl;
logstream(LOG_INFO)<<"Avg test length: " << avg_test_size / line << std::endl;
logstream(LOG_INFO)<<"Avg train length: " << avg_train_size / line << std::endl;
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
K = get_option_int("K", K);
if (K < 1)
logstream(LOG_FATAL)<<"Number of top elements (--K=) should be >= 1"<<std::endl;
omp_set_num_threads(get_option_int("ncpus", 1));
mytime.start();
training = get_option_string("training");
test = get_option_string("test");
eval_metrics();
std::cout << "Finished in " << mytime.current_time() << std::endl;
return 0;
}
| 09jijiangwen-download | toolkits/collaborative_filtering/metric_eval.cpp | C++ | asf20 | 4,590 |
#ifndef PRINTOUTS
#define PRINTOUTS
#define MAX_PRINTOUT_LEN 25
bool absolute_value = true;
inline double fabs2(double val){
if (absolute_value)
return fabs(val);
else return val;
}
void print_vec(const char * name, const DistVec & vec, bool high = false){
if (!debug)
return;
int i;
printf("%s[%d]\n", name, vec.offset);
for (i=vec.start; i< std::min(vec.end, MAX_PRINTOUT_LEN); i++){
if (high)
printf("%15.15lg ", fabs2(latent_factors_inmem[i].pvec[vec.offset]));
else
printf("%.5lg ", fabs2(latent_factors_inmem[i].pvec[vec.offset]));
}
printf("\n");
}
void print_vec(const char * name, const vec & pvec, bool high = false){
if (!debug)
return;
printf("%s\n", name);
for (int i= 0; i< std::min((int)pvec.size(), MAX_PRINTOUT_LEN); i++){
if (high)
printf("%15.15lg ", fabs2(pvec[i]));
else
printf("%.5lg ", fabs2(pvec[i]));
}
printf("\n");
}
void print_mat(const char * name, const mat & pmat, bool high = false){
if (!debug)
return;
printf("%s\n", name);
mat pmat2 = transpose((mat&)pmat);
if (pmat2.cols() == 1)
pmat2 = pmat2.transpose();
for (int i= 0; i< std::min((int)pmat2.rows(), MAX_PRINTOUT_LEN); i++){
for (int j=0; j< std::min((int)pmat2.cols(), MAX_PRINTOUT_LEN); j++){
if (high)
printf("%15.15lg ", fabs2(get_val(pmat2, i, j)));
else
printf("%.5lg ", fabs2(get_val(pmat2, i, j)));
}
printf("\n");
}
}
void print_vec_pos(std::string name, vec & v, int i){
if (!debug)
return;
if (i == -1)
printf("%s\n", name.c_str());
else {
printf("%s[%d]: %.5lg\n", name.c_str(), i, fabs(v[i]));
return;
}
for (int j=0; j< std::min((int)v.size(),MAX_PRINTOUT_LEN); j++){
printf("%.5lg", fabs2(v(j)));
if (v.size() > 1)
printf(" ");
}
printf("\n");
}
#define PRINT_VEC(a) print_vec(#a,a,0)
#define PRINT_VEC2(a,b) print_vec(a,b,0)
#define PRINT_VEC3(a,b,c) print_vec_pos(a,b,c)
#define PRINT_VEC2_HIGH(a,i) print_vec(#a,a[i],1)
#define PRINT_INT(a) if (debug) printf("%s: %d\n", #a, a);
#define PRINT_NAMED_INT(a,b) if (debug) printf("%s: %d\n",a, b);
#define PRINT_DBL(a) if (debug) printf("%s: %.5lg\n", #a, a);
#define PRINT_NAMED_DBL(a,b) if (debug) printf("%s: %.5lg\n", a, b);
#define PRINT_MAT(a) print_mat(#a, a, 0);
#define PRINT_MAT2(a,b) print_mat(a,b,0);
#endif
| 09jijiangwen-download | toolkits/collaborative_filtering/printouts.hpp | C++ | asf20 | 2,318 |
/**
* @file
* @author Danny Bickson
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* Matrix factorization with the Koren's SVD++ algorithm.
* Algorithm described in the paper:
*
*/
#include "common.hpp"
#include "eigen_wrapper.hpp"
struct svdpp_params{
float itmBiasStep;
float itmBiasReg;
float usrBiasStep;
float usrBiasReg;
float usrFctrStep;
float usrFctrReg;
float itmFctrStep;
float itmFctrReg; //gamma7
float itmFctr2Step;
float itmFctr2Reg;
float step_dec;
svdpp_params(){
itmBiasStep = 1e-4f;
itmBiasReg = 1e-4f;
usrBiasStep = 1e-4f;
usrBiasReg = 2e-4f;
usrFctrStep = 1e-4f;
usrFctrReg = 2e-4f;
itmFctrStep = 1e-4f;
itmFctrReg = 1e-4f; //gamma7
itmFctr2Step = 1e-4f;
itmFctr2Reg = 1e-4f;
step_dec = 0.9;
}
};
svdpp_params svdpp;
#define BIAS_POS -1
struct vertex_data {
vec pvec;
vec weight;
double bias;
vertex_data() {
pvec = zeros(D);
weight = zeros(D);
bias = 0;
}
void set_val(int index, float val){
if (index == BIAS_POS)
bias = val;
else if (index < D)
pvec[index] = val;
else weight[index-D] = val;
}
float get_val(int index){
if (index== BIAS_POS)
return bias;
else if (index < D)
return pvec[index];
else return weight[index-D];
}
};
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vertex_data VertexDataType;
typedef float EdgeDataType; // Edges store the "rating" of user->movie pair
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
graphchi_engine<VertexDataType, EdgeDataType> * pvalidation_engine = NULL;
std::vector<vertex_data> latent_factors_inmem;
#include "io.hpp"
#include "rmse.hpp"
#include "rmse_engine.hpp"
/** compute a missing value based on SVD++ algorithm */
float svdpp_predict(const vertex_data& user, const vertex_data& movie, const float rating, double & prediction, void * extra = NULL){
//\hat(r_ui) = \mu +
prediction = globalMean;
// + b_u + b_i +
prediction += user.bias + movie.bias;
// + q_i^T *(p_u +sqrt(|N(u)|)\sum y_j)
//prediction += dot_prod(movie.pvec,(user.pvec+user.weight));
for (int j=0; j< D; j++)
prediction += movie.pvec[j] * (user.pvec[j] + user.weight[j]);
prediction = std::min((double)prediction, maxval);
prediction = std::max((double)prediction, minval);
float err = rating - prediction;
if (std::isnan(err))
logstream(LOG_FATAL)<<"Got into numerical errors. Try to decrease step size using the command line: svdpp_user_bias_step, svdpp_item_bias_step, svdpp_user_factor2_step, svdpp_user_factor_step, svdpp_item_step" << std::endl;
return err*err;
}
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct SVDPPVerticesInMemProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Called before an iteration is started.
*/
void before_iteration(int iteration, graphchi_context &gcontext) {
reset_rmse(gcontext.execthreads);
}
/**
* Called after an iteration has finished.
*/
void after_iteration(int iteration, graphchi_context &gcontext) {
svdpp.itmFctrStep *= svdpp.step_dec;
svdpp.itmFctr2Step *= svdpp.step_dec;
svdpp.usrFctrStep *= svdpp.step_dec;
svdpp.itmBiasStep *= svdpp.step_dec;
svdpp.usrBiasStep *= svdpp.step_dec;
training_rmse(iteration, gcontext);
validation_rmse(&svdpp_predict, gcontext);
}
/**
* Vertex update function.
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
if ( vertex.num_outedges() > 0){
vertex_data & user = latent_factors_inmem[vertex.id()];
memset(&user.weight[0], 0, sizeof(double)*D);
for(int e=0; e < vertex.num_outedges(); e++) {
vertex_data & movie = latent_factors_inmem[vertex.edge(e)->vertex_id()];
user.weight += movie.weight;
}
// sqrt(|N(u)|)
float usrNorm = double(1.0/sqrt(vertex.num_outedges()));
//sqrt(|N(u)| * sum_j y_j
user.weight *= usrNorm;
vec step = zeros(D);
// main algorithm, see Koren's paper, just below below equation (16)
for(int e=0; e < vertex.num_outedges(); e++) {
vertex_data & movie = latent_factors_inmem[vertex.edge(e)->vertex_id()];
float observation = vertex.edge(e)->get_data();
double estScore;
rmse_vec[omp_get_thread_num()] += svdpp_predict(user, movie,observation, estScore);
// e_ui = r_ui - \hat{r_ui}
float err = observation - estScore;
assert(!std::isnan(rmse_vec[omp_get_thread_num()]));
vec itmFctr = movie.pvec;
vec usrFctr = user.pvec;
//q_i = q_i + gamma2 *(e_ui*(p_u + sqrt(N(U))\sum_j y_j) - gamma7 *q_i)
for (int j=0; j< D; j++)
movie.pvec[j] += svdpp.itmFctrStep*(err*(usrFctr[j] + user.weight[j]) - svdpp.itmFctrReg*itmFctr[j]);
//p_u = p_u + gamma2 *(e_ui*q_i -gamma7 *p_u)
for (int j=0; j< D; j++)
user.pvec[j] += svdpp.usrFctrStep*(err *itmFctr[j] - svdpp.usrFctrReg*usrFctr[j]);
step += err*itmFctr;
//b_i = b_i + gamma1*(e_ui - gmma6 * b_i)
movie.bias += svdpp.itmBiasStep*(err-svdpp.itmBiasReg* movie.bias);
//b_u = b_u + gamma1*(e_ui - gamma6 * b_u)
user.bias += svdpp.usrBiasStep*(err-svdpp.usrBiasReg* user.bias);
}
step *= float(svdpp.itmFctr2Step*usrNorm);
//gamma7
double mult = svdpp.itmFctr2Step*svdpp.itmFctr2Reg;
for(int e=0; e < vertex.num_edges(); e++) {
vertex_data& movie = latent_factors_inmem[vertex.edge(e)->vertex_id()];
//y_j = y_j + gamma2*sqrt|N(u)| * q_i - gamma7 * y_j
movie.weight += step - mult * movie.weight;
}
}
}
};
void output_svdpp_result(std::string filename) {
MMOutputter_mat<vertex_data> user_output(filename + "_U.mm", 0, M, "This file contains SVD++ output matrix U. In each row D factors of a single user node. Then additional D weight factors.", latent_factors_inmem, 2*D);
MMOutputter_mat<vertex_data> item_output(filename + "_V.mm", M ,M+N, "This file contains SVD++ output matrix V. In each row D factors of a single item node.", latent_factors_inmem);
MMOutputter_vec<vertex_data> bias_user_vec(filename + "_U_bias.mm", 0, M, BIAS_POS, "This file contains SVD++ output bias vector. In each row a single user bias.", latent_factors_inmem);
MMOutputter_vec<vertex_data> bias_mov_vec(filename + "_V_bias.mm", M, M+N, BIAS_POS, "This file contains SVD++ output bias vector. In each row a single item bias.", latent_factors_inmem);
MMOutputter_scalar gmean(filename + "_global_mean.mm", "This file contains SVD++ global mean which is required for computing predictions.", globalMean);
logstream(LOG_INFO) << "SVDPP output files (in matrix market format): " << filename << "_U.mm" <<
", " << filename + "_V.mm, " << filename << "_U_bias.mm, " << filename << "_V_bias.mm, " << filename << "_global_mean.mm" << std::endl;
}
void svdpp_init(){
srand48(time(NULL));
latent_factors_inmem.resize(M+N);
#pragma omp parallel for
for(int i = 0; i < (int)(M+N); ++i){
vertex_data & data = latent_factors_inmem[i];
data.pvec = zeros(D);
if (i < (int)M) //user node
data.weight = zeros(D);
for (int j=0; j<D; j++)
latent_factors_inmem[i].pvec[j] = drand48();
}
logstream(LOG_INFO) << "SVD++ initialization ok" << std::endl;
}
int main(int argc, const char ** argv) {
print_copyright();
//* GraphChi initialization will read the command line arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("svdpp-inmemory-factors");
svdpp.step_dec = get_option_float("svdpp_step_dec", 0.9);
svdpp.itmBiasStep = get_option_float("svdpp_item_bias_step", 1e-3);
svdpp.itmBiasReg = get_option_float("svdpp_item_bias_reg", 1e-3);
svdpp.usrBiasStep = get_option_float("svdpp_user_bias_step", 1e-3);
svdpp.usrBiasReg = get_option_float("svdpp_user_bias_reg", 1e-3);
svdpp.usrFctrStep = get_option_float("svdpp_user_factor_step", 1e-3);
svdpp.usrFctrReg = get_option_float("svdpp_user_factor_reg", 1e-3);
svdpp.itmFctrReg = get_option_float("svdpp_item_factor_reg", 1e-3);
svdpp.itmFctrStep = get_option_float("svdpp_item_factor_step", 1e-3);
svdpp.itmFctr2Reg = get_option_float("svdpp_item_factor2_reg", 1e-3);
svdpp.itmFctr2Step = get_option_float("svdpp_item_factor2_step", 1e-3);
parse_command_line_args();
parse_implicit_command_line();
/* Preprocess data if needed, or discover preprocess files */
int nshards = convert_matrixmarket<EdgeDataType>(training, NULL, 0, 0, 3, TRAINING, false);
if (validation != ""){
int vshards = convert_matrixmarket<EdgeDataType>(validation, NULL, 0, 0, 3, VALIDATION, false);
init_validation_rmse_engine<VertexDataType, EdgeDataType>(pvalidation_engine, vshards, &svdpp_predict);
}
svdpp_init();
if (load_factors_from_file){
load_matrix_market_matrix(training + "_U.mm", 0, 2*D);
load_matrix_market_matrix(training + "_V.mm", M, D);
vec user_bias = load_matrix_market_vector(training +"_U_bias.mm", false, true);
assert(user_bias.size() == M);
vec item_bias = load_matrix_market_vector(training +"_V_bias.mm", false, true);
assert(item_bias.size() == N);
for (uint i=0; i<M+N; i++){
latent_factors_inmem[i].bias = ((i<M)?user_bias[i] : item_bias[i-M]);
}
vec gm = load_matrix_market_vector(training + "_global_mean.mm", false, true);
globalMean = gm[0];
}
/* Run */
SVDPPVerticesInMemProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m);
set_engine_flags(engine);
pengine = &engine;
engine.run(program, niters);
/* Output latent factor matrices in matrix-market format */
output_svdpp_result(training);
test_predictions(&svdpp_predict);
/* Report execution metrics */
if (!quiet)
metrics_report(m);
return 0;
}
| 09jijiangwen-download | toolkits/collaborative_filtering/svdpp.cpp | C++ | asf20 | 11,084 |
/**
* @file
* @author Danny Bickson
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* Implementation of the label propagation algorithm
*/
#include "../collaborative_filtering/common.hpp"
#include "../parsers/common.hpp"
#include "../collaborative_filtering/eigen_wrapper.hpp"
double alpha = 0.15;
#define TEXT_LENGTH 64
std::string contexts_file, nouns_file, pos_seeds, neg_seeds;
double_map nouns;
double_map contexts;
struct vertex_data {
vec pvec;
bool seed;
double normalizer;
int nb_count;
char text[TEXT_LENGTH];
vertex_data() {
pvec = zeros(D);
seed = false;
normalizer = 0;
nb_count = 0;
}
//this function is only called for seed nodes
void set_val(int index, float val){
pvec[index] = val;
seed = true;
}
float get_val(int index){
return pvec[index];
}
};
struct edge_data{
int cooccurence_count;
edge_data(double val, double nothing){
cooccurence_count = (int)val;
}
edge_data(double val){
cooccurence_count = (int)val;
}
edge_data() : cooccurence_count(0) { }
};
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vertex_data VertexDataType;
typedef edge_data EdgeDataType; // Edges store the "rating" of user->movie pair
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
std::vector<vertex_data> latent_factors_inmem;
#include "../collaborative_filtering/io.hpp"
// tfidc is a modified weight formula for Co-EM (see Justin
// Betteridge's "CoEM results" page)
#define TFIDF(coocc, num_neighbors, vtype_total) (log(1+coocc)*log(vtype_total*1.0/num_neighbors))
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct COEMVerticesInMemProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Vertex update function - computes the least square step
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
vertex_data & vdata = latent_factors_inmem[vertex.id()];
if (vertex.num_edges() == 0 || vdata.seed) //no edges, nothing to do here
return;
vec ret = zeros(D);
double normalization = 0;
for(int e=0; e < vertex.num_edges(); e++) {
edge_data edge = vertex.edge(e)->get_data();
vertex_data & nbr_latent = latent_factors_inmem[vertex.edge(e)->vertex_id()];
ret += edge.cooccurence_count * nbr_latent.pvec;
normalization += edge.cooccurence_count;
}
ret /= normalization;
vdata.pvec = alpha * vdata.pvec + (1-alpha)*ret;
}
};
void load_seeds_from_txt_file(std::map<std::string,uint> & map, const std::string filename, bool negative){
logstream(LOG_INFO)<<"loading " << (negative ? "negative" : "positive" ) << " seeds from txt file: " << filename << std::endl;
FILE * f = fopen(filename.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file: " << filename << std::endl;
char * linebuf = NULL;
size_t linesize;
int line = 0;
while (true){
int rc = getline(&linebuf, &linesize, f);
char * to_free = linebuf;
if (rc == -1)
break;
char *pch = strtok(linebuf,"\r\n\t_^$");
if (!pch){
logstream(LOG_FATAL) << "Error when parsing file: " << filename << ":" << line <<std::endl;
}
uint pos = map[pch];
if (pos <= 0)
logstream(LOG_FATAL)<<"Failed to find " << pch << " in map. Aborting" << std::endl;
assert(pos <= M);
latent_factors_inmem[pos-1].seed = true;
latent_factors_inmem[pos-1].pvec[0] = negative ? 0 : 1;
line++;
//free(to_free);
}
logstream(LOG_INFO)<<"Seed list size is: " << line << std::endl;
fclose(f);
}
void output_coem_result(std::string filename) {
MMOutputter_mat<vertex_data> user_mat(filename + "_U.mm", 0, M , "This file contains COEM output matrix U. In each row D probabilities for the Y labels", latent_factors_inmem);
logstream(LOG_INFO) << "COEM output files (in matrix market format): " << filename << "_U.mm" << std::endl;
}
int main(int argc, const char ** argv) {
print_copyright();
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("label_propagation");
contexts_file = get_option_string("contexts");
nouns_file = get_option_string("nouns");
pos_seeds = get_option_string("pos_seeds");
neg_seeds = get_option_string("neg_seeds");
parse_command_line_args();
load_map_from_txt_file(contexts.string2nodeid, contexts_file, 1);
load_map_from_txt_file(nouns.string2nodeid, nouns_file, 1);
//load graph (adj matrix) from file
int nshards = convert_matrixmarket<EdgeDataType>(training, NULL, 0, 0, 3, TRAINING, true);
init_feature_vectors<std::vector<vertex_data> >(M+N, latent_factors_inmem);
load_seeds_from_txt_file(nouns.string2nodeid, pos_seeds, false);
load_seeds_from_txt_file(nouns.string2nodeid, neg_seeds, true);
#pragma omp parallel for
for (int i=0; i< (int)M; i++){
//normalize seed probabilities to sum up to one
if (latent_factors_inmem[i].seed){
if (sum(latent_factors_inmem[i].pvec) != 0)
latent_factors_inmem[i].pvec /= sum(latent_factors_inmem[i].pvec);
continue;
}
//other nodes get random label probabilities
for (int j=0; j< D; j++)
latent_factors_inmem[i].pvec[j] = drand48();
}
/* load initial state from disk (optional) */
if (load_factors_from_file){
load_matrix_market_matrix(training + "_U.mm", 0, D);
}
/* Run */
COEMVerticesInMemProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m);
set_engine_flags(engine);
pengine = &engine;
engine.run(program, niters);
/* Output latent factor matrices in matrix-market format */
output_coem_result(training);
/* Report execution metrics */
if (!quiet)
metrics_report(m);
return 0;
}
| 09jijiangwen-download | toolkits/text_analysis/coem.cpp | C++ | asf20 | 6,750 |
#**
# * @file
# * @author Danny Bickson
# * @version 1.0
# *
# * @section LICENSE
# *
# * Copyright [2012] [Carngie Mellon University]
# *
# * Licensed under the Apache License, Version 2.0 (the "License");
# * you may not use this file except in compliance with the License.
# * You may obtain a copy of the License at
# *
# * http://www.apache.org/licenses/LICENSE-2.0
# *
# * Unless required by applicable law or agreed to in writing, software
# * distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
# Makefile for compiling graphchi collaborative filtering library
# Written by Danny Bickson
# Thanks to Yucheng Low for fixing the Makefile
INCFLAGS = -I/usr/local/include/ -I../../src/ -I.
CPPFLAGS = -O3 $(INCFLAGS) -DEIGEN_NDEBUG -fopenmp -Wall -Wno-strict-aliasing
LINKFLAGS = -lz
# Note : on Ubuntu on some compilers -lz is not detected properly so it is
# deliberatively set to be the last flag.
CPP = g++
CXX = g++
headers=$(wildcard *.h**)
all: $(patsubst %.cpp, %, $(wildcard *.cpp))
%: %.cpp $(headers)
$(CPP) $(CPPFLAGS) $< -o $@ $(LINKFLAGS)
clean:
rm -f $(patsubst %.cpp, %, $(wildcard *.cpp))
| 09jijiangwen-download | toolkits/text_analysis/Makefile | Makefile | asf20 | 1,323 |
body {
background-color: #F0F0F0;
font-family: 'Open Sans', sans-serif;
margin: 0;
color: #333;
}
#wrapper {
margin: auto;
width: 1000px;
padding: 15px 15px;
min-height: 600px;
background-color: #F4F4F4;
}
#left {
width: 400px;
float: left;
}
#right {
margin-left: 15px;
width: 585px;
float: left;
}
#graph {
height: 435
}
table {
margin: auto;
}
td {
background: #F0F0F0;
padding: 4px;
font-size: 14px;
width: 160px;
}
.container {
padding: 8px;
border-radius: 4px;
margin-bottom: 15px;
background-color: #F9F9F9;
-moz-box-shadow: 0 2px 3px rgba(50,50,50,0.05);
-webkit-box-shadow: 0 2px 3px rgba(50,50,50,0.05);
box-shadow: 0 2px 4px rgba(50,50,50,0.05);
}
h2 {
margin: 6px;
padding: 0px 4px;
padding-bottom: 2px;
border-bottom: solid 1px #CCC;
font-size: 20px;
}
p {
margin: 10px 10px;
font-size: 14px;
}
#logo {
margin-left: -3px;
padding-bottom: 8px;
}
.no-padding {
padding: 0;
}
.color-div {
display: inline-block;
height: 20px;
width: 20px;
background-color: blue;
}
.clear-both {
clear: both;
}
| 09jijiangwen-download | toolkits/visual/style.css | CSS | asf20 | 1,061 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta charset="utf-8">
<link rel='stylesheet' type='text/css' href='style.css'>
<link rel='stylesheet' type="text/css" href="d3.css">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://d3js.org/d3.v2.js"></script>
<!--<script src="graphit.js" type='text/javascript'></script>-->
<script src="graphM2M.js" type='text/javascript'></script>
<script type='text/javascript' src='d3_chart_2.js'></script>
<title>GraphChi Visualization Toolkit</title>
</head>
<body>
<!--<div id='wrapper' width="1024">-->
<p align="left">
<table border="0" width="1000">
<tr>
<td>
<!--div id='right'>-->
<table border="0" width="500">
<tr>
<td>
<div class='container no-padding'>
<img id='logo' src='logo.gif' alt='GraphLab' />
<center>
<h1> GraphChi Visualization Toolkit</h1>
<h2>Written By Danny Bickson, CMU</h2>
<h2>Send any bug reports to danny.bickson@gmail.com</h2>
</center>
</div>
</td>
</tr>
<tr>
<td>
<div class='container no-padding' align="left">
<h2>Graph</h2>
Graph file: <select id="order"></select>
<table id='graph_table' width="500" border="0"></table>
<!--</div>-->
</td>
</tr>
<tr>
<td>
<div class='container no-padding' align="left">
<h2>Settings</h2>
<p>
<table id='settings_table' width="500" border="0"> </table>
</p>
</div>
</td>
</tr>
</table>
</td>
<td>
<div id='large_graph'></div>
</td>
</tr>
</table>
<!--</div>-->
</p>
<script type='text/javascript'>
check_iterations();
function check_iterations() {
$.get('settingA', function(response){
var settings = parse_settings(response);
$('#settings_table').empty();
$('#data_properties_table').empty();
for (var ind=0; ind < settings.length-1; ind = ind+2) {
if (ind < 17) {
$("#settings_table").append("<tr><td>" + settings[ind] + "</td><td>" + settings[ind+1] + "</td></tr>");
} else {
$("#data_properties_table").append("<tr><td>" + settings[ind] + "</td><td>" + settings[ind+1] + "</td></tr>");
}
}
});
//setTimeout("check_iterations()", 500);
}
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;
}
</script>
</body>
</html>
| 09jijiangwen-download | toolkits/visual/index.html | HTML | asf20 | 2,683 |
#!/bin/bash
# script for visualizing a subgraph
# Written by Danny Bickson, CMU
cd ../../
GRAPHCHI_ROOT=`pwd`
cd -
CURPATH=`pwd`
NUM_EDGES=0
FILENAME=""
SEEDS=""
HOPS=2
NODES=0;
EDGES=0;
PROGRAM_OPTIONS="f:h:n:o:r:s:"
HELP_STRING="-f Graph_file [-h hops] [-n edge_num] [-o nodes] [-s seeds] [-r multiple files regexp]\n For example: `basename $0` -f GRAPH_0.TSV -n 1000 -s 12,36,112";
if ( ! getopts $PROGRAM_OPTIONS opt); then
echo "Usage: `basename $0` options $HELP_STRING"
exit $E_OPTERROR;
fi
while getopts $PROGRAM_OPTIONS opt;
do
case $opt in
f) FILENAME=$OPTARG;;
n) NUM_EDGES=$OPTARG;;
s) SEEDS=$OPTARG;;
h) HOPS=$OPTARG;;
o) NODES=$OPTARG;;
r) FILENAMES="$OPTARG";;
\?) echo "Usage: `basename $0` options $HELP_STRING";;
esac
done
if [ $NUM_EDGES -gt 2000 ]; then
echo "You should specify number of edges using -n XX, where XX is the number of edges to be subtructed (default 1000, max 2000)"
exit
fi
if [ ! -z "$FILENAMES" ]; then
if [ ! -z $FILENAME ]; then
echo "When using -r command to specify multiple files, you are not allowed to use the -f command"
exit
fi
DIRNAME=`dirname "$FILENAMES"`
WILDCARD=`basename "$FILENAMES"`
FINDSTR="find \"$DIRNAME\" -name \"$WILDCARD\" | sort > input.files"
FILENAMES=`eval $FINDSTR`
else
FILENAMES=`basename $FILENAME`
echo $FILENAMES > input.files
DIRNAME=`dirname $FILENAME`
fi
OPIOTNAL_ARG=""
rm -fR file.txt
touch file.txt
file_num=0;
while read FILENAME
do
(( file_num++ ))
echo "Going over file: $FILENAME file number: $file_num"
#check that input file exists
if [ ! -f $FILENAME ]; then
echo "Failed to open file: $FILENAME. Specify filename using -f XXXX command."
exit
elif [ ! -z $SEEDS ]; then # check that the input file has the right format for cutting a subgraph from
head -n 1 $FILENAME | grep -q "^%%MatrixMarket";
if [ $? -eq 1 ]; then #matrix market header was not found
if [ $NODES -eq 0 ]; then
echo "For graph input file which is not in matrix market sparse format, you need to use the -o command to specify an upper limit on the number of nod ids"
exit
else
EDGES=`wc -l $FILENAME`;
if [ -z `head -n 1 $FILENAME | cut -f 3` ]; then
OPIOTNAL_ARG="--tokens_per_row=2"
fi
fi
fi
fi
#grab edges starting from a set of seeds
if [ ! -z $SEEDS ]; then
cd $GRAPHCHI_ROOT
./toolkits/graph_analytics/subgraph --training=$FILENAME --seeds=$SEEDS --hops=$HOPS --edges=$NUM_EDGES --nodes=$NODES --orig_edges=$EDGES --quiet=1 $OPIOTNAL_ARG
mv $FILENAME.out $FILENAME.$NUM_EDGES
else # else grab edges from the head of the file
head -n $NUM_EDGES $FILENAME > $FILENAME.$NUM_EDGES
fi
#translate the node ids to consecutive id 1..n
echo "$DIRNAME/$FILENAME.$NUM_EDGES" > $GRAPHCHI_ROOT/a
cd $GRAPHCHI_ROOT
./toolkits/parsers/consecutive_matrix_market --file_list=a --binary=1 --single_domain=1
rm -f ./toolkits/visual/auser.map.text
mv auser.map.text ./toolkits/visual/
cd $CURPATH
if [ ! -f auser.map.text ]; then
echo "Bug - missing file auser.map.text"
exit 1
fi
echo "Going to go over `wc -l auser.map.text | awk '{print $1}'` lines of map file"
nodes_num=0;
declare -A names;
while read i
do
names[`echo $i|awk '{print $2}'`]=`echo $i|awk '{print $1}'`;
(( nodes_num++ ))
done < auser.map.text
#echo "${!names[*]}"
if [ ! -f $FILENAME.$NUM_EDGES.out ]; then
echo "Bug: failed to find $FILENAME.$NUM_EDGES.out"
exit 1
fi
echo "source,target" > graph${NUM_EDGES}.csv
edges_num=0;
while read i
do
echo "${names[`echo $i|awk '{print $1}'`]},${names[`echo $i|awk '{print $2}'`]}">> graph${NUM_EDGES}.csv
(( edges_num++ ))
done < $FILENAME.$NUM_EDGES.out
#remove intermediate files
rm -f $GRAPHCHI_ROOT/$FILENAME.$NUM_EDGES
mv graph${NUM_EDGES}.csv graph${NUM_EDGES}.$file_num.csv
echo "graph${NUM_EDGES}.$file_num.csv" >> file.txt
echo "[filename][$FILENAME]" > graph${NUM_EDGES}.$file_num.csv.txt
echo "[nodes][$nodes_num]" >> graph${NUM_EDGES}.$file_num.csv.txt
echo "[edges][$edges_num]" >>graph${NUM_EDGES}.$file_num.csv.txt
done < input.files # for FILENAMES
#write statistics to file
echo "[directory][$DIRNAME]" > settingA
#echo "[nodes][$nodes_num]" >> settingA
#echo "[edges][$edges_num]" >> settingA
echo "[hops][$HOPS]" >> settingA
echo "[seeds][$SEEDS]" >> settingA
echo "[creation][`date`]" >> settingA
echo "[user][$USER]" >> settingA
echo "scp bickson@thrust.ml.cmu.edu:~/tmp/graph${NUM_EDGES}.csv bickson@thrust.ml.cmu.edu:~/tmp/settingA ~/Downloads/visualization_demo/gv_demo/"
| 09jijiangwen-download | toolkits/visual/make_data.csv.sh | Shell | asf20 | 4,653 |
// 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');
});
};
| 09jijiangwen-download | toolkits/visual/graphM2M.js | JavaScript | asf20 | 4,631 |
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
path.link {
fill: black;
stroke: #666;
stroke-width: 1.5px;
}
marker#licensing {
fill: green;
}
path.link.licensing {
stroke: green;
}
path.link.resolved {
stroke-dasharray: 0,2 1;
}
circle {
fill: #ccc;
stroke: #333;
stroke-width: 1.5px;
}
text {
font: 10px sans-serif;
pointer-events: none;
}
text.shadow {
stroke: #fff;
stroke-width: 3px;
stroke-opacity: .8;
}
| 09jijiangwen-download | toolkits/visual/d3.css | CSS | asf20 | 592 |
#!/bin/sh
#change the website path to point to your website dir, and then run "sh refresh_website.sh" when you
#want to view your graph
cp index.html *.css *.js graph*.csv logo.gif settingA file.txt *csv.txt /afs/cs.cmu.edu/user/bickson/www/graphchi/
| 09jijiangwen-download | toolkits/visual/refresh_website.sh | Shell | asf20 | 253 |
/**
* @file
* @author Aapo Kyrola <akyrola@cs.cmu.edu>
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* Application for computing the connected components of a graph.
* The algorithm is simple: on first iteration each vertex sends its
* id to neighboring vertices. On subsequent iterations, each vertex chooses
* the smallest id of its neighbors and broadcasts its (new) label to
* its neighbors. The algorithm terminates when no vertex changes label.
*
* @section REMARKS
*
* Version of connected components that keeps the vertex values
* in memory.
* @author Aapo Kyrola
*
* Danny B: added output of each vertex label
*/
#define GRAPHCHI_DISABLE_COMPRESSION
#include <cmath>
#include <string>
#include <map>
#include "graphchi_basic_includes.hpp"
#include "label_analysis.hpp"
#include "../collaborative_filtering/eigen_wrapper.hpp"
#include "../collaborative_filtering/timer.hpp"
using namespace graphchi;
bool edge_count = false;
std::map<uint,uint> state;
mutex mymutex;
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vid_t VertexDataType; // vid_t is the vertex id type
typedef vid_t EdgeDataType;
VertexDataType * vertex_values;
size_t changes = 0;
timer mytimer;
int actual_vertices = 0;
bool * active_nodes;
int iter = 0;
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct ConnectedComponentsProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Called after an iteration has finished.
*/
void after_iteration(int iteration, graphchi_context &ginfo) {
logstream(LOG_DEBUG)<<mytimer.current_time() << "iteration: " << iteration << " changes: " << changes << std::endl;
if (changes == 0)
ginfo.set_last_iteration(iteration);
changes = 0;
iter++;
}
vid_t neighbor_value(graphchi_edge<EdgeDataType> * edge) {
return vertex_values[edge->vertex_id()];
}
void set_data(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, vid_t value) {
vertex_values[vertex.id()] = value;
}
/**
* Vertex update function.
* On first iteration ,each vertex chooses a label = the vertex id.
* On subsequent iterations, each vertex chooses the minimum of the neighbor's
* label (and itself).
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
/* On subsequent iterations, find the minimum label of my neighbors */
if (!edge_count){
vid_t curmin = vertex_values[vertex.id()];
//first time, count the number of nodes which actually have edges
if (gcontext.iteration == 0 && vertex.num_edges() > 0){
mymutex.lock(); actual_vertices++; mymutex.unlock();
}
for(int i=0; i < vertex.num_edges(); i++) {
vid_t nblabel = neighbor_value(vertex.edge(i));
curmin = std::min(nblabel, curmin);
}
//in case of a new min reschedule neighbors
if (vertex_values[vertex.id()] > curmin) {
changes++;
set_data(vertex, curmin);
for (int i=0; i< vertex.num_edges(); i++){
active_nodes[vertex.edge(i)->vertex_id()] = true;
}
}
else active_nodes[vertex.id()] = false;
}
else {
vid_t curmin = vertex_values[vertex.id()];
for(int i=0; i < vertex.num_edges(); i++) {
vid_t nblabel = neighbor_value(vertex.edge(i));
curmin = std::min(nblabel, curmin);
if (vertex.edge(i)->vertex_id() > vertex.id()){
mymutex.lock();
state[curmin]++;
mymutex.unlock();
}
}
}
}
/**
* Called before an iteration starts.
*/
void before_iteration(int iteration, graphchi_context &ctx) {
changes = 0;
if (iteration == 0 && !edge_count) {
/* initialize each vertex with its own lable */
vertex_values = new VertexDataType[ctx.nvertices];
for(int i=0; i < (int)ctx.nvertices; i++) {
vertex_values[i] = i;
}
}
ctx.scheduler->remove_tasks(0, (int) ctx.nvertices - 1);
for (int i=0; i< ctx.nvertices; i++)
if (active_nodes[i])
ctx.scheduler->add_task(i);
}
};
int main(int argc, const char ** argv) {
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("connected-components-inmem");
/* Basic arguments for application */
std::string filename = get_option_string("file"); // Base filename
int niters = get_option_int("niters", 100); // Number of iterations (max)
int output_labels = get_option_int("output_labels", 0); //output node labels to file?
bool scheduler = true; // Always run with scheduler
/* Process input file - if not already preprocessed */
float p = get_option_float("p", -1);
int n = get_option_int("n", -1);
int quiet = get_option_int("quiet", 0);
if (quiet)
global_logger().set_log_level(LOG_ERROR);
int nshards = (int) convert_if_notexists<EdgeDataType>(filename, get_option_string("nshards", "auto"));
mytimer.start();
/* Run */
ConnectedComponentsProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(filename, nshards, scheduler, m);
engine.set_disable_vertexdata_storage();
engine.set_enable_deterministic_parallelism(false);
engine.set_modifies_inedges(false);
engine.set_modifies_outedges(false);
engine.set_preload_commit(false);
engine.set_maxwindow(engine.num_vertices());
mytimer.start();
active_nodes = new bool[engine.num_vertices()];
for (int i=0; i< engine.num_vertices(); i++)
active_nodes[i] = true;
engine.run(program, niters);
/* Run analysis of the connected components (output is written to a file) */
if (output_labels){
FILE * pfile = fopen((filename + "-components").c_str(), "w");
if (!pfile)
logstream(LOG_FATAL)<<"Failed to open file: " << filename << std::endl;
fprintf(pfile, "%%%%MatrixMarket matrix array real general\n");
fprintf(pfile, "%lu %u\n", engine.num_vertices()-1, 1);
for (uint i=1; i< engine.num_vertices(); i++){
fprintf(pfile, "%u\n", vertex_values[i]);
assert(vertex_values[i] >= 0 && vertex_values[i] < engine.num_vertices());
}
fclose(pfile);
logstream(LOG_INFO)<<"Saved succesfully to out file: " << filename << "-components" << " time for saving: " << mytimer.current_time() << std::endl;
}
std::cout<<"Total runtime: " << mytimer.current_time() << std::endl;
if (p > 0)
std::cout << "site fraction p= " << p << std::endl;
if (n > 0){
std::cout << "n=" << n*p << std::endl;
std::cout << "isolated sites: " << p*(double)n-actual_vertices << std::endl;
}
std::cout << "Number of sites: " << actual_vertices << std::endl;
std::cout << "Number of bonds: " << engine.num_edges() << std::endl;
if (n){
std::cout << "Percentage of sites: " << (double)actual_vertices / (double)n << std::endl;
std::cout << "Percentage of bonds: " << (double)engine.num_edges() / (2.0*n) << std::endl;
}
std::cout << "Number of iterations: " << iter << std::endl;
std::cout << "SITES RESULT:\nsize\tcount\n";
std::map<uint,uint> final_countsv;
std::map<uint,uint> final_countse;
std::map<uint,uint> statv;
for (int i=0; i< engine.num_vertices(); i++)
statv[vertex_values[i]]++;
uint total_sites = 0;
for (std::map<uint, uint>::const_iterator iter = statv.begin();
iter != statv.end(); iter++) {
//std::cout << iter->first << "\t" << iter->second << "\n";
final_countsv[iter->second] += 1;
total_sites += iter->second;
}
for (std::map<uint, uint>::const_iterator iter = final_countsv.begin();
iter != final_countsv.end(); iter++) {
std::cout << iter->first << "\t" << iter->second << "\n";
}
edge_count = 1;
engine.run(program, 1);
std::cout << "BONDS RESULT:\nsize\tcount\n";
uint total_bonds = 0;
for (std::map<uint, uint>::const_iterator iter = state.begin();
iter != state.end(); iter++) {
//std::cout << iter->first << "\t" << iter->second << "\n";
final_countse[iter->second] += 1;
total_bonds += iter->second;
}
for (std::map<uint, uint>::const_iterator iter = final_countse.begin();
iter != final_countse.end(); iter++) {
std::cout << iter->first << "\t" << iter->second << "\n";
}
assert(total_sites == graph.num_vertices());
assert(total_bonds == graph.num_edges());
return 0;
}
| 09jijiangwen-download | toolkits/graph_analytics/bond_percolation.cpp | C++ | asf20 | 9,337 |
#**
# * @file
# * @author Danny Bickson
# * @version 1.0
# *
# * @section LICENSE
# *
# * Copyright [2012] [Carngie Mellon University]
# *
# * Licensed under the Apache License, Version 2.0 (the "License");
# * you may not use this file except in compliance with the License.
# * You may obtain a copy of the License at
# *
# * http://www.apache.org/licenses/LICENSE-2.0
# *
# * Unless required by applicable law or agreed to in writing, software
# * distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
# Makefile for compiling graphchi collaborative filtering library
# Written by Danny Bickson
# Thanks to Yucheng Low for fixing the Makefile
INCFLAGS = -I/usr/local/include/ -I../../src/ -I.
CPPFLAGS = -O3 $(INCFLAGS) -DEIGEN_NDEBUG -fopenmp -Wall -Wno-strict-aliasing
LINKFLAGS = -lz
# Note : on Ubuntu on some compilers -lz is not detected properly so it is
# deliberatively set to be the last flag.
CPP = g++
CXX = g++
headers=$(wildcard *.h**)
all: $(patsubst %.cpp, %, $(wildcard *.cpp))
%: %.cpp $(headers)
$(CPP) $(CPPFLAGS) $< -o $@ $(LINKFLAGS)
clean:
rm -f $(patsubst %.cpp, %, $(wildcard *.cpp))
| 09jijiangwen-download | toolkits/graph_analytics/Makefile | Makefile | asf20 | 1,323 |
/**
* * @file
* * @author Aapo Kyrola <akyrola@cs.cmu.edu>
* * @version 1.0
* *
* * @section LICENSE
* *
* * Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University]
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
* *
* * @section DESCRIPTION
* *
* * Analyses output of label propagation algorithms such as connected components
* * and community detection. Memory efficient implementation.
* *
* * @author Aapo Kyrola
* */
#include <vector>
#include <algorithm>
#include <errno.h>
#include <assert.h>
#include "io/stripedio.hpp"
#include "logger/logger.hpp"
#include "util/merge.hpp"
#include "util/ioutil.hpp"
#include "util/qsort.hpp"
#include "api/chifilenames.hpp"
#ifndef DEF_GRAPHCHI_LABELANALYSIS
#define DEF_GRAPHCHI_LABELANALYSIS
using namespace graphchi;
template <typename LabelType>
struct labelcount_tt {
LabelType label;
unsigned int count; // Count excludes the vertex which has its own id as the label. (Important optimization)
labelcount_tt(LabelType l, int c) : label(l), count(c) {}
labelcount_tt() {}
};
template <typename LabelType>
bool label_count_greater(const labelcount_tt<LabelType> &a, const labelcount_tt<LabelType> &b) {
return a.count > b.count;
}
template <typename LabelType>
void analyze_labels2(std::string base_filename, FILE * pfile, int printtop = 20) {
typedef labelcount_tt<LabelType> labelcount_t;
/**
* * NOTE: this implementation is quite a mouthful. Cleaner implementation
* * could be done by using a map implementation. But STL map takes too much
* * memory, and I want to avoid Boost dependency - which would have boost::unordered_map.
* */
std::string filename = filename_vertex_data<LabelType>(base_filename);
metrics m("labelanalysis");
stripedio * iomgr = new stripedio(m);
int f = iomgr->open_session(filename, true);
size_t sz = get_filesize(filename);
/* Setup buffer sizes */
size_t bufsize = 1024 * 1024; // Read one megabyte a time
int nbuf = (int) (bufsize / sizeof(LabelType));
std::vector<labelcount_t> curlabels;
size_t nread = 0;
bool first = true;
vid_t curvid = 0;
LabelType * buffer = (LabelType*) calloc(nbuf, sizeof(LabelType));
while (nread < sz) {
size_t len = std::min(sz - nread, bufsize);
iomgr->preada_now(f, buffer, len, nread);
nread += len;
int nt = (int) (len / sizeof(LabelType));
/* Mark vertices with its own label with 0xffffffff so they will be ignored */
for(int i=0; i < nt; i++) {
LabelType l = buffer[i];
if (curvid > 0)
fprintf(pfile, "%d 1 %d\n", curvid, l);
if (l == curvid) buffer[i] = 0xffffffff;
curvid++;
}
/* First sort the buffer */
quickSort(buffer, nt, std::less<LabelType>());
/* Then collect */
std::vector<labelcount_t> newlabels;
newlabels.reserve(nt);
vid_t lastlabel = 0xffffffff;
for(int i=0; i < nt; i++) {
if (buffer[i] != 0xffffffff) {
if (buffer[i] != lastlabel) {
newlabels.push_back(labelcount_t(buffer[i], 1));
} else {
newlabels[newlabels.size() - 1].count ++;
}
lastlabel = buffer[i];
}
}
if (first) {
for(int i=0; i < (int)newlabels.size(); i++) {
curlabels.push_back(newlabels[i]);
}
} else {
/* Merge current and new label counts */
int cl = 0;
int nl = 0;
std::vector< labelcount_t > merged;
merged.reserve(curlabels.size() + newlabels.size());
while(cl < (int)curlabels.size() && nl < (int)newlabels.size()) {
if (newlabels[nl].label == curlabels[cl].label) {
merged.push_back(labelcount_t(newlabels[nl].label, newlabels[nl].count + curlabels[cl].count));
nl++; cl++;
} else {
if (newlabels[nl].label < curlabels[cl].label) {
merged.push_back(newlabels[nl]);
nl++;
} else {
merged.push_back(curlabels[cl]);
cl++;
}
}
}
while(cl < (int)curlabels.size()) merged.push_back(curlabels[cl++]);
while(nl < (int)newlabels.size()) merged.push_back(newlabels[nl++]);
curlabels = merged;
}
first = false;
}
/* Sort */
std::sort(curlabels.begin(), curlabels.end(), label_count_greater<LabelType>);
/* Write output file */
std::string outname = base_filename + "_components.txt";
FILE * resf = fopen(outname.c_str(), "w");
if (resf == NULL) {
logstream(LOG_ERROR) << "Could not write label outputfile : " << outname << std::endl;
return;
}
for(int i=0; i < (int) curlabels.size(); i++) {
fprintf(resf, "%u,%u\n", curlabels[i].label, curlabels[i].count + 1);
}
fclose(resf);
std::cout << "Total number of different labels (components/communities): " << curlabels.size() << std::endl;
std::cout << "List of labels was written to file: " << outname << std::endl;
for(int i=0; i < (int)std::min((size_t)printtop, curlabels.size()); i++) {
std::cout << (i+1) << ". label: " << curlabels[i].label << ", size: " << curlabels[i].count << std::endl;
}
iomgr->close_session(f);
delete iomgr;
}
#endif
| 09jijiangwen-download | toolkits/graph_analytics/label_analysis.hpp | C++ | asf20 | 6,197 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
#include <cmath>
#include <cstdio>
#include <limits>
#include <iostream>
#include "graphchi_basic_includes.hpp"
#include "api/chifilenames.hpp"
#include "api/vertex_aggregator.hpp"
#include "preprocessing/sharder.hpp"
#include "../collaborative_filtering/eigen_wrapper.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/common.hpp"
using namespace graphchi;
int square = 0;
int tokens_per_row = 3;
bool debug = false;
int max_iter = 50;
ivec active_nodes_num;
ivec active_links_num;
int iiter = 0; //current iteration
uint nodes = 0;
uint orig_edges = 0;
uint num_active = 0;
uint links = 0;
mutex mymutex;
timer mytimer;
struct vertex_data {
bool active;
int kcore, degree;
vec pvec; //to remove
vertex_data() : active(true), kcore(-1), degree(0) {}
void set_val(int index, double val){}
float get_val(int index){ return 0;}
}; // end of vertex_data
//edges in kcore algorithm are binary
struct edge_data {
edge_data() { }
//compatible with parser which have edge value (we don't need it)
edge_data(double val) { }
edge_data(double val, double time) { }
};
typedef vertex_data VertexDataType;
typedef edge_data EdgeDataType; // Edges store the "rating" of user->movie pair
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
std::vector<vertex_data> latent_factors_inmem;
#include "../collaborative_filtering/io.hpp"
struct KcoresProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Vertex update function.
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
vertex_data & vdata = latent_factors_inmem[vertex.id()];
if (debug && iiter > 99 && vertex.id() % 1000 == 0)
std::cout<<"Entering node: " << vertex.id() << std::endl;
if (!vdata.active)
return;
int cur_iter = iiter;
int cur_links = 0;
int increasing_links = 0;
for(int e=0; e < vertex.num_edges(); e++) {
const vertex_data & other = latent_factors_inmem[vertex.edge(e)->vertex_id()];
if (other.active){
if (debug && iiter > 99)
std::cout<<"neighbor: "<<vertex.edge(e)->vertex_id()<<" active"<<std::endl;
cur_links++;
if (vertex.edge(e)->vertex_id() > vertex.id())
increasing_links++;
}
}
if (cur_links <= cur_iter){
vdata.active = false;
vdata.kcore = cur_iter;
}
else {
if (debug && iiter > 99)
std::cout<<vertex.id()<<": cur links: " << cur_links << std::endl;
mymutex.lock();
links += increasing_links;
mymutex.unlock();
}
if (vdata.active){
mymutex.lock();
num_active++;
mymutex.unlock();
}
}
void after_iteration(int iteration, graphchi_context &gcontext) {
active_nodes_num[iiter] = num_active;
if (num_active == 0)
links = 0;
printf("Number of active nodes in round %d is %di, links: %d\n", iiter, num_active, links);
active_links_num[iiter] = links;
}
void before_iteration(int iteration, graphchi_context &gcontext) {
num_active = 0;
links = 0;
}
}; // end of aggregator
vec fill_output(){
vec ret = vec::Zero(latent_factors_inmem.size());
for (uint i=0; i < latent_factors_inmem.size(); i++)
ret[i] = latent_factors_inmem[i].kcore;
return ret;
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi graph analytics library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
//* GraphChi initialization will read the command line arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("kcores-inmemory-factors");
std::string datafile;
int unittest = 0;
int max_iter = get_option_int("max_iter", 15000); // Number of iterations
maxval = get_option_float("maxval", 1e100);
minval = get_option_float("minval", -1e100);
bool quiet = get_option_int("quiet", 0);
if (quiet)
global_logger().set_log_level(LOG_ERROR);
debug = get_option_int("debug", 0);
unittest = get_option_int("unittest", 0);
datafile = get_option_string("training");
square = get_option_int("square", 0);
tokens_per_row = get_option_int("tokens_per_row", tokens_per_row);
nodes = get_option_int("nodes", nodes);
orig_edges = get_option_int("orig_edges", orig_edges);
active_nodes_num = ivec(max_iter+1);
active_links_num = ivec(max_iter+1);
//unit testing
if (unittest == 1){
datafile = "kcores_unittest1";
}
mytimer.start();
/* Preprocess data if needed, or discover preprocess files */
int nshards = 0;
if (tokens_per_row == 4 )
convert_matrixmarket4<edge_data>(datafile, false, square);
else if (tokens_per_row == 3 || tokens_per_row == 2)
convert_matrixmarket<edge_data>(datafile, NULL, nodes, orig_edges, tokens_per_row);
else logstream(LOG_FATAL)<<"Please use --tokens_per_row=3 or --tokens_per_row=4" << std::endl;
latent_factors_inmem.resize(square? std::max(M,N) : M+N);
KcoresProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(datafile, nshards, false, m);
set_engine_flags(engine);
engine.set_maxwindow(nodes+1);
int pass = 0;
for (iiter=1; iiter< max_iter+1; iiter++){
logstream(LOG_INFO)<<mytimer.current_time() << ") Going to run k-cores iteration " << iiter << std::endl;
while(true){
int prev_nodes = active_nodes_num[iiter];
/* Run */
engine.run(program, 1);
pass++;
int cur_nodes = active_nodes_num[iiter];
if (prev_nodes == cur_nodes)
break;
}
if (active_nodes_num[iiter] == 0){
max_iter = iiter;
break;
}
}
std::cout << "KCORES finished in " << mytimer.current_time() << std::endl;
std::cout << "Number of updates: " << pass*(M+N) << " pass: " << pass << std::endl;
imat retmat = imat(max_iter+1, 4);
memset((int*)data(retmat),0,sizeof(int)*retmat.size());
active_nodes_num[0] = (square? std::max(M,N) : M+N);
active_links_num[0] = L;
assert(L>0);
std::cout<<" Core Removed Total Removed"<<std::endl;
std::cout<<" Num Nodes Removed Links" <<std::endl;
for (int i=0; i <= max_iter; i++){
set_val(retmat, i, 0, i);
if (i >= 1){
set_val(retmat, i, 1, active_nodes_num[i-1]-active_nodes_num[i]);
set_val(retmat, i, 2, active_nodes_num[0]-active_nodes_num[i]);
assert(active_nodes_num[i] >= 0);
set_val(retmat, i, 3, L - active_links_num[i]);
}
}
//write_output_matrix(datafile + ".kcores.out", format, retmat);
std::cout<<retmat<<std::endl;
vec ret = fill_output();
write_output_vector(datafile + "x.out", ret,false, "This vector holds for each node its kcore degree");
if (unittest == 1){
imat sol = init_imat("0 0 0 0; 1 1 1 1; 2 4 5 7; 3 4 9 13", 4, 4);
assert(sumsum(sol - retmat) == 0);
}
return EXIT_SUCCESS;
}
| 09jijiangwen-download | toolkits/graph_analytics/kcores.cpp | C++ | asf20 | 7,833 |
/**
* @file
* @author Aapo Kyrola <akyrola@cs.cmu.edu>
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* Application for computing the connected components of a graph.
* The algorithm is simple: on first iteration each vertex sends its
* id to neighboring vertices. On subsequent iterations, each vertex chooses
* the smallest id of its neighbors and broadcasts its (new) label to
* its neighbors. The algorithm terminates when no vertex changes label.
*
* @section REMARKS
*
* This application is interesting demonstration of the asyncronous capabilities
* of GraphChi, improving the convergence considerably. Consider
* a chain graph 0->1->2->...->n. First, vertex 0 will write its value to its edges,
* which will be observed by vertex 1 immediatelly, changing its label to 0. Nexgt,
* vertex 2 changes its value to 0, and so on. This all happens in one iteration.
* A subtle issue is that as any pair of vertices a<->b share an edge, they will
* overwrite each others value. However, because they will be never run in parallel
* (due to deterministic parallellism of graphchi), this does not compromise correctness.
*
* @author Aapo Kyrola
*/
#include <cmath>
#include <string>
#include "graphchi_basic_includes.hpp"
#include "label_analysis.hpp"
#include "../collaborative_filtering/eigen_wrapper.hpp"
using namespace graphchi;
FILE * pfile = NULL;
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vid_t VertexDataType; // vid_t is the vertex id type
typedef vid_t EdgeDataType;
vec unique_labels;
int niters;
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct ConnectedComponentsProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Vertex update function.
* On first iteration ,each vertex chooses a label = the vertex id.
* On subsequent iterations, each vertex chooses the minimum of the neighbor's
* label (and itself).
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
/* This program requires selective scheduling. */
assert(gcontext.scheduler != NULL);
if (gcontext.iteration == 0) {
vertex.set_data(vertex.id());
gcontext.scheduler->add_task(vertex.id());
}
/* On subsequent iterations, find the minimum label of my neighbors */
vid_t curmin = vertex.get_data();
for(int i=0; i < vertex.num_edges(); i++) {
vid_t nblabel = vertex.edge(i)->get_data();
if (gcontext.iteration == 0) nblabel = vertex.edge(i)->vertex_id(); // Note!
curmin = std::min(nblabel, curmin);
}
/* Check if label changed */
vertex.set_data(curmin);
/**
* Broadcast new label to neighbors by writing the value
* to the incident edges.
* Note: on first iteration, write only to out-edges to avoid
* overwriting data (this is kind of a subtle point)
*/
vid_t label = vertex.get_data();
if (gcontext.iteration > 0) {
for(int i=0; i < vertex.num_edges(); i++) {
if (label < vertex.edge(i)->get_data()) {
vertex.edge(i)->set_data(label);
/* Schedule neighbor for update */
gcontext.scheduler->add_task(vertex.edge(i)->vertex_id());
}
}
} else if (gcontext.iteration == 0) {
for(int i=0; i < vertex.num_outedges(); i++) {
vertex.outedge(i)->set_data(label);
}
}
}
};
/* class for output the label number for each node (optional) */
class OutputVertexCallback : public VCallback<VertexDataType> {
public:
/* print node id and then the label id */
virtual void callback(vid_t vertex_id, VertexDataType &value) {
fprintf(pfile, "%u 1 %u\n", vertex_id+1, value); //graphchi offsets start from zero, while matlab from 1
unique_labels[value] = 1;
}
};
int main(int argc, const char ** argv) {
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("connected-components");
/* Basic arguments for application */
std::string filename = get_option_string("file"); // Base filename
niters = get_option_int("niters", 10); // Number of iterations (max)
int output_labels = get_option_int("output_labels", 0); //output node labels to file?
bool scheduler = true; // Always run with scheduler
/* Process input file - if not already preprocessed */
int nshards = convert_if_notexists<EdgeDataType>(filename, get_option_string("nshards", "auto"));
if (get_option_int("onlyresult", 0) == 0) {
/* Run */
ConnectedComponentsProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(filename, nshards, scheduler, m);
engine.run(program, niters);
/* optional: output labels for each node to file */
if (output_labels){
pfile = fopen((filename + "-components").c_str(), "w");
if (!pfile)
logstream(LOG_FATAL)<<"Failed to open file: " << filename << std::endl;
fprintf(pfile, "%%%%MatrixMarket matrix coordinate real general\n");
fprintf(pfile, "%lu %u %lu\n", engine.num_vertices()-1, 1, engine.num_vertices()-1);
OutputVertexCallback callback;
//unique_labels = zeros(engine.num_vertices());
//foreach_vertices<VertexDataType>(filename, 0, engine.num_vertices(), callback);
//fclose(pfile);
logstream(LOG_INFO)<<"Found: " << sum(unique_labels) << " unique labels " << std::endl;
/* Run analysis of the connected components (output is written to a file) */
m.start_time("label-analysis");
analyze_labels2<vid_t>(filename, pfile);
m.stop_time("label-analysis");
fclose(pfile);
}
}
return 0;
}
| 09jijiangwen-download | toolkits/graph_analytics/connectedcomponents.cpp | C++ | asf20 | 7,006 |
/**
* @file
* @author Aapo Kyrola <akyrola@cs.cmu.edu>
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* Application for computing the connected components of a graph.
* The algorithm is simple: on first iteration each vertex sends its
* id to neighboring vertices. On subsequent iterations, each vertex chooses
* the smallest id of its neighbors and broadcasts its (new) label to
* its neighbors. The algorithm terminates when no vertex changes label.
*
* @section REMARKS
*
* Version of connected components that keeps the vertex values
* in memory.
* @author Aapo Kyrola
*
* Danny B: added output of each vertex label
*/
#include <cmath>
#include <string>
#include "graphchi_basic_includes.hpp"
#include "label_analysis.hpp"
#include "../collaborative_filtering/eigen_wrapper.hpp"
#include "../collaborative_filtering/timer.hpp"
using namespace graphchi;
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vid_t VertexDataType; // vid_t is the vertex id type
typedef vid_t EdgeDataType;
VertexDataType * vertex_values;
size_t changes = 0;
timer mytimer;
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct ConnectedComponentsProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Called after an iteration has finished.
*/
void after_iteration(int iteration, graphchi_context &ginfo) {
logstream(LOG_DEBUG)<<mytimer.current_time() << "iteration: " << iteration << " changes: " << changes << std::endl;
if (changes == 0)
ginfo.set_last_iteration(iteration);
changes = 0;
}
vid_t neighbor_value(graphchi_edge<EdgeDataType> * edge) {
return vertex_values[edge->vertex_id()];
}
void set_data(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, vid_t value) {
vertex_values[vertex.id()] = value;
}
/**
* Vertex update function.
* On first iteration ,each vertex chooses a label = the vertex id.
* On subsequent iterations, each vertex chooses the minimum of the neighbor's
* label (and itself).
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
/* On subsequent iterations, find the minimum label of my neighbors */
vid_t curmin = vertex_values[vertex.id()];
for(int i=0; i < vertex.num_edges(); i++) {
vid_t nblabel = neighbor_value(vertex.edge(i));
curmin = std::min(nblabel, curmin);
}
if (vertex_values[vertex.id()] > curmin) {
changes++;
set_data(vertex, curmin);
}
}
/**
* Called before an iteration starts.
*/
void before_iteration(int iteration, graphchi_context &ctx) {
changes = 0;
if (iteration == 0) {
/* initialize each vertex with its own lable */
vertex_values = new VertexDataType[ctx.nvertices];
for(int i=0; i < (int)ctx.nvertices; i++) {
vertex_values[i] = i;
}
}
}
};
int main(int argc, const char ** argv) {
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("connected-components-inmem");
/* Basic arguments for application */
std::string filename = get_option_string("file"); // Base filename
int niters = get_option_int("niters", 100); // Number of iterations (max)
int output_labels = get_option_int("output_labels", 0); //output node labels to file?
bool scheduler = false; // Always run with scheduler
/* Process input file - if not already preprocessed */
int nshards = (int) convert_if_notexists<EdgeDataType>(filename, get_option_string("nshards", "auto"));
mytimer.start();
/* Run */
ConnectedComponentsProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(filename, nshards, scheduler, m);
engine.set_disable_vertexdata_storage();
engine.set_enable_deterministic_parallelism(false);
engine.set_modifies_inedges(false);
engine.set_modifies_outedges(false);
engine.set_preload_commit(false);
engine.set_maxwindow(engine.num_vertices());
engine.run(program, niters);
mytimer.start();
/* Run analysis of the connected components (output is written to a file) */
if (output_labels){
FILE * pfile = fopen((filename + "-components").c_str(), "w");
if (!pfile)
logstream(LOG_FATAL)<<"Failed to open file: " << filename << std::endl;
fprintf(pfile, "%%%%MatrixMarket matrix array real general\n");
fprintf(pfile, "%lu %u\n", engine.num_vertices()-1, 1);
for (uint i=1; i< engine.num_vertices(); i++){
fprintf(pfile, "%u\n", vertex_values[i]);
assert(vertex_values[i] >= 0 && vertex_values[i] < engine.num_vertices());
}
fclose(pfile);
logstream(LOG_INFO)<<"Saved succesfully to out file: " << filename << "-components" << " time for saving: " << mytimer.current_time() << std::endl;
}
return 0;
}
| 09jijiangwen-download | toolkits/graph_analytics/inmemconncomps.cpp | C++ | asf20 | 5,831 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
Written by Danny Bickson, CMU
1) File for extracting a subgraph out of the input graph, starting with a given set of seeds, for X hops.
2) This program also prints the degree distribution of a graph (using --degrees=1 command line argument)
3) This program also counts the number of edges for each connected compoentns (using the --cc=filename command line)
*
*/
#include <cmath>
#include <cstdio>
#include <limits>
#include <iostream>
#include <set>
#include "graphchi_basic_includes.hpp"
#include "api/chifilenames.hpp"
#include "api/vertex_aggregator.hpp"
#include "preprocessing/sharder.hpp"
#include "../collaborative_filtering/util.hpp"
#include "../collaborative_filtering/eigen_wrapper.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/common.hpp"
using namespace graphchi;
using namespace std;
int square = 0;
int tokens_per_row = 3;
int _degree = 0;
int seed_edges_only = 0;
int undirected = 1;
std::string cc;
size_t singleton_nodes = 0;
bool debug = false;
int max_iter = 50;
int iiter = 0; //current iteration
uint num_active = 0;
uint links = 0;
mutex mymutex;
timer mytimer;
FILE * pfile = NULL;
size_t edges = 1000; //number of edges to cut from graph
size_t nodes = 0; //number of nodes in original file (optional)
size_t orig_edges = 0; // number of edges in original file (optional)
int min_range = 0;
int max_range = 2400000000;
struct vertex_data {
bool active;
bool done;
bool next_active;
int component;
vec pvec; //to remove
vertex_data() : active(false), done(false), next_active(false), component(0) {}
void set_val(int index, double val){};
float get_val(int index){ return 0; }
}; // end of vertex_data
//edges in kcore algorithm are binary
struct edge_data {
edge_data() { }
//compatible with parser which have edge value (we don't need it)
edge_data(double val) { }
edge_data(double val, double time) { }
};
typedef vertex_data VertexDataType;
typedef edge_data EdgeDataType;
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
std::vector<vertex_data> latent_factors_inmem;
vec component_edges;
vec component_nodes;
vec component_seeds;
size_t changes = 0;
#include "../collaborative_filtering/io.hpp"
struct SubgraphsProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Vertex update function.
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
vertex_data & vdata = latent_factors_inmem[vertex.id()];
/* printout degree distribution and finish */
if (_degree){
if (vertex.num_edges() > 0 || max_range != 2400000000)
if (vertex.id() >= (uint)min_range && vertex.id() < (uint)max_range)
fprintf(pfile, "%u %u\n", vertex.id()+1, vertex.num_edges());
return;
}
/* calc component number of nodes and edges and finish */
else if (cc != ""){
assert(vdata.component>= 0 && vdata.component < component_nodes.size());
if (debug && vdata.component == 9322220)
logstream(LOG_DEBUG)<<"Node " << vertex.id() << " has " << vertex.num_edges() << std::endl;
if (vdata.component == 0)
return;
mymutex.lock();
component_nodes[vdata.component]++;
mymutex.unlock();
if (vertex.num_edges() == 0){
mymutex.lock();
singleton_nodes++;
mymutex.unlock();
}
for(int e=0; e < vertex.num_edges(); e++) {
vertex_data & other = latent_factors_inmem[vertex.edge(e)->vertex_id()];
if (debug && vdata.component == 9322220)
logstream(LOG_DEBUG)<<"Going over edge: " << vertex.id() << "=>" << vertex.edge(e)->vertex_id() << " component: " << vdata.component <<" : "<<other.component<< " seed? " << vdata.active << std::endl;
if (vdata.component != other.component)
logstream(LOG_FATAL)<<"BUG Going over edge: " << vertex.id() << "=>" << vertex.edge(e)->vertex_id() << " component: " << vdata.component <<" : "<<other.component<< " seed? " << vdata.active << std::endl;
if (vertex.id() < vertex.edge(e)->vertex_id()){
if (debug && other.component == 9322220)
logstream(LOG_INFO)<<"Added an edge for component: " << other.component << std::endl;
mymutex.lock();
component_edges[vdata.component]++;
mymutex.unlock();
}
}
return;
}
if (!vdata.active)
return;
mymutex.lock();
num_active++;
std::set<uint> myset;
std::set<uint>::iterator it;
for(int e=0; e < vertex.num_edges(); e++) {
vertex_data & other = latent_factors_inmem[vertex.edge(e)->vertex_id()];
if (links >= edges)
break;
if (other.done)
continue;
if (seed_edges_only && !other.active)
continue;
//solve a bug where an edge appear twice if A->B and B->A in the data
if (undirected){
it = myset.find(vertex.edge(e)->vertex_id());
if (it != myset.end())
continue;
}
fprintf(pfile, "%u %u %u\n", vertex.id()+1, vertex.edge(e)->vertex_id()+1,iiter+1);
if (undirected)
myset.insert(vertex.edge(e)->vertex_id());
if (debug && (vertex.id()+1 == 9322220 || vertex.edge(e)->vertex_id()+1 == 9322220))
cout<<"Found edge: $$$$ " << vertex.id() << " => " << vertex.edge(e)->vertex_id()+1 << " other.done " << other.done << endl;
links++;
if (!other.done){
other.next_active = true;
}
}
vdata.active=false;
vdata.done = true;
mymutex.unlock();
}
}; // end of aggregator
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi graph analytics library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
//* GraphChi initialization will read the command line arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("subgraph-inmemory-factors");
std::string datafile;
int max_iter = get_option_int("hops", 3); // Number of iterations
bool quiet = get_option_int("quiet", 0);
undirected = get_option_int("undirected", undirected);
if (quiet)
global_logger().set_log_level(LOG_ERROR);
debug = get_option_int("debug", 0);
datafile = get_option_string("training");
square = get_option_int("square", 0);
tokens_per_row = get_option_int("tokens_per_row", tokens_per_row);
edges = get_option_int("edges", 2460000000);
nodes = get_option_int("nodes", nodes);
orig_edges = get_option_int("orig_edges", orig_edges);
_degree = get_option_int("degree", _degree);
cc = get_option_string("cc", cc);
seed_edges_only = get_option_int("seed_edges_only", seed_edges_only);
if (_degree || cc != "" || seed_edges_only)
max_iter = 1;
std::string seeds = get_option_string("seeds","");
std::string seed_file = get_option_string("seed_file", "");
min_range = get_option_int("min_range", min_range);
max_range = get_option_int("max_range", max_range);
mytimer.start();
/* Preprocess data if needed, or discover preprocess files */
int nshards = 0;
if (tokens_per_row == 4 )
convert_matrixmarket4<edge_data>(datafile, false, square);
else if (tokens_per_row == 3 || tokens_per_row == 2)
convert_matrixmarket<edge_data>(datafile, NULL, nodes, orig_edges, tokens_per_row);
else logstream(LOG_FATAL)<<"Please use --tokens_per_row=2 or --tokens_per_row=3 or --tokens_per_row=4" << std::endl;
latent_factors_inmem.resize(square? std::max(M,N) : M+N);
vec vseed;
if (!_degree){
if (seed_file == ""){/* read list of seeds from the --seeds=XX command line argument */
if (seeds == "")
logstream(LOG_FATAL)<<"Must specify either seeds or seed_file"<<std::endl;
char * pseeds = strdup(seeds.c_str());
char * pch = strtok(pseeds, ",\n\r\t ");
int node = atoi(pch);
latent_factors_inmem[node-1].active = true;
while ((pch = strtok(NULL, ",\n\r\t "))!= NULL){
node = atoi(pch);
latent_factors_inmem[node-1].active = true;
}
}
else { /* load initial set of seeds from file */
vseed = load_matrix_market_vector(seed_file, false, false);
for (int i=0; i< vseed.size(); i++){
assert(vseed[i] > 0 && vseed[i] <= latent_factors_inmem.size());
latent_factors_inmem[vseed[i]-1].active = true;
}
}
}
vec components;
/* read a vector of connected components for each node */
if (cc != ""){
components = load_matrix_market_vector(cc, false,true);
assert((int)components.size() <= (int) latent_factors_inmem.size());
for (uint i=0; i< components.size(); i++){
assert(i+1 < latent_factors_inmem.size());
assert(components[i] >= 1 && components[i] <= nodes);
if (debug && components[i] == 9322220)
logstream(LOG_DEBUG)<<"Setting node : " <<i<<" component : " << components[i] << std::endl;
latent_factors_inmem[i].component = components[i];
}
component_edges = zeros(nodes);
component_nodes = zeros(nodes);
component_seeds = zeros(nodes);
for (uint i=0; i< vseed.size(); i++){
assert(vseed[i] >= 1 && vseed[i] <= latent_factors_inmem.size());
component_seeds[latent_factors_inmem[vseed[i]-1].component]++;
}
assert(sum(component_seeds) == vseed.size());
}
else if (seed_edges_only){
for (uint i=0; i< latent_factors_inmem.size(); i++){
vertex_data & vdata = latent_factors_inmem[i];
if (!vdata.active)
vdata.done = true;
}
}
std::string suffix;
if (cc != "")
suffix = "-cc.txt";
else if (seed_edges_only)
suffix = "-subset.txt";
else if (_degree)
suffix = "-degree.txt";
else suffix = "-subgraph.txt";
pfile = open_file((datafile + suffix).c_str(), "w", false);
std::cout<<"Writing output to: " << datafile << suffix << std::endl;
num_active = 0;
graphchi_engine<VertexDataType, EdgeDataType> engine(datafile, nshards, false, m);
set_engine_flags(engine);
engine.set_maxwindow(nodes+1);
SubgraphsProgram program;
for (iiter=0; iiter< max_iter; iiter++){
//std::cout<<mytimer.current_time() << ") Going to run subgraph iteration " << iiter << std::endl;
/* Run */
//while(true){
engine.run(program, 1);
std::cout<< iiter << ") " << mytimer.current_time() << " Number of active nodes: " << num_active <<" Number of links: " << links << std::endl;
for (uint i=0; i< latent_factors_inmem.size(); i++){
if (latent_factors_inmem[i].next_active && !latent_factors_inmem[i].done){
latent_factors_inmem[i].next_active = false;
latent_factors_inmem[i].active = true;
}
}
if (links >= edges){
std::cout<<"Grabbed enough edges!" << std::endl;
break;
}
}
if (cc != ""){
logstream(LOG_INFO)<<"component nodes sum: " << sum(component_nodes) << std::endl;
logstream(LOG_INFO)<<"component edges sum: " << sum(component_edges) << std::endl;
int total_written = 0;
assert(sum(component_nodes) == components.size());
assert(pfile != NULL);
int total_seeds = 0;
for (uint i=0; i< component_nodes.size(); i++){
if ((max_range != 2400000000 && i >= (uint)min_range && i < (uint)max_range) || (max_range == 2400000000 && (component_nodes[i] > 1 || component_edges[i] > 0))){
fprintf(pfile, "%d %d %d %d\n", i, (int)component_nodes[i], (int)component_edges[i], (int)component_seeds[i]);
total_written++;
total_seeds+= component_seeds[i];
}
if (component_nodes[i] > 1 && component_edges[i] == 0)
logstream(LOG_FATAL)<<"Bug: component " << i << " has " << component_nodes[i] << " but not edges!" <<std::endl;
if (component_nodes[i] == 0 && component_edges[i] > 0)
logstream(LOG_FATAL)<<"Bug: component " << i << " has " << component_edges[i] << " but not nodes!" <<std::endl;
if (component_seeds[i] == 0 && component_edges[i] > 0)
logstream(LOG_FATAL)<<"Bug: component " << i << " has " << component_edges[i] << " but not seeds!" << std::endl;
if (component_edges[i] > 0 && component_edges[i]+2 < component_nodes[i] )
logstream(LOG_FATAL)<<"Bug: component " << i << " has missing edges: " << component_edges[i] << " nodes: " << component_nodes[i] << std::endl;
if (component_nodes[i] == 2 && component_edges[i] == 2)
logstream(LOG_FATAL)<<"Bug: component " << i << " 2 nodes +2 edges: " << component_edges[i] << " nodes: " << component_nodes[i] << std::endl;
}
logstream(LOG_INFO)<<"total written components: " << total_written << " sum : " << sum(component_nodes) << std::endl;
logstream(LOG_INFO)<<"Singleton nodes (no edges): " << singleton_nodes << std::endl;
logstream(LOG_INFO)<<"Total seeds: " << total_seeds << std::endl;
}
else {
std::cout<< iiter << ") Number of active nodes: " << num_active <<" Number of links: " << links << std::endl;
std::cout << "subgraph finished in " << mytimer.current_time() << std::endl;
std::cout << "Number of passes: " << iiter<< std::endl;
std::cout << "Total active nodes: " << num_active << " edges: " << links << std::endl;
}
fflush(pfile);
fclose(pfile);
//delete pout;
return EXIT_SUCCESS;
}
| 09jijiangwen-download | toolkits/graph_analytics/subgraph.cpp | C++ | asf20 | 14,139 |
/**
* @file
* @author Danny Bickson
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Carnegie Mellon University]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @section DESCRIPTION
*
* Implementation of the label propagation algorithm
*/
#include "../collaborative_filtering/common.hpp"
#include "../collaborative_filtering/eigen_wrapper.hpp"
double alpha = 0.15;
int debug = 0;
struct vertex_data {
vec pvec;
bool seed;
vertex_data() {
pvec = zeros(D);
seed = false;
}
//this function is only called for seed nodes
void set_val(int index, float val){
pvec[index] = val;
seed = true;
}
float get_val(int index){
return pvec[index];
}
};
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef vertex_data VertexDataType;
typedef float EdgeDataType; // Edges store the "rating" of user->movie pair
graphchi_engine<VertexDataType, EdgeDataType> * pengine = NULL;
std::vector<vertex_data> latent_factors_inmem;
#include "../collaborative_filtering/io.hpp"
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct LPVerticesInMemProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
/**
* Vertex update function - computes the least square step
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
vertex_data & vdata = latent_factors_inmem[vertex.id()];
if (debug)
logstream(LOG_DEBUG)<<"Entering node: " << vertex.id() << " seed? " << vdata.seed << " in vector: " << vdata.pvec << std::endl;
if (vdata.seed || vertex.num_outedges() == 0) //if this is a seed node, don't do anything
return;
vec ret = zeros(D);
for(int e=0; e < vertex.num_outedges(); e++) {
float weight = vertex.edge(e)->get_data();
assert(weight != 0);
vertex_data & nbr_latent = latent_factors_inmem[vertex.edge(e)->vertex_id()];
ret += weight * nbr_latent.pvec;
}
//normalize probabilities
assert(sum(ret) != 0);
ret = ret / sum(ret);
vdata.pvec = alpha * vdata.pvec + (1-alpha)*ret;
vdata.pvec/= sum(vdata.pvec);
}
};
void output_lp_result(std::string filename) {
MMOutputter_mat<vertex_data> user_mat(filename + "_U.mm", 0, M , "This file contains LP output matrix U. In each row D probabilities for the Y labels", latent_factors_inmem);
logstream(LOG_INFO) << "LP output files (in matrix market format): " << filename << "_U.mm" << std::endl;
}
int main(int argc, const char ** argv) {
print_copyright();
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("label_propagation");
alpha = get_option_float("alpha", alpha);
debug = get_option_int("debug", debug);
parse_command_line_args();
//load graph (adj matrix) from file
int nshards = convert_matrixmarket<EdgeDataType>(training, NULL, 0, 0, 3, TRAINING, true);
if (M != N)
logstream(LOG_FATAL)<<"Label propagation supports only square matrices" << std::endl;
init_feature_vectors<std::vector<vertex_data> >(M, latent_factors_inmem, false);
//load seed initialization from file
load_matrix_market_matrix(training + ".seeds", 0, D);
#pragma omp parallel for
for (int i=0; i< (int)M; i++){
//normalize seed probabilities to sum up to one
if (latent_factors_inmem[i].seed){
assert(sum(latent_factors_inmem[i].pvec) != 0);
latent_factors_inmem[i].pvec /= sum(latent_factors_inmem[i].pvec);
continue;
}
//other nodes get random label probabilities
for (int j=0; j< D; j++)
latent_factors_inmem[i].pvec[j] = drand48();
}
/* load initial state from disk (optional) */
if (load_factors_from_file){
load_matrix_market_matrix(training + "_U.mm", 0, D);
}
/* Run */
LPVerticesInMemProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m);
set_engine_flags(engine);
pengine = &engine;
engine.run(program, niters);
/* Output latent factor matrices in matrix-market format */
output_lp_result(training);
/* Report execution metrics */
if (!quiet)
metrics_report(m);
return 0;
}
| 09jijiangwen-download | toolkits/graph_analytics/label_propagation.cpp | C++ | asf20 | 5,007 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Danny Bickson, CMU
*
*
* This program reads a text input file, where each line
* is taken from another document. The program counts the number of word
* occurances for each line (document) and outputs a document word count to be used
* in LDA.
*/
#include <cstdio>
#include <iostream>
#include <map>
#include <omp.h>
#include <assert.h>
#include "graphchi_basic_includes.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/util.hpp"
#include "common.hpp"
using namespace std;
using namespace graphchi;
bool debug = false;
timer mytime;
size_t lines;
unsigned long long total_lines = 0;
string dir;
string outdir;
std::vector<std::string> in_files;
//non word tokens that will be removed in the parsing
//it is possible to add additional special characters or remove ones you want to keep
const char spaces[] = {" \r\n\t!?@#$%^&*()-+.,~`\";:/"};
const char qoute[] = {",\""};
const char comma[] = {","};
int has_header_titles = 1;
std::vector<std::string> header_titles;
int from_val = -1; int to_val = -1;
int mid_val = -1;
void parse(int i){
in_file fin(in_files[i]);
out_file fout((outdir + in_files[i] + ".out"));
size_t linesize = 0;
char * saveptr = NULL, * saveptr2 = NULL,* linebuf = NULL;
size_t line = 1;
uint id;
if (has_header_titles){
char * linebuf = NULL;
size_t linesize;
char linebuf_debug[1024];
/* READ LINE */
int rc = getline(&linebuf, &linesize, fin.outf);
if (rc == -1)
logstream(LOG_FATAL)<<"Error header line " << " [ " << linebuf_debug << " ] " << std::endl;
strncpy(linebuf_debug, linebuf, 1024);
char *pch = strtok(linebuf,"\t,\r; ");
if (pch == NULL)
logstream(LOG_FATAL)<<"Error header line " << " [ " << linebuf_debug << " ] " << std::endl;
header_titles.push_back(pch);
if (debug) printf("Found title: %s\n", pch);
while (pch != NULL){
pch = strtok(NULL, "\t,\r; ");
if (pch == NULL)
break;
header_titles.push_back(pch);
if (debug) printf("Found title: %s\n", pch);
}
}
while(true){
int rc = getline(&linebuf, &linesize, fin.outf);
if (rc < 1)
return;
int index = 0;
char frombuf[256];
char tobuf[256];
char *pch = strtok_r(linebuf, ",", &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
fprintf(fout.outf,"\"%s\",", pch);
if (debug) printf("Found token 1 %s\n", pch);
if (pch[0] == '"')
pch++;
index++;
int from,to,mid;
if (index == from_val)
from = atoi(pch);
if (index == to_val)
to = atoi(pch);
if (index == mid_val)
mid = atoi(pch);
while(true){
pch = strtok_r(NULL, ",", &saveptr);
if (pch == NULL)
break;
index++;
if (debug) printf("Found token %d %s\n", index, pch);
if (pch[0] == '"')
pch++;
if (index == from_val)
from = atoi(pch);
if (index == to_val)
to = atoi(pch);
if (index == mid_val)
mid = atoi(pch);
}
char totalbuf[512];
if (mid_val == -1 && to_val == -1)
sprintf(totalbuf, "%d\t", from);
else if (mid_val != -1)
sprintf(totalbuf, "%d\t%d\t%d\t", from, mid, to);
else
sprintf(totalbuf, "%d\t%d\t", from, to);
if (debug) printf("Incrementing map: %s\n", totalbuf);
frommap.string2nodeid[totalbuf]++;
}
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
debug = get_option_int("debug", 0);
dir = get_option_string("file_list");
lines = get_option_int("lines", 0);
omp_set_num_threads(get_option_int("ncpus", 1));
from_val = get_option_int("from_val", from_val);
to_val = get_option_int("to_val", to_val);
mid_val = get_option_int("mid_val", mid_val);
if (from_val == -1)
logstream(LOG_FATAL)<<"Must set from/to " << std::endl;
mytime.start();
FILE * f = fopen(dir.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl;
while(true){
char buf[256];
int rc = fscanf(f, "%s\n", buf);
if (rc < 1)
break;
in_files.push_back(buf);
}
if (in_files.size() == 0)
logstream(LOG_FATAL)<<"Failed to read any file frommap from the list file: " << dir << std::endl;
#pragma omp parallel for
for (int i=0; i< (int)in_files.size(); i++)
parse(i);
std::cout << "Finished in " << mytime.current_time() << std::endl;
save_map_to_text_file(frommap.string2nodeid, outdir + dir + "map.text");
return 0;
}
| 09jijiangwen-download | toolkits/parsers/nbayes.cpp | C++ | asf20 | 5,312 |
#**
# * @file
# * @author Danny Bickson
# * @version 1.0
# *
# * @section LICENSE
# *
# * Copyright [2012] [Carngie Mellon University]
# *
# * Licensed under the Apache License, Version 2.0 (the "License");
# * you may not use this file except in compliance with the License.
# * You may obtain a copy of the License at
# *
# * http://www.apache.org/licenses/LICENSE-2.0
# *
# * Unless required by applicable law or agreed to in writing, software
# * distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
# Makefile for compiling graphchi collaborative filtering library
# Written by Danny Bickson
# Thanks to Yucheng Low for fixing the Makefile
INCFLAGS = -I/usr/local/include/ -I../../src/ -I.
CPPFLAGS = -O3 -DNDEBUG $(INCFLAGS) -DEIGEN_NDEBUG -fopenmp -Wall -Wno-strict-aliasing
LINKFLAGS = -lz
# Note : on Ubuntu on some compilers -lz is not detected properly so it is
# deliberatively set to be the last flag.
CPP = g++
CXX = g++
headers=$(wildcard *.h**)
all: $(patsubst %.cpp, %, $(wildcard *.cpp))
%: %.cpp $(headers)
$(CPP) $(CPPFLAGS) $< -o $@ $(LINKFLAGS)
clean:
rm -f $(patsubst %.cpp, %, $(wildcard *.cpp))
| 09jijiangwen-download | toolkits/parsers/Makefile | Makefile | asf20 | 1,333 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Danny Bickson, CMU */
#ifndef _GRAPHCHI_PARSERS_COMMON
#define _GRAPHCHI_PARSERS_COMMON
#include <map>
#include <string>
#include "graphchi_basic_includes.hpp"
using namespace graphchi;
mutex mymutex;
struct double_map{
std::map<std::string,uint> string2nodeid;
std::map<uint,std::string> nodeid2hash;
uint maxid;
double_map(){
maxid = 0;
}
};
double_map frommap;
double_map tomap;
template<typename T1>
void load_map_from_txt_file(T1 & map, const std::string filename, int fields){
logstream(LOG_INFO)<<"loading map from txt file: " << filename << std::endl;
FILE * f = fopen(filename.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file: " << filename << std::endl;
char * linebuf = NULL;
size_t linesize;
int line = 0;
while (true){
int rc = getline(&linebuf, &linesize, f);
char * to_free = linebuf;
if (rc == -1)
break;
if (fields == 1){
char *pch = strtok(linebuf,"\r\n\t");
if (!pch)
logstream(LOG_FATAL) << "Error when parsing file: " << filename << ":" << line <<std::endl;
map[pch] = ++line;
}
else {
char *pch = strtok(linebuf," \r\n\t");
if (!pch){
logstream(LOG_FATAL) << "Error when parsing file: " << filename << ":" << line <<std::endl;
}
char * pch2 = strtok(NULL,"\n");
if (!pch2)
logstream(LOG_FATAL) << "Error when parsing file: " << filename << ":" << line <<std::endl;
map[pch] = atoi(pch2);
line++;
}
//free(to_free);
}
logstream(LOG_INFO)<<"Map size is: " << map.size() << std::endl;
fclose(f);
}
void save_map_to_text_file(const std::map<std::string,uint> & map, const std::string filename, int optional_offset = 0){
std::map<std::string,uint>::const_iterator it;
out_file fout(filename);
unsigned int total = 0;
for (it = map.begin(); it != map.end(); it++){
fprintf(fout.outf, "%s %u\n", it->first.c_str(), it->second + optional_offset);
total++;
}
logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl;
}
void save_map_to_text_file(const std::map<unsigned long long,uint> & map, const std::string filename, int optional_offset = 0){
std::map<unsigned long long,uint>::const_iterator it;
out_file fout(filename);
unsigned int total = 0;
for (it = map.begin(); it != map.end(); it++){
fprintf(fout.outf, "%llu %u\n", it->first, it->second + optional_offset);
total++;
}
logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl;
}
void save_map_to_text_file(const std::map<uint,std::string> & map, const std::string filename){
std::map<uint,std::string>::const_iterator it;
out_file fout(filename);
unsigned int total = 0;
for (it = map.begin(); it != map.end(); it++){
fprintf(fout.outf, "%u %s\n", it->first, it->second.c_str());
total++;
}
logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl;
}
/*
* assign a consecutive id from either the [from] or [to] ids.
*/
void assign_id(double_map& dmap, unsigned int & outval, const std::string &name){
std::map<std::string,uint>::iterator it = dmap.string2nodeid.find(name);
//if an id was already assigned, return it
if (it != dmap.string2nodeid.end()){
outval = it->second;
return;
}
mymutex.lock();
//assign a new id
outval = dmap.string2nodeid[name];
if (outval == 0){
dmap.string2nodeid[name] = dmap.maxid;
dmap.nodeid2hash[dmap.maxid] = name;
outval = dmap.maxid;
dmap.maxid++;
}
mymutex.unlock();
}
#endif //_GRAPHCHI_PARSERS_COMMON
| 09jijiangwen-download | toolkits/parsers/common.hpp | C++ | asf20 | 4,446 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Danny Bickson, CMU
*
*
* This program reads a text input file, where each line
* is taken from another document. The program counts the number of word
* occurances for each line (document) and outputs a document word count to be used
* in LDA.
*/
#include <cstdio>
#include <iostream>
#include <map>
#include <omp.h>
#include <assert.h>
#include "graphchi_basic_includes.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/util.hpp"
#include "common.hpp"
using namespace std;
using namespace graphchi;
bool debug = false;
timer mytime;
size_t lines;
unsigned long long total_lines = 0;
string dir;
string outdir;
std::vector<std::string> in_files;
int min_threshold = 1; //output to file, token that appear at least min_threshold times
int max_threshold = 1234567890; //output to file tokens that appear at most max_threshold times
//non word tokens that will be removed in the parsing
//it is possible to add additional special characters or remove ones you want to keep
const char spaces[] = {" \r\n\t!?@#$%^&*()-+.,~`'\";:"};
void parse(int i){
in_file fin(in_files[i]);
out_file fout((outdir + in_files[i] + ".out"));
size_t linesize = 0;
char * saveptr = NULL, * linebuf = NULL;
size_t line = 1;
uint id;
while(true){
std::map<uint,uint> wordcount;
int rc = getline(&linebuf, &linesize, fin.outf);
if (rc < 1)
break;
if (strlen(linebuf) <= 1) //skip empty lines
continue;
char *pch = strtok_r(linebuf, spaces, &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
assign_id(frommap, id, pch);
wordcount[id]+= 1;
while(pch != NULL){
pch = strtok_r(NULL, spaces ,&saveptr);
if (pch != NULL && strlen(pch) > 1){
assign_id(frommap, id, pch);
wordcount[id]+= 1;
}
}
total_lines++;
std::map<uint,uint>::const_iterator it;
for (it = wordcount.begin(); it != wordcount.end(); it++){
if ((int)it->second >= min_threshold && (int)it->second <= max_threshold)
fprintf(fout.outf, "%lu %u %u\n", line, it->first, it->second);
}
line++;
if (lines && line>=lines)
break;
if (debug && (line % 50000 == 0))
logstream(LOG_INFO) << "Parsed line: " << line << " map size is: " << frommap.string2nodeid.size() << std::endl;
if (frommap.string2nodeid.size() % 500000 == 0)
logstream(LOG_INFO) << "Hash map size: " << frommap.string2nodeid.size() << " at time: " << mytime.current_time() << " edges: " << total_lines << std::endl;
}
logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl <<
"total map size: " << frommap.string2nodeid.size() << endl;
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
debug = get_option_int("debug", 0);
dir = get_option_string("file_list");
lines = get_option_int("lines", 0);
min_threshold = get_option_int("min_threshold", min_threshold);
max_threshold = get_option_int("max_threshold", max_threshold);
omp_set_num_threads(get_option_int("ncpus", 1));
mytime.start();
FILE * f = fopen(dir.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl;
while(true){
char buf[256];
int rc = fscanf(f, "%s\n", buf);
if (rc < 1)
break;
in_files.push_back(buf);
}
if (in_files.size() == 0)
logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl;
#pragma omp parallel for
for (int i=0; i< (int)in_files.size(); i++)
parse(i);
std::cout << "Finished in " << mytime.current_time() << std::endl;
save_map_to_text_file(frommap.string2nodeid, outdir + dir + "map.text");
save_map_to_text_file(frommap.nodeid2hash, outdir + dir + "reverse.map.text");
return 0;
}
| 09jijiangwen-download | toolkits/parsers/texttokens.cpp | C++ | asf20 | 4,864 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Danny Bickson, CMU
*
*
* This program reads a text input file, where each line
* is taken from another document. The program counts the number of word
* occurances for each line (document) and outputs a document word count to be used
* in LDA.
*/
#include <cstdio>
#include <iostream>
#include <map>
#include <omp.h>
#include <assert.h>
#include "graphchi_basic_includes.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/util.hpp"
#include "common.hpp"
#include <math.h>
#include <iomanip>
using namespace std;
using namespace graphchi;
bool debug = false;
timer mytime;
size_t lines;
unsigned long long total_lines = 0;
string dir;
string outdir;
std::vector<std::string> in_files;
//non word tokens that will be removed in the parsing
//it is possible to add additional special characters or remove ones you want to keep
const char spaces[] = {" \r\n\t!?@#$%^&*()-+.,~`\";:/"};
const char qoute[] = {",\""};
const char comma[] = {","};
int has_header_titles = 1;
std::map<std::string, int> p_x;
std::map<std::string, int> p_y;
int n = 0;
std::vector<std::string> header_titles;
int from_val = -1; int to_val = -1;
void parse(int i){
in_file fin(in_files[i]);
size_t linesize = 0;
char * saveptr = NULL, * saveptr2 = NULL,* linebuf = NULL;
size_t line = 1;
uint id;
if (has_header_titles){
char * linebuf = NULL;
size_t linesize;
char linebuf_debug[1024];
/* READ LINE */
int rc = getline(&linebuf, &linesize, fin.outf);
if (rc == -1)
logstream(LOG_FATAL)<<"Error header line " << " [ " << linebuf_debug << " ] " << std::endl;
strncpy(linebuf_debug, linebuf, 1024);
char *pch = strtok(linebuf,"\t,\r;\"");
if (pch == NULL)
logstream(LOG_FATAL)<<"Error header line " << " [ " << linebuf_debug << " ] " << std::endl;
for (int j=0; j < strlen(pch); j++) if (pch[j] == ' ') pch[j] = '_';
header_titles.push_back(pch);
if (debug) printf("Found title: %s\n", pch);
while (pch != NULL){
pch = strtok(NULL, "\t,\r;\"");
if (pch == NULL || pch[0] == '\0')
break;
for (int j=0; j < strlen(pch); j++) if (pch[j] == ' ') pch[j] = '_';
header_titles.push_back(pch);
if (debug) printf("Found title: %s\n", pch);
}
}
while(true){
int rc = getline(&linebuf, &linesize, fin.outf);
if (rc < 1)
return;
int index = 0;
char frombuf[256];
char tobuf[256];
char *pch = strtok_r(linebuf, ",\"", &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
if (debug) printf("Found token 1 %s\n", pch);
if (pch[0] == '"')
pch++;
index++;
bool found_from = false, found_to = false;
int from,to;
if (index == from_val){
strncpy(frombuf, pch, 256);
found_from = true;
}
if (index == to_val){
strncpy(tobuf, pch, 256);
found_to = true;
}
while(true){
pch = strtok_r(NULL, ",\"", &saveptr);
if (pch == NULL)
break;
index++;
if (debug) printf("Found token %d %s\n", index, pch);
if (pch[0] == '"')
pch++;
if (index > from_val && index > to_val)
break;
if (index == from_val){
strncpy(frombuf, pch, 256);
found_from = true;
}
if (index == to_val){
strncpy(tobuf, pch, 256);
found_to = true;
}
}
char totalbuf[512];
assert(found_from && found_to);
sprintf(totalbuf, "%s_%s", frombuf, tobuf);
if (debug) printf("Incrementing map: %s\n", totalbuf);
frommap.string2nodeid[totalbuf]++;
p_x[frombuf]++;
p_y[tobuf]++;
n++;
}
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
debug = get_option_int("debug", 0);
dir = get_option_string("file_list");
lines = get_option_int("lines", 0);
omp_set_num_threads(get_option_int("ncpus", 1));
from_val = get_option_int("from_val", from_val);
to_val = get_option_int("to_val", to_val);
if (from_val == -1)
logstream(LOG_FATAL)<<"Must set from/to " << std::endl;
mytime.start();
FILE * f = fopen(dir.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl;
while(true){
char buf[256];
int rc = fscanf(f, "%s\n", buf);
if (rc < 1)
break;
in_files.push_back(buf);
}
if (in_files.size() == 0)
logstream(LOG_FATAL)<<"Failed to read any file frommap from the list file: " << dir << std::endl;
#pragma omp parallel for
for (int i=0; i< (int)in_files.size(); i++)
parse(i);
std::cout << "Finished in " << mytime.current_time() << std::endl;
int total_x =0 , total_y = 0;
std::map<std::string, int>::iterator it;
double h = 0;
for (it = p_x.begin(); it != p_x.end(); it++){
total_x+= it->second;
h-= (it->second / (double)n)*log2(it->second / (double)n);
}
for (it = p_y.begin(); it != p_y.end(); it++)
total_y+= it->second;
assert(total_x == n);
assert(total_y == n);
double mi = 0;
std::map<std::string, uint>::iterator iter;
assert(n != 0);
int total_p_xy = 0;
for (iter = frommap.string2nodeid.begin() ; iter != frommap.string2nodeid.end(); iter++){
double p_xy = iter->second / (double)n;
assert(p_xy > 0);
char buf[256];
strncpy(buf, iter->first.c_str(), 256);
char * first = strtok(buf, "_");
char * second = strtok(NULL, "\n\r ");
assert(first && second);
double px = p_x[first] / (double)n;
double py = p_y[second] / (double)n;
assert(px > 0 && py > 0);
mi += p_xy * log2(p_xy / (px * py));
total_p_xy += iter->second;
}
assert(total_p_xy == n);
logstream(LOG_INFO)<<"Total examples: " <<n << std::endl;
logstream(LOG_INFO)<<"Unique p(x) " << p_x.size() << std::endl;
logstream(LOG_INFO)<<"Unique p(y) " << p_y.size() << std::endl;
logstream(LOG_INFO)<<"Average F(x) " << total_x / (double)p_x.size() << std::endl;
logstream(LOG_INFO)<<"Average F(y) " << total_y / (double)p_y.size() << std::endl;
std::cout<<"Mutual information of " << from_val << " [" << header_titles[from_val-1] << "] <-> " << to_val << " [" << header_titles[to_val-1] << "] is: " ;
if (mi/h > 1e-3)
std::cout<<std::setprecision(3) << mi << std::endl;
else std::cout<<"-"<<std::endl;
save_map_to_text_file(frommap.string2nodeid, outdir + dir + "map.text");
logstream(LOG_INFO)<<"Saving map file " << outdir << dir << "map.text" << std::endl;
return 0;
}
| 09jijiangwen-download | toolkits/parsers/mi.cpp | C++ | asf20 | 7,175 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Danny Bickson, CMU
*
* This program takes a file in the following graph format format:
* 1 1 050803 156
* 1 1 050803 12
* 2 2 050803 143
* 3 3 050803 0
* 4 4 050803 0
* 5 5 050803 1
* 6 6 050803 68
*
* Namely, a text file where the first field is a "from" field (uint >=1), second field is a "to" field (uint > = 1)
* and then there is a list of fields seperated by spaces (either strings or numbers) which characterize this edge.
*
* The input file is sorted by the from and to fields.
*
* The output of this program is a sorted graph, where edges values are aggregated together, s.t. each edge
* appears only once:
* 1 1 050803 168
* 2 2 050803 143
* 3 3 050803 0
* 4 4 050803 0
* 5 5 050803 1
* 6 6 050803 68
*
* Namely, an aggregation of the value in column defined by --col=XX command line flag,
* in the above example 168 = 156+12
* */
#include <cstdio>
#include <map>
#include <iostream>
#include <map>
#include <omp.h>
#include <assert.h>
#include "graphchi_basic_includes.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/util.hpp"
using namespace std;
using namespace graphchi;
bool debug = false;
timer mytime;
size_t lines;
unsigned long long total_lines = 0;
string dir;
string outdir;
std::vector<std::string> in_files;
int col = 3;
//non word tokens that will be removed in the parsing
//it is possible to add additional special characters or remove ones you want to keep
const char spaces[] = {" \r\n\t!?@#$%^&*()-+.,~`'\";:"};
void parse(int i){
in_file fin(in_files[i]);
out_file fout((outdir + in_files[i] + ".out"));
size_t linesize = 0;
char * saveptr = NULL, * linebuf = NULL;
size_t line = 1;
double total = 0;
uint from = 0, to = 0;
uint last_from = 0, last_to = 0;
while(true){
int rc = getline(&linebuf, &linesize, fin.outf);
if (rc < 1)
break;
if (strlen(linebuf) <= 1) //skip empty lines
continue;
//identify from and to fields
char *pch = strtok_r(linebuf, spaces, &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; continue; }
from = atoi(pch);
pch = strtok_r(NULL, spaces ,&saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; continue; }
to = atoi(pch);
int col_num = 3;
//go over the rest of the line
while(true){
pch = strtok_r(NULL, spaces ,&saveptr);
if (pch == NULL && col_num > col)
break;
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; continue; }
//aggregate the requested column
if (col == col_num){
if (from != last_from || to != last_to){
if (last_from != 0 && last_to != 0)
fprintf(fout.outf, "%u %u %g\n", last_from, last_to, total);
total = atof(pch);
}
else
total += atof(pch);
}
col_num++;
}
last_from = from; last_to = to;
total_lines++;
line++;
if (lines && line>=lines)
break;
if (debug && (line % 50000 == 0))
logstream(LOG_INFO) << "Parsed line: " << line << std::endl;
}
if (last_from != 0 && last_to != 0)
fprintf(fout.outf, "%u %u %g\n", last_from, last_to, total);
logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl;
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
debug = get_option_int("debug", 0);
dir = get_option_string("file_list");
lines = get_option_int("lines", 0);
col = get_option_int("col", 3);
omp_set_num_threads(get_option_int("ncpus", 1));
mytime.start();
FILE * f = fopen(dir.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl;
while(true){
char buf[256];
int rc = fscanf(f, "%s\n", buf);
if (rc < 1)
break;
in_files.push_back(buf);
}
if (in_files.size() == 0)
logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl;
#pragma omp parallel for
for (int i=0; i< (int)in_files.size(); i++)
parse(i);
std::cout << "Finished in " << mytime.current_time() << std::endl;
return 0;
}
| 09jijiangwen-download | toolkits/parsers/aggregator.cpp | C++ | asf20 | 5,359 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Code by Yucheng Low, UW
* Adapted by Danny Bickson, CMU
*
* File for counting the number of unsigned int occurances in a text file
* Where each line has one value
*
* For example, input file named "in" has the following lines:
*
* 1
* 2
* 2
* 3
* 3
* 3
* 3
* 3
* 3
* 3
* 3
*
* The output of "./count in"
* 1 1
* 2 2
* 3 8
*/
#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include <stdint.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char** argv) {
if (argc <= 1){
std::cerr<<"Usage: counter <input file name>" << std::endl;
exit(1);
}
std::ifstream fin(argv[1]);
map<uint32_t, uint32_t> count;
size_t lines = 0;
while(fin.good()) {
std::string b;
++lines;
getline(fin, b);
if (fin.eof())
break;
int32_t bid = atol(b.c_str());
if (lines >= 3){
++count[bid];
//std::cout<<"adding: " << bid << std::endl;
if (lines % 5000000 == 0) {
std::cerr << lines << " lines\n";
}
}
}
fin.close();
map<uint32_t, uint32_t>::iterator itr;
for(itr = count.begin(); itr != count.end(); ++itr){
if ((*itr).second > 0 )
std::cout<< (*itr).first << " " <<(*itr).second<<std::endl;
}
}
| 09jijiangwen-download | toolkits/parsers/count.cpp | C++ | asf20 | 1,914 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Stefan Weigert, TUD based on the
* "consecutive_matrix_market.cpp" parser
*/
#include <cstdio>
#include <map>
#include <omp.h>
#include <cassert>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "graphchi_basic_includes.hpp"
#include "../collaborative_filtering/util.hpp"
using namespace graphchi;
// global options
int debug = 0;
int csv = 0;
int tsv = 0;
const char* token;
std::vector<std::string> in_files;
// global data-structs
mutex ids_mutex;
std::map<unsigned int, unsigned int> ids;
/*
* The expected format is one of the following:
*
*
* <source-ip>\t<dst-ip>\t<some attribute>
* <source-ip>,<dst-ip>,<other stuff>
* <source-ip> <dst-ip> <other stuff>
*/
void parse(int i) {
uint64_t max_id = 1;
in_file fin(in_files[i].c_str());
out_file fout(std::string(in_files[i] + ".out").c_str());
uint64_t lines = 0;
uint64_t hits = 0;
while(true) {
struct in_addr caller;
struct in_addr callee;
char line[256];
char* res = fgets(line, 256, fin.outf);
// end of file
if (res == NULL) {
break;
}
char* caller_str = strtok(line, token);
assert(caller_str != NULL);
char* callee_str = strtok(NULL, token);
assert(callee_str != NULL);
char* attribute = strtok(NULL, token);
assert(attribute != NULL);
// try to convert caller - if it goes wrong just continue
if (inet_aton(caller_str, &caller) == 0) {
if (debug) logstream(LOG_WARNING) << "could not convert caller-ip:" << caller_str << std::endl;
continue;
}
// try to convert caller - if it goes wrong just continue
if (inet_aton(callee_str, &callee) == 0) {
if (debug) logstream(LOG_WARNING) << "could not convert callee-ip:" << caller_str << std::endl;
continue;
}
// check if we know that ip already
if (ids.find(caller.s_addr) == ids.end()) {
// we don't - IDs are global to all threads and files, so
// lock
ids_mutex.lock();
// another thread might have added that IP
// meanwhile. non-existing keys have a value of 0
// initially
if (ids[caller.s_addr] == 0) {
// do the actual update
ids[caller.s_addr] = max_id;
++max_id;
}
ids_mutex.unlock();
} else {
++hits;
}
// repeat the same for the callee
if (ids.find(callee.s_addr) == ids.end()) {
ids_mutex.lock();
if (ids[callee.s_addr] == 0) {
ids[callee.s_addr] = max_id;
++max_id;
}
ids_mutex.unlock();
} else {
++hits;
}
// attribute already contains the '\n' since it's the last
// string on the line
if (tsv) {
fprintf(fout.outf, "%u\t%u\t%s", ids[caller.s_addr], ids[callee.s_addr], attribute);
} else if (csv) {
fprintf(fout.outf, "%u,%u,%s", ids[caller.s_addr], ids[callee.s_addr], attribute);
} else {
fprintf(fout.outf, "%u %u %s", ids[caller.s_addr], ids[callee.s_addr], attribute);
}
if (++lines % 100000 == 0) {
logstream(LOG_INFO) << "Edges: " << lines
<< ", Ids: " << ids.size()
<< ", Hits: " << hits << "\n";
}
}
logstream(LOG_INFO) << "Finished parsing " << in_files[i] << std::endl;
}
int main(int argc, const char *argv[]) {
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
// get options
debug = get_option_int("debug", 0);
std::string dir = get_option_string("file");
omp_set_num_threads(get_option_int("ncpus", 1));
tsv = get_option_int("tsv", 0); // is this tab seperated file?
csv = get_option_int("csv", 0); // is the comma seperated file?
if (tsv) token = "\t";
else if (csv) token = ",";
else token = " ";
// read list-of files
FILE * f = fopen(dir.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL) << "Failed to open file list!" << std::endl;
while(true){
char buf[256];
int rc = fscanf(f, "%s\n", buf);
if (rc < 1)
break;
in_files.push_back(buf);
}
// process each file (possibly in parallel)
#pragma omp parallel
for(unsigned i = 0; i < in_files.size(); ++i) {
parse(i);
}
// serialize the id-map
logstream(LOG_INFO) << "serializing ids..." << std::endl;
out_file fout(std::string(dir + ".map").c_str());
for (std::map<unsigned int, unsigned int>::const_iterator it = ids.begin();
it != ids.end();
++it)
{
if (tsv) fprintf(fout.outf, "%u\t%u\n", it->first, it->second);
else if (csv) fprintf(fout.outf, "%u,%u\n", it->first, it->second);
else fprintf(fout.outf, "%u %u\n", it->first, it->second);
}
return 0;
}
| 09jijiangwen-download | toolkits/parsers/ips2ids.cpp | C++ | asf20 | 6,026 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Danny Bickson, CMU
*
* File for converting graph in SNAP format to GraphChi CF toolkit format.
* See SNAP format explanation here: http://docs.graphlab.org/graph_formats.html
* See GraphChi matrix market format here: http://bickson.blogspot.co.il/2012/02/matrix-market-format.html
*/
#include <cstdio>
#include <map>
#include <iostream>
#include <map>
#include <omp.h>
#include <assert.h>
#include "graphchi_basic_includes.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/util.hpp"
#include "../../example_apps/matrix_factorization/matrixmarket/mmio.h"
#include "../../example_apps/matrix_factorization/matrixmarket/mmio.c"
using namespace std;
using namespace graphchi;
bool debug = false;
map<string,uint> string2nodeid;
map<uint,string> nodeid2hash;
map<string,uint> string2nodeid2;
map<uint,string> nodeid2hash2;
uint conseq_id;
uint conseq_id2;
mutex mymutex;
timer mytime;
size_t lines;
unsigned long long total_lines = 0;
string dir;
string outdir;
std::vector<std::string> in_files;
uint M,N;
size_t nnz = 0;
const char * string_to_tokenize;
int csv = 0;
int tsv = 0;
int binary = 0; //edges are binary, contain no weights
int single_domain = 0; //both user and movies ids are from the same id space:w
const char * spaces = " \r\n\t";
const char * tsv_spaces = "\t\n";
const char * csv_spaces = ",\n";
void save_map_to_text_file(const std::map<std::string,uint> & map, const std::string filename){
std::map<std::string,uint>::const_iterator it;
out_file fout(filename);
unsigned int total = 0;
for (it = map.begin(); it != map.end(); it++){
fprintf(fout.outf, "%s %u\n", it->first.c_str(), it->second);
total++;
}
logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl;
}
void save_map_to_text_file(const std::map<uint,std::string> & map, const std::string filename){
std::map<uint,std::string>::const_iterator it;
out_file fout(filename);
unsigned int total = 0;
for (it = map.begin(); it != map.end(); it++){
fprintf(fout.outf, "%u %s\n", it->first, it->second.c_str());
total++;
}
logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl;
}
/*
* assign a consecutive id from either the [from] or [to] ids.
*/
void assign_id(map<string,uint> & string2nodeid, map<uint,string> & nodeid2hash, uint & outval, const string &name, bool from){
map<string,uint>::iterator it = string2nodeid.find(name);
//if an id was already assigned, return it
if (it != string2nodeid.end()){
outval = it->second;
return;
}
mymutex.lock();
//assign a new id
outval = string2nodeid[name];
if (outval == 0){
//update the mapping between string to the id
string2nodeid[name] = (from? ++conseq_id : ++conseq_id2);
//return the id
outval = (from? conseq_id : conseq_id2);
//store the reverse mapping between id to string
nodeid2hash[outval] = name;
if (from)
M = std::max(M, conseq_id);
else
N = std::max(N, conseq_id2);
}
mymutex.unlock();
}
/* example file format:
* 2884424247 11 1210682095 1789803763 1879013170 1910216645 2014570227
* 2109318072 2268277425 2289674265 2340794623 2513611825 2770280793
* 2884596247 31 1191220232 1191258123 1225281292 1240067740
* 2885009247 16 1420862042 1641392180 1642909335 1775498871 1781379945
* 1784537661 1846581167 1934183965 2011304655 2016713117 2017390697
* 2128869911 2132021133 2645747085 2684129850 2866009832
*/
void parse(int i){
in_file fin(in_files[i]);
out_file fout((outdir + in_files[i] + ".out"));
size_t linesize = 0;
char * saveptr = NULL, * linebuf = NULL;
char linebuf_debug[1024];
size_t line = 1;
uint from,to;
bool matrix_market = false;
while(true){
int rc = getline(&linebuf, &linesize, fin.outf);
strncpy(linebuf_debug, linebuf, 1024);
if (rc < 1)
break;
if (strlen(linebuf) <= 1) //skip empty lines
continue;
//skipping over matrix market header (if any)
if (!strncmp(linebuf, "%%MatrixMarket", 14)){
matrix_market = true;
continue;
}
if (matrix_market && linebuf[0] == '%'){
continue;
}
if (matrix_market && linebuf[0] != '%'){
matrix_market = false;
continue;
}
//read [FROM]
char *pch = strtok_r(linebuf,string_to_tokenize, &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf_debug << "]" << std::endl; return; }
assign_id(string2nodeid,nodeid2hash, from, pch, true);
//read [NUMBER OF EDGES]
pch = strtok_r(NULL,string_to_tokenize, &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf_debug << "]" << std::endl; return; }
int num_edges = atoi(pch);
if (num_edges < 0)
{ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf_debug << "] - number of edges < 0" << std::endl; return; }
for (int k=0; k< num_edges; k++){
pch = strtok_r(NULL, "\n\t\r, ", &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf_debug << "]" << std::endl; return; }
assign_id(single_domain ? string2nodeid:string2nodeid2,
single_domain ? nodeid2hash : nodeid2hash2, to, pch, single_domain ? true : false);
if (tsv)
fprintf(fout.outf, "%u\t%u\n", from, to);
else if (csv)
fprintf(fout.outf, "%u,%un", from, to);
else
fprintf(fout.outf, "%u %u\n", from, to);
nnz++;
}
line++;
total_lines++;
if (lines && line>=lines)
break;
if (debug && (line % 50000 == 0))
logstream(LOG_INFO) << "Parsed line: " << line << " map size is: " << string2nodeid.size() << std::endl;
if (string2nodeid.size() % 500000 == 0)
logstream(LOG_INFO) << "Hash map size: " << string2nodeid.size() << " at time: " << mytime.current_time() << " edges: " << total_lines << std::endl;
}
logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl <<
"total map size: " << string2nodeid.size() << endl;
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
debug = get_option_int("debug", 0);
dir = get_option_string("file_list");
lines = get_option_int("lines", 0);
omp_set_num_threads(get_option_int("ncpus", 1));
tsv = get_option_int("tsv", 0); //is this tab seperated file?
csv = get_option_int("csv", 0); // is the comma seperated file?
binary = get_option_int("binary", 0);
single_domain = get_option_int("single_domain", 0);
mytime.start();
string_to_tokenize = spaces;
if (tsv)
string_to_tokenize = tsv_spaces;
else if (csv)
string_to_tokenize = csv_spaces;
FILE * f = fopen(dir.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl;
while(true){
char buf[256];
int rc = fscanf(f, "%s\n", buf);
if (rc < 1)
break;
in_files.push_back(buf);
}
if (in_files.size() == 0)
logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl;
//#pragma omp parallel for
for (uint i=0; i< in_files.size(); i++)
parse(i);
std::cout << "Finished in " << mytime.current_time() << std::endl;
save_map_to_text_file(string2nodeid, outdir + dir + "user.map.text");
save_map_to_text_file(nodeid2hash, outdir + dir + "user.reverse.map.text");
if (!single_domain){
save_map_to_text_file(string2nodeid2, outdir + dir + "movie.map.text");
save_map_to_text_file(nodeid2hash2, outdir + dir + "movie.reverse.map.text");
}
logstream(LOG_INFO)<<"Writing matrix market header into file: matrix_market.info" << std::endl;
out_file fout("matrix_market.info");
MM_typecode out_typecode;
mm_clear_typecode(&out_typecode);
mm_set_integer(&out_typecode);
mm_set_sparse(&out_typecode);
mm_set_matrix(&out_typecode);
mm_write_banner(fout.outf, out_typecode);
mm_write_mtx_crd_size(fout.outf, M, single_domain ? M : N, nnz);
return 0;
}
| 09jijiangwen-download | toolkits/parsers/adj.cpp | C++ | asf20 | 9,141 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Danny Bickson, CMU
*/
#include <cstdio>
#include <map>
#include <iostream>
#include <map>
#include <omp.h>
#include <assert.h>
#include "graphchi_basic_includes.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/util.hpp"
#include "../../example_apps/matrix_factorization/matrixmarket/mmio.h"
#include "../../example_apps/matrix_factorization/matrixmarket/mmio.c"
#include "common.hpp"
using namespace std;
using namespace graphchi;
#define DIVIDE_FACTOR 1
mutex mymutexarray[DIVIDE_FACTOR];
bool debug = false;
map<unsigned long long,uint> string2nodeid[DIVIDE_FACTOR];
//map<uint,string> nodeid2hash;
map<unsigned long long,uint> string2nodeid2[DIVIDE_FACTOR];
//map<uint,string> nodeid2hash2;
uint conseq_id;
uint conseq_id2;
timer mytime;
size_t lines;
unsigned long long total_lines = 0;
string dir;
string outdir;
std::vector<std::string> in_files;
uint M,N;
size_t nnz = 0;
const char * string_to_tokenize;
int csv = 0;
int tsv = 0;
int binary = 0; //edges are binary, contain no weights
int single_domain = 0; //both user and movies ids are from the same id space:w
const char * spaces = " \r\n\t";
const char * tsv_spaces = "\t\n";
const char * csv_spaces = ",\n";
timer mytimer;
int ncpus = 1;
/*
* assign a consecutive id from either the [from] or [to] ids.
*/
void assign_id(map<unsigned long long,uint> & string2nodeid, uint & outval, const unsigned long long name, bool from, int mod){
map<unsigned long long,uint>::iterator it = string2nodeid.find(name);
//if an id was already assigned, return it
if (it != string2nodeid.end()){
outval = it->second;
return;
}
if (ncpus > 1)
mymutexarray[mod].lock();
//assign a new id
outval = string2nodeid[name];
if (outval == 0){
//update the mapping between string to the id
string2nodeid[name] = ((from || single_domain)? ++conseq_id : ++conseq_id2);
//return the id
outval = ((from || single_domain)? conseq_id : conseq_id2);
}
if (ncpus > 1)
mymutexarray[mod].unlock();
}
void parse(int i){
in_file fin(in_files[i]);
out_file fout((outdir + in_files[i] + ".out"));
size_t linesize = 0;
char * saveptr = NULL, * linebuf = NULL;
size_t line = 1;
uint from,to;
bool matrix_market = false;
while(true){
int rc = getline(&linebuf, &linesize, fin.outf);
if (rc < 1)
break;
if (strlen(linebuf) <= 1){ //skip empty lines
continue;
}
//skipping over matrix market header (if any)
if (!strncmp(linebuf, "%%MatrixMarket", 14)){
matrix_market = true;
continue;
}
if (matrix_market && linebuf[0] == '%'){
continue;
}
if (matrix_market && linebuf[0] != '%'){
matrix_market = false;
continue;
}
//read [FROM]
char *pch = strtok_r(linebuf,string_to_tokenize, &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
unsigned long long id = atoll(pch);
int mod = id % DIVIDE_FACTOR;
assign_id(string2nodeid[mod], from, atoll(pch), true, mod);
//read [TO]
pch = strtok_r(NULL,string_to_tokenize, &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
id = atoll(pch);
int mod2 = id % DIVIDE_FACTOR;
assign_id(single_domain ? string2nodeid[mod]:string2nodeid2[mod2], to, atoll(pch), single_domain ? true : false, single_domain ? mod : mod2);
//read the rest of the line
if (!binary){
pch = strtok_r(NULL, "\n", &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
}
if (tsv)
fprintf(fout.outf, "%d%u\t%d%u\t%s\n", mod, from, mod2, to, binary? "": pch);
else if (csv)
fprintf(fout.outf, "%d%u,%d%u,%s\n", mod, from, mod2, to, binary? "" : pch);
else
fprintf(fout.outf, "%d%u %d%u %s\n", mod, from, mod2, to, binary? "" : pch);
nnz++;
line++;
total_lines++;
if (lines && line>=lines)
break;
if (debug && (line % 1000000 == 0))
logstream(LOG_INFO) << mytimer.current_time() << ") Parsed line: " << line << " map size is: " << string2nodeid[0].size() << std::endl;
if (string2nodeid[0].size() % 100000 == 0)
logstream(LOG_INFO) << mytimer.current_time() << ") Hash map size: " << string2nodeid[0].size() << " at time: " << mytime.current_time() << " edges: " << total_lines << std::endl;
}
logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl <<
"total map size: " << string2nodeid[0].size() << endl;
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
mytimer.start();
debug = get_option_int("debug", 0);
dir = get_option_string("file_list");
lines = get_option_int("lines", 0);
ncpus = get_option_int("ncpus", ncpus);
omp_set_num_threads(ncpus);
tsv = get_option_int("tsv", 0); //is this tab seperated file?
csv = get_option_int("csv", 0); // is the comma seperated file?
binary = get_option_int("binary", 0);
single_domain = get_option_int("single_domain", 0);
mytime.start();
string_to_tokenize = spaces;
if (tsv)
string_to_tokenize = tsv_spaces;
else if (csv)
string_to_tokenize = csv_spaces;
FILE * f = fopen(dir.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl;
while(true){
char buf[256];
int rc = fscanf(f, "%s\n", buf);
if (rc < 1)
break;
in_files.push_back(buf);
}
if (in_files.size() == 0)
logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl;
#pragma omp parallel for
for (uint i=0; i< in_files.size(); i++)
parse(i);
std::cout << "Finished in " << mytime.current_time() << std::endl;
M = 0;
for (int i=0; i< DIVIDE_FACTOR; i++)
M += string2nodeid[i].size();
if (single_domain)
N = M;
else {
N = 0;
for (int i=0; i< DIVIDE_FACTOR; i++)
N += string2nodeid2[i].size();
}
#pragma omp parallel for
for (int i=0; i< DIVIDE_FACTOR; i++){
char buf[256];
sprintf(buf, "user.map.%d", i);
save_map_to_text_file(string2nodeid[i], outdir + std::string(buf));
if (!single_domain){
save_map_to_text_file(string2nodeid2[i], outdir + std::string(buf));
}
}
logstream(LOG_INFO)<<"Writing matrix market header into file: matrix_market.info" << std::endl;
out_file fout("matrix_market.info");
MM_typecode out_typecode;
mm_clear_typecode(&out_typecode);
mm_set_integer(&out_typecode);
mm_set_sparse(&out_typecode);
mm_set_matrix(&out_typecode);
mm_write_banner(fout.outf, out_typecode);
mm_write_mtx_crd_size(fout.outf, M, N, nnz);
return 0;
}
| 09jijiangwen-download | toolkits/parsers/consecutive_longs.cpp | C++ | asf20 | 7,801 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Danny Bickson, CMU
*/
#include <cstdio>
#include <map>
#include <iostream>
#include <map>
#include <omp.h>
#include <assert.h>
#include "graphchi_basic_includes.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/util.hpp"
#include "../../example_apps/matrix_factorization/matrixmarket/mmio.h"
#include "../../example_apps/matrix_factorization/matrixmarket/mmio.c"
#include "common.hpp"
using namespace std;
using namespace graphchi;
bool debug = false;
map<string,uint> string2nodeid;
//map<uint,string> nodeid2hash;
map<string,uint> string2nodeid2;
//map<uint,string> nodeid2hash2;
uint conseq_id;
uint conseq_id2;
timer mytime;
size_t lines;
unsigned long long total_lines = 0;
string dir;
string outdir;
std::vector<std::string> in_files;
uint M,N;
size_t nnz = 0;
const char * string_to_tokenize;
int csv = 0;
int tsv = 0;
int binary = 0; //edges are binary, contain no weights
int single_domain = 0; //both user and movies ids are from the same id space:w
const char * spaces = " \r\n\t";
const char * tsv_spaces = "\t\n";
const char * csv_spaces = "\",\n";
timer mytimer;
int has_header_titles = 0;
int ignore_rest_of_line = 0;
/*
* assign a consecutive id from either the [from] or [to] ids.
*/
void assign_id(map<string,uint> & string2nodeid, uint & outval, const string &name, bool from){
map<string,uint>::iterator it = string2nodeid.find(name);
//if an id was already assigned, return it
if (it != string2nodeid.end()){
outval = it->second;
return;
}
mymutex.lock();
//assign a new id
outval = string2nodeid[name];
if (outval == 0){
//update the mapping between string to the id
string2nodeid[name] = ((from || single_domain)? ++conseq_id : ++conseq_id2);
//return the id
outval = ((from || single_domain)? conseq_id : conseq_id2);
}
mymutex.unlock();
}
void parse(int i){
in_file fin(in_files[i]);
out_file fout((outdir + in_files[i] + ".out"));
size_t linesize = 0;
char * saveptr = NULL, * linebuf = NULL;
size_t line = 1;
uint from,to;
bool matrix_market = false;
while(true){
int rc = getline(&linebuf, &linesize, fin.outf);
if (rc < 1)
break;
if (strlen(linebuf) <= 1){ //skip empty lines
line++;
continue;
}
if (has_header_titles && line == 1){
line++;
continue;
}
//skipping over matrix market header (if any)
if (!strncmp(linebuf, "%%MatrixMarket", 14)){
matrix_market = true;
continue;
}
if (matrix_market && linebuf[0] == '%'){
continue;
}
if (matrix_market && linebuf[0] != '%'){
matrix_market = false;
continue;
}
//read [FROM]
char *pch = strtok_r(linebuf,string_to_tokenize, &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
assign_id(string2nodeid, from, pch, true);
//read [TO]
pch = strtok_r(NULL,string_to_tokenize, &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
assign_id(single_domain ? string2nodeid:string2nodeid2, to, pch, single_domain ? true : false);
//read the rest of the line
if (!binary){
if (ignore_rest_of_line)
pch = strtok_r(NULL, string_to_tokenize, &saveptr);
else
pch = strtok_r(NULL, "\n", &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
}
if (tsv)
fprintf(fout.outf, "%u\t%u\t%s\n", from, to, binary? "": pch);
else if (csv)
fprintf(fout.outf, "%u %u %s\n", from, to, binary? "" : pch);
else
fprintf(fout.outf, "%u %u %s\n", from, to, binary? "" : pch);
nnz++;
line++;
total_lines++;
if (lines && line>=lines)
break;
if (debug && (line % 50000 == 0))
logstream(LOG_INFO) << mytimer.current_time() << ") Parsed line: " << line << " map size is: " << string2nodeid.size() << std::endl;
if (string2nodeid.size() % 500000 == 0)
logstream(LOG_INFO) << mytimer.current_time() << ") Hash map size: " << string2nodeid.size() << " at time: " << mytime.current_time() << " edges: " << total_lines << std::endl;
}
logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl <<
"total map size: " << string2nodeid.size() << endl;
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
mytimer.start();
debug = get_option_int("debug", 0);
dir = get_option_string("file_list");
lines = get_option_int("lines", 0);
omp_set_num_threads(get_option_int("ncpus", 1));
tsv = get_option_int("tsv", 0); //is this tab seperated file?
csv = get_option_int("csv", 0); // is the comma seperated file?
binary = get_option_int("binary", 0);
single_domain = get_option_int("single_domain", 0);
has_header_titles = get_option_int("has_header_titles", has_header_titles);
ignore_rest_of_line = get_option_int("ignore_rest_of_line", ignore_rest_of_line);
mytime.start();
string_to_tokenize = spaces;
if (tsv)
string_to_tokenize = tsv_spaces;
else if (csv)
string_to_tokenize = csv_spaces;
FILE * f = fopen(dir.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl;
while(true){
char buf[256];
int rc = fscanf(f, "%s\n", buf);
if (rc < 1)
break;
in_files.push_back(buf);
}
if (in_files.size() == 0)
logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl;
#pragma omp parallel for
for (uint i=0; i< in_files.size(); i++)
parse(i);
std::cout << "Finished in " << mytime.current_time() << std::endl;
M = string2nodeid.size();
if (single_domain)
N = M;
else N = string2nodeid2.size();
save_map_to_text_file(string2nodeid, outdir + dir + "user.map.text");
if (!single_domain){
save_map_to_text_file(string2nodeid2, outdir + dir + "movie.map.text");
}
logstream(LOG_INFO)<<"Writing matrix market header into file: matrix_market.info" << std::endl;
out_file fout("matrix_market.info");
MM_typecode out_typecode;
mm_clear_typecode(&out_typecode);
mm_set_integer(&out_typecode);
mm_set_sparse(&out_typecode);
mm_set_matrix(&out_typecode);
mm_write_banner(fout.outf, out_typecode);
mm_write_mtx_crd_size(fout.outf, M, N, nnz);
return 0;
}
| 09jijiangwen-download | toolkits/parsers/consecutive_matrix_market.cpp | C++ | asf20 | 7,469 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
*
*/
#include <cstdio>
#include <map>
#include <iostream>
#include <map>
#include <omp.h>
#include <assert.h>
#include <algorithm>
#include "graphchi_basic_includes.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/util.hpp"
using namespace std;
using namespace graphchi;
bool debug = false;
map<string,uint> string2nodeid;
map<uint,string> nodeid2hash;
map<uint,uint> tweets_per_user;
uint conseq_id;
mutex mymutex;
timer mytime;
size_t lines = 0, links_found = 0, http_links = 0, missing_names = 0, retweet_found = 0, wide_tweets = 0;
unsigned long long total_lines = 0;
string dir;
string outdir;
std::vector<std::string> in_files;
const char user_chars_tokens[] = {" \r\n\t,.\"!?#%^&*()|-\'+$/:"};
uint maxfrom = 0;
uint maxto = 0;
void save_map_to_text_file(const std::map<std::string,uint> & map, const std::string filename){
std::map<std::string,uint>::const_iterator it;
out_file fout(filename);
unsigned int total = 0;
for (it = map.begin(); it != map.end(); it++){
fprintf(fout.outf, "%s %u\n", it->first.c_str(), it->second);
total++;
}
logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl;
}
void save_map_to_text_file(const std::map<uint,std::string> & map, const std::string filename){
std::map<uint,std::string>::const_iterator it;
out_file fout(filename);
unsigned int total = 0;
for (it = map.begin(); it != map.end(); it++){
fprintf(fout.outf, "%u %s\n", it->first, it->second.c_str());
total++;
}
logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl;
}
void save_map_to_text_file(const std::map<uint,uint> & map, const std::string filename){
std::map<uint,uint>::const_iterator it;
out_file fout(filename);
unsigned int total = 0;
for (it = map.begin(); it != map.end(); it++){
fprintf(fout.outf, "%u %u\n", it->first, it->second);
total++;
}
logstream(LOG_INFO)<<"Wrote a total of " << total << " map entries to text file: " << filename << std::endl;
}
/*
* If this is a legal user name, assign an integer id to this user name
*
* What Characters Are Allowed in Twitter Usernames
*
* Taken from: http://kagan.mactane.org/blog/2009/09/22/what-characters-are-allowed-in-twitter-usernames/
*
* A while back, when I was writing Hummingbird, I needed to look for Twitter usernames in various strings. More recently, I’m doing some work that involves Twitter at my new job. Once again, I need to find and match on Twitter usernames.
*
* Luckily, this time, Twitter seems to have updated its signup page with some nice AJAX that constrains the user’s options, and provides helpful feedback. So, for anyone else who needs this information in the future, here’s the scoop:
*
* Letters, numbers, and underscores only. It’s case-blind, so you can enter hi_there, Hi_There, or HI_THERE and they’ll all work the same (and be treated as a single account).
* There is apparently no minimum-length requirement; the user a exists on Twitter. Maximum length is 15 characters.
* There is also no requirement that the name contain letters at all; the user 69 exists, as does a user whose name I can’t pronounce
*/
bool assign_id(uint & outval, string name, const int line, const string &filename){
if (name.size() == 0 || strstr(name.c_str(), "/") || strstr(name.c_str(), ":") || name.size() > 15)
return false;
for (uint i=0; i< name.size(); i++)
name[i] = tolower(name[i]);
const char shtrudel[]= {"@"};
name.erase (std::remove(name.begin(), name.end(), shtrudel[0]), name.end());
map<string,uint>::iterator it = string2nodeid.find(name);
if (it != string2nodeid.end()){
outval = it->second;
return true;
}
mymutex.lock();
outval = string2nodeid[name];
if (outval == 0){
string2nodeid[name] = ++conseq_id;
outval = conseq_id;
nodeid2hash[outval] = name;
}
mymutex.unlock();
return true;
}
/*
* U http://twitter.com/xlamp
*/
bool extract_user_name(const char * linebuf, size_t line, int i, char * saveptr, char * userid){
char *pch = strtok_r(NULL, user_chars_tokens,&saveptr); //HTTP
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
pch = strtok_r(NULL,user_chars_tokens,&saveptr); //TWITTER
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
pch = strtok_r(NULL,user_chars_tokens,&saveptr); //COM
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
pch = strtok_r(NULL,user_chars_tokens,&saveptr); //USERNAME
if (!pch){ logstream(LOG_WARNING) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; missing_names++; return false; }
for (uint j=0; j< strlen(pch); j++) pch[j] = tolower(pch[j]); //make user name lower
strncpy(userid, pch, 256);
return true;
}
bool convert_string_to_time(const char * linebuf, size_t line, int i, char * saveptr, long int & outtime){
struct tm ptm;
char *year = strtok_r(NULL," \r\n\t:/-",&saveptr);
if (!year){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_year = atoi(year) - 1900;
char *month = strtok_r(NULL," \r\n\t:/-",&saveptr);
if (!month){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_mon = atoi(month) - 1;
char *day = strtok_r(NULL," \r\n\t:/-",&saveptr);
if (!day){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_mday = atoi(day);
char *hour = strtok_r(NULL," \r\n\t:/-",&saveptr);
if (!hour){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_hour = atoi(hour);
char *minute = strtok_r(NULL," \r\n\t:/-",&saveptr);
if (!minute){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_min = atoi(minute);
char *second = strtok_r(NULL," \r\n\t:/-",&saveptr);
if (!second){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_sec = atoi(second);
outtime = mktime(&ptm);
return true;
}
bool parse_links(const char * linebuf, size_t line, int i, char * saveptr, uint id, long int ptime, FILE * f){
uint otherid = 0;
if (strstr(linebuf, "http://"))
http_links++;
bool found = false;
char * pch = NULL;
do {
pch = strtok_r(NULL, user_chars_tokens, &saveptr);
if (!pch || strlen(pch) == 0)
return found;
if (pch[0] == '@'){
bool ok = assign_id(otherid, pch+1, line, linebuf);
if (ok){
fprintf(f, "%u %u %ld 1\n", id, otherid, ptime);
maxfrom = std::max(maxfrom, id);
maxto = std::max(maxto, otherid);
links_found++;
found = true;
}
if (debug && line < 20)
printf("found link between : %u %u in time %ld\n", id, otherid, ptime);
}
else if (!strncmp(pch, "RT", 2)){
pch = strtok_r(NULL, user_chars_tokens, &saveptr);
if (!pch || strlen(pch) == 0)
continue;
bool ok = assign_id(otherid, pch, line, linebuf);
if (ok){
fprintf(f, "%u %u %ld 2\n", id, otherid, ptime);
retweet_found++;
found = true;
}
}
} while (pch != NULL);
return found;
}
/*
* Twitter input format is:
*
* T 2009-06-11 16:56:42
* U http://twitter.com/tiffnic85
* W Bus is pulling out now. We gotta be in LA by 8 to check into the Paragon.
*
* T 2009-06-11 16:56:42
* U http://twitter.com/xlamp
* W 灰を灰皿に落とそうとすると高確率でヘッドセットの線を根性焼きする形になるんだが
*
* T 2009-06-11 16:56:43
* U http://twitter.com/danilaselva
* W @carolinesweatt There are no orphans...of God! :) Miss your face!
*
*/
void parse(int i){
in_file fin(in_files[i]);
out_file fout((outdir + in_files[i] + ".out"));
size_t linesize = 0;
char * saveptr = NULL, * linebuf = NULL, buf1[256], linebuf_debug[1024];
size_t line = 1;
uint id;
long int ptime;
bool ok;
bool first = true;
while(true){
int rc = getline(&linebuf, &linesize, fin.outf);
strncpy(linebuf_debug, linebuf, 1024);
total_lines++;
if (rc < 1)
break;
if (strlen(linebuf) <= 1) //skip empty lines
continue;
if (first){ first = false; continue; } //skip first line
char *pch = strtok_r(linebuf," \r\n\t:/-", &saveptr);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
switch(*pch){
case 'T':
ok = convert_string_to_time(linebuf_debug, total_lines, i, saveptr, ptime);
if (!ok)
return;
break;
case 'U':
ok = extract_user_name(linebuf_debug, total_lines, i, saveptr, buf1);
if (ok)
assign_id(id, buf1, line, in_files[i]);
tweets_per_user[id]++;
break;
case 'W':
ok = parse_links(linebuf_debug, total_lines, i, saveptr, id, ptime, fout.outf);
if (debug && line < 20)
printf("Found user: %s id %u time %ld\n", buf1, id, ptime);
if (!ok)
wide_tweets++;
break;
default:
logstream(LOG_ERROR)<<"Error: expecting with T U or W first character" << std::endl;
return;
}
line++;
if (lines && line>=lines)
break;
if (debug && (line % 50000 == 0))
logstream(LOG_INFO) << "Parsed line: " << line << " map size is: " << string2nodeid.size() << std::endl;
if (string2nodeid.size() % 500000 == 0)
logstream(LOG_INFO) << "Hash map size: " << string2nodeid.size() << " at time: " << mytime.current_time() << " edges: " << total_lines << std::endl;
}
logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl <<
"total map size: " << string2nodeid.size() << endl;
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
debug = get_option_int("debug", 0);
dir = get_option_string("file_list");
lines = get_option_int("lines", 0);
omp_set_num_threads(get_option_int("ncpus", 1));
mytime.start();
FILE * f = fopen(dir.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl;
while(true){
char buf[256];
int rc = fscanf(f, "%s\n", buf);
if (rc < 1)
break;
in_files.push_back(buf);
}
if (in_files.size() == 0)
logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl;
#pragma omp parallel for
for (uint i=0; i< in_files.size(); i++)
parse(i);
std::cout << "Finished in " << mytime.current_time() << std::endl << "\t direct tweets found: " << links_found <<
" \t global tweets: " << wide_tweets <<
"\t http links: " << http_links <<
"\t retweets: " << retweet_found <<
"\t total lines in input file : " << total_lines <<
" \t invalid records (missing names) " << missing_names << std::endl;
save_map_to_text_file(string2nodeid, outdir + "map.text");
save_map_to_text_file(nodeid2hash, outdir + "reverse.map.text");
save_map_to_text_file(tweets_per_user, outdir + "tweets_per_user.text");
out_file fout("mm.info");
fprintf(fout.outf, "%%%%MatrixMarket matrix coordinate real general\n");
fprintf(fout.outf, "%u %u %lu\n", maxfrom+1, maxto+1, links_found);
return 0;
}
| 09jijiangwen-download | toolkits/parsers/twitter.cpp | C++ | asf20 | 12,944 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
*
*/
#include <cstdio>
#include <iostream>
#include <omp.h>
#include <assert.h>
#include <algorithm>
#include "graphchi_basic_includes.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/util.hpp"
using namespace std;
using namespace graphchi;
bool debug = false;
timer mytime;
size_t lines = 0;
unsigned long long total_lines = 0;
string dir;
string outdir;
std::vector<std::string> in_files;
const char user_chars_tokens[] = {" \r\n\t,.\"!?#%^&*()|-\'+$/:"};
uint maxfrom = 0;
uint maxto = 0;
/* 2011-12-05 00:00:00 */
bool convert_string_to_time(char * linebuf, size_t line, int i, long int & outtime){
char * saveptr = NULL;
struct tm ptm;
memset(&ptm, 0, sizeof(ptm));
char *year = strtok_r(linebuf," \r\n\t:/-",&saveptr);
if (!year){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_year = atoi(year) - 1900;
char *month = strtok_r(NULL," \r\n\t:/-",&saveptr);
if (!month){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_mon = atoi(month) - 1;
char *day = strtok_r(NULL," \r\n\t:/-",&saveptr);
if (!day){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_mday = atoi(day);
char *hour = strtok_r(NULL," \r\n\t:/-",&saveptr);
if (!hour){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_hour = atoi(hour);
char *minute = strtok_r(NULL," \r\n\t:/-",&saveptr);
if (!minute){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_min = atoi(minute);
char *second = strtok_r(NULL," \r\n\t:/-",&saveptr);
if (!second){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return false; }
ptm.tm_sec = atoi(second);
outtime = mktime(&ptm);
return true;
}
/*
* The CDR line format is:
*
*
* 2011-12-05 00:00:00 15 15 9 591
* 2011-12-05 00:00:00 15 22 1 39
* 2011-12-05 00:00:00 15 134 1 482
* 2011-12-05 00:00:00 15 180 2 1686
* 2011-12-05 00:00:00 15 355 1 119
* 2011-12-05 00:00:00 15 815 1 63
*/
void parse(int i){
in_file fin(in_files[i]);
out_file fout((outdir + in_files[i] + ".out"));
size_t linesize = 0;
char * saveptr2 = NULL, * linebuf = NULL, linebuf_debug[1024];
size_t line = 1;
uint from, to, duration1, duration2;
long int ptime;
while(true){
int rc = getline(&linebuf, &linesize, fin.outf);
strncpy(linebuf_debug, linebuf, 1024);
total_lines++;
if (rc < 1)
break;
bool ok = convert_string_to_time(linebuf_debug, total_lines, i, ptime);
if (!ok)
return;
char *pch = strtok_r(linebuf,"\t", &saveptr2); //skip the date
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
pch = strtok_r(NULL," \r\n\t:/-", &saveptr2);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
from = atoi(pch);
maxfrom = std::max(from, maxfrom);
pch = strtok_r(NULL," \r\n\t:/-", &saveptr2);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
to = atoi(pch);
maxto = std::max(to, maxto);
pch = strtok_r(NULL," \r\n\t:/-", &saveptr2);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
duration1 = atoi(pch);
pch = strtok_r(NULL," \r\n\t:/-", &saveptr2);
if (!pch){ logstream(LOG_ERROR) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl; return; }
duration2 = atoi(pch);
line++;
if (lines && line>=lines)
break;
if (debug && (line % 100000 == 0))
logstream(LOG_INFO)<<"Parsed line: " << line << endl;
fprintf(fout.outf, "%u %u %lu %u\n", from, to, ptime, duration2);
}
logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl;
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
debug = get_option_int("debug", 0);
dir = get_option_string("file_list");
lines = get_option_int("lines", 0);
omp_set_num_threads(get_option_int("ncpus", 1));
mytime.start();
FILE * f = fopen(dir.c_str(), "r");
if (f == NULL)
logstream(LOG_FATAL)<<"Failed to open file list!"<<std::endl;
while(true){
char buf[256];
int rc = fscanf(f, "%s\n", buf);
if (rc < 1)
break;
in_files.push_back(buf);
}
if (in_files.size() == 0)
logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl;
//#pragma omp parallel for
for (uint i=0; i< in_files.size(); i++)
parse(i);
std::cout << "Finished in " << mytime.current_time() << std::endl <<
"\t total lines in input file : " << total_lines << "\t max from: " << maxfrom << "\t max to: " <<maxto << std::endl;
return 0;
}
| 09jijiangwen-download | toolkits/parsers/cdr.cpp | C++ | asf20 | 6,470 |
/**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Written by Danny Bickson, CMU
*
* This program takes a file in the following graph format format:
* 1 61 0.9
* 1 8 0.6
* 2 1 1.2
* 2 2 0.9
* 2 3 0.4
* 2 18 0.13
* 2 21 0.11
*
* Namely, a text file where the first field is a "from" field (uint >=1), second field is a "to" field (uint > = 1)
* and a numeric value. Note that the file is assumed to be sorted by the "from" field and then the "val" field.
*`
* The output file is top K values for each entries (or less if there where fewer in the input file)
* In the abive example, assuming K = 2 the ouput will be:
* 1 61 8
* 2 1 2
* Namely, in each line the first is the "from" frield and the rest are the "to" top fields.
*
* A second output is
* 1 0.9 0.6
* 2 1.2 0.9
* */
#include <cstdio>
#include <map>
#include <iostream>
#include <map>
#include <omp.h>
#include <assert.h>
#include "graphchi_basic_includes.hpp"
#include "../collaborative_filtering/timer.hpp"
#include "../collaborative_filtering/util.hpp"
#include "../collaborative_filtering/eigen_wrapper.hpp"
using namespace std;
using namespace graphchi;
bool debug = false;
timer mytime;
size_t lines;
unsigned long long total_lines = 0;
string dir;
string outdir;
std::vector<std::string> in_files;
int col = 3;
int K = 10;
int has_value = 1;
//non word tokens that will be removed in the parsing
//it is possible to add additional special characters or remove ones you want to keep
const char spaces[] = {" \r\n\t;:"};
void dump_entry(uint from, vec & to_vec, vec & vals_vec, int pos, FILE * out_ids, FILE * out_vals){
assert(pos <= K);
fprintf(out_ids, "%u ", from);
if (has_value)
fprintf(out_vals, "%u ", from);
for (int i=0; i< pos; i++){
fprintf(out_ids, "%u ", (uint)to_vec[i]);
if (has_value)
fprintf(out_vals, "%12.6g ", vals_vec[i]);
}
fprintf(out_ids, "\n");
if (has_value)
fprintf(out_vals, "\n");
}
void parse(int i){
in_file fin(in_files[i]);
out_file ids_out((outdir + in_files[i] + ".ids"));
out_file val_out((outdir + in_files[i] + ".vals"));
vec to_vec = zeros(K);
vec val_vec = zeros(K);
int pos = 0;
size_t linesize = 0;
char * saveptr = NULL, * linebuf = NULL;
size_t line = 1;
uint from = 0, to = 0;
uint last_from = 0;
while(true){
int rc = getline(&linebuf, &linesize, fin.outf);
if (rc < 1)
break;
//char * line_to_free = linebuf;
//find from
char *pch = strtok_r(linebuf, spaces, &saveptr);
if (!pch || atoi(pch)<= 0)
logstream(LOG_FATAL) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl;
from = atoi(pch);
//find to
pch = strtok_r(NULL, spaces ,&saveptr);
if (!pch || atoi(pch)<=0)
logstream(LOG_FATAL) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl;
to = atoi(pch);
//find val
if (has_value){
pch = strtok_r(NULL, spaces ,&saveptr);
if (!pch)
logstream(LOG_FATAL) << "Error when parsing file: " << in_files[i] << ":" << line << "[" << linebuf << "]" << std::endl;
}
if (from != last_from){
// fprintf(fout.outf, "%u %u %g\n", last_from, last_to, total);
if (last_from != 0){
dump_entry(last_from, to_vec, val_vec, pos, ids_out.outf, val_out.outf);
pos = 0;
}
}
if (pos>= K)
continue;
val_vec[pos] = has_value?atof(pch):1.0;
to_vec[pos] = to;
pos++;
//free(line_to_free);
last_from = from;
total_lines++;
line++;
if (lines && line>=lines)
break;
if (debug && (line % 50000 == 0))
logstream(LOG_INFO) << "Parsed line: " << line << std::endl;
}
if (last_from != 0)
dump_entry(last_from, to_vec, val_vec, pos, ids_out.outf, val_out.outf);
logstream(LOG_INFO) <<"Finished parsing total of " << line << " lines in file " << in_files[i] << endl;
}
int main(int argc, const char *argv[]) {
logstream(LOG_WARNING)<<"GraphChi parsers library is written by Danny Bickson (c). Send any "
" comments or bug reports to danny.bickson@gmail.com " << std::endl;
global_logger().set_log_level(LOG_INFO);
global_logger().set_log_to_console(true);
graphchi_init(argc, argv);
debug = get_option_int("debug", 0);
lines = get_option_int("lines", 0);
has_value = get_option_int("has_value", has_value);
K = get_option_int("K", K);
if (K < 1)
logstream(LOG_FATAL)<<"Number of top elements (--K=) should be >= 1"<<std::endl;
omp_set_num_threads(get_option_int("ncpus", 1));
mytime.start();
std::string training = get_option_string("training");
in_files.push_back(training);
if (in_files.size() == 0)
logstream(LOG_FATAL)<<"Failed to read any file names from the list file: " << dir << std::endl;
parse(0);
std::cout << "Finished in " << mytime.current_time() << std::endl;
return 0;
}
| 09jijiangwen-download | toolkits/parsers/topk.cpp | C++ | asf20 | 5,564 |
# -*- coding:utf-8 -*-
import datetime
import time
import math
import coord
import tornado.ioloop
def handle_bus_message(msg):
bus_data = parse_message(msg)
handle_bus_data(bus_data)
buses = {}
buses_state = {}
def handle_bus_data(bus_data):
name = bus_data["Name"]
if bus_data.name not in buses:
bus = {"Name":name, "Stop":False, "Fly":False}
buses[bus_data.name] = bus
state = {}
buses_state[name] = state
else:
bus = buses[name]
state = buses_state[name]
if "Time" in bus and bus["Time"]>=bus_data["Time"]:
return
bus["Stop"] = False
bus["Fly"] = False
bus["Longitude"] = bus_data["Longitude"]
bus["Latitude"] = bus_data["Latitude"]
station_index, percent, distance, coord_index = get_closest(bus["Latitude"], bus["Longitude"])
if distance > 0.5:
bus["Fly"] = True
# log here
return
if index==0:
bus["StationIndex"] = 1
bus["Station"] = IndexToStation[1]
else:
bus["StationIndex"] = index
bus["Station"] = IndexToStation[index]
if "coord_index" in state:
if state["coord_index"] > coord_index:
bus["Direction"] = True
elif: state["coord_index"] < coord_index:
bus["Direction"] = False
if index==1 and percent<0 or index==0:
percent = 0
if bus["Direction"] = True:
percent *= -1
bus["Pencent"] = percent
if index==0:
bus["Stop"] = True
else:
bus["Time"] = bus_data["Time"]
state["coord_index"] = coord_index
def _timeout():
bus["Stop"] = True
if "timeout" in state and state["timeout"] is not None:
tornado.ioloop.IOLoop.instance().remove_timeout(state["timeout"])
state["timeout"] = None
state["timeout"] = tornado.ioloop.IOLoop.instance().add_timeout(time.time()+5*60, _timeout)
def parse_message(msg):
if msg is None or len(msg)==0:
return
fields = msg.split(',')
if len(fields) < 11:
return
name = fields[0].strip()
latitude = dm2d(float(fields[4]))
longitude = dm2d(float(fields[6]))
_date = fields[10]
_time = fields[2]
timestamp = time.mktime(time.strptime(' '.join((_date, _time)), "%d%m%y %H%M%S"))
return {"Name": name, "Latitude": latitude, "Longitude": longitude, "Time", timestamp}
# 计算地球两经纬度间距离
def calc_distance(lat1, lgt1, lat2, lgt2):
lat1, lgt1, lat2, lgt2 = d2r(lat1), d2r(lgt1), d2r(lat2), d2r(lgt2)
dlat = lat2 - lat1
dlgt = lgt2 - lgt1
distance = 2 * math.asin(math.sqrt(math.Sin(dlat/2) ** 2 +
math.cos(lat1)*math.cos(lat2)*(math.Sin(dlgt/2)**2))) * 6378.137
# 角分换算为角度
def dm2d(dm):
return int(dm/100) + (dm%100)/60
# 角度换算为弧度
def d2r(d):
return d / 360 * 2 * math.pi
# 获取离坐标最近的 coord
def get_closest(lat, lgt):
shortest = float("inf")
for i, coord in enumerate(data.Coords):
distance = calc_distance(lat, lgt, coord.Latitude, coord.Longitude)
if distance < shortest:
shortest = distance
station_index = coord_station_index(coord)
percent = coord_percent(coord)
coord_index = i
return station_index, percent, distance, coord_index
| 100steps-bbt | server/busmanager.py | Python | bsd | 3,403 |
# -*- coding:utf-8 -*-
import socket
import functools
import tornado.ioloop
import busmanager
import config
_socket = None
_ioloop = tornado.ioloop.IOLoop.instance()
def start():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setblocking(0)
sock.bind(("127.0.0.1", config.UDP_PORT))
global _socket
_socket = sock
_ioloop.add_handler(_socket.fileno(), _read_callback, _ioloop.READ)
def _read_callback(fd, events):
b, _ = _socket.recvfrom(1024)
busmanager.handle_bus_message(b)
if __name__=="__main__":
start()
tornado.ioloop.IOLoop.instance().start()
| 100steps-bbt | server/udpserver.py | Python | bsd | 700 |
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
| 100steps-bbt | server/main.py | Python | bsd | 314 |
# -*- coding:utf-8 -*-
Coords = [
(23.152793, 113.342832, 0.33, 0),
(23.152792, 113.342624, -0.33, 1),
(23.152790, 113.342417, 0.00, 1),
(23.153019, 113.342402, 0.17, 1),
(23.153249, 113.342386, 0.33, 1),
(23.153478, 113.342371, 0.50, 1),
(23.153707, 113.342356, -0.33, 2),
(23.153937, 113.342340, -0.17, 2),
(23.154166, 113.342325, 0.00, 2),
(23.154163, 113.342050, 0.15, 2),
(23.154161, 113.341776, 0.31, 2),
(23.154159, 113.341501, 0.46, 2),
(23.154156, 113.341226, -0.38, 3),
(23.154363, 113.341200, -0.25, 3),
(23.154571, 113.341174, -0.13, 3),
(23.154778, 113.341148, 0.00, 3),
(23.155019, 113.341134, 0.11, 3),
(23.155259, 113.341120, 0.22, 3),
(23.155500, 113.341105, 0.33, 3),
(23.155740, 113.341091, 0.44, 3),
(23.155981, 113.341077, -0.44, 4),
(23.156221, 113.341063, -0.33, 4),
(23.156462, 113.341048, -0.22, 4),
(23.156702, 113.341034, -0.11, 4),
(23.156943, 113.341020, 0.00, 4),
(23.156935, 113.340790, 0.15, 4),
(23.156926, 113.340560, 0.30, 4),
(23.156918, 113.340330, 0.44, 4),
(23.157180, 113.340290, -0.37, 5),
(23.157443, 113.340250, -0.19, 5),
(23.157705, 113.340210, 0.00, 5),
(23.157719, 113.339932, 0.07, 5),
(23.157734, 113.339655, 0.15, 5),
(23.157748, 113.339377, 0.22, 5),
(23.157762, 113.339099, 0.29, 5),
(23.157777, 113.338822, 0.37, 5),
(23.157791, 113.338544, 0.44, 5),
(23.157719, 113.338271, -0.49, 6),
(23.157646, 113.337998, -0.41, 6),
(23.157574, 113.337725, -0.34, 6),
(23.157501, 113.337452, -0.26, 6),
(23.157429, 113.337179, -0.19, 6),
(23.157615, 113.337056, -0.12, 6),
(23.157800, 113.336934, -0.06, 6),
(23.157986, 113.336811, 0.00, 6),
(23.158173, 113.336675, 0.33, 6),
(23.158359, 113.336539, -0.33, 7),
(23.158546, 113.336403, 0.00, 7),
(23.158757, 113.336492, 0.04, 7),
(23.158967, 113.336580, 0.08, 7),
(23.159177, 113.336669, 0.13, 7),
(23.159388, 113.336757, 0.17, 7),
(23.159599, 113.336845, 0.21, 7),
(23.159809, 113.336934, 0.25, 7),
(23.160039, 113.337005, 0.30, 7),
(23.160269, 113.337076, 0.34, 7),
(23.160498, 113.337146, 0.38, 7),
(23.160728, 113.337217, 0.43, 7),
(23.160958, 113.337288, 0.47, 7),
(23.161169, 113.337466, -0.48, 8),
(23.161379, 113.337644, -0.43, 8),
(23.161590, 113.337822, -0.38, 8),
(23.161801, 113.337999, -0.33, 8),
(23.162012, 113.338177, -0.28, 8),
(23.162222, 113.338355, -0.23, 8),
(23.162433, 113.338533, -0.18, 8),
(23.162673, 113.338513, -0.13, 8),
(23.162914, 113.338493, -0.09, 8),
(23.163154, 113.338472, -0.04, 8),
(23.163394, 113.338452, 0.00, 8),
(23.163616, 113.338411, 0.12, 8),
(23.163838, 113.338370, 0.24, 8),
(23.164060, 113.338330, 0.36, 8),
(23.164282, 113.338289, 0.48, 8),
(23.164504, 113.338248, -0.40, 9),
(23.164747, 113.338293, -0.26, 9),
(23.164991, 113.338338, -0.13, 9),
(23.165234, 113.338383, 0.00, 9),
(23.165499, 113.338369, 0.11, 9),
(23.165763, 113.338354, 0.23, 9),
(23.166028, 113.338340, 0.34, 9),
(23.165860, 113.338372, 0.42, 9),
(23.166051, 113.338299, -0.50, 10),
(23.166241, 113.338225, -0.41, 10),
(23.166432, 113.338152, -0.32, 10),
(23.166626, 113.337982, -0.21, 10),
(23.166820, 113.337812, -0.11, 10),
(23.167014, 113.337642, 0.00, 10),
(23.167071, 113.337389, 0.17, 10),
(23.167128, 113.337136, 0.33, 10),
(23.167185, 113.336883, 0.50, 10),
(23.167241, 113.336630, -0.33, 11),
(23.167298, 113.336377, -0.17, 11),
(23.167355, 113.336124, 0.00, 11),
(23.167481, 113.335938, 0.09, 11),
(23.167608, 113.335752, 0.19, 11),
(23.167734, 113.335566, 0.28, 11),
(23.167814, 113.335361, 0.37, 11),
(23.167894, 113.335156, 0.46, 11),
(23.167975, 113.334951, -0.45, 12),
(23.168055, 113.334746, -0.37, 12),
(23.168211, 113.334593, -0.27, 12),
(23.168368, 113.334440, -0.18, 12),
(23.168525, 113.334287, -0.09, 12),
(23.168681, 113.334134, 0.00, 12),
]
def coord_latitude(coord):
return coord[0]
def coord_longitude(coord):
return coord[1]
def coord_percent(coord):
return coord[2]
def coord_station_index(coord);
return coord[3]
IndexToStation = [
"车场",
"南门总站",
"中山像站",
"百步梯站",
"27号楼站",
"人文馆站",
"西五站",
"西秀村站",
"修理厂站",
"北门站",
"北湖站",
"卫生所站",
"北二总站",
]
| 100steps-bbt | server/coord.py | Python | bsd | 4,212 |
# -*- coding:utf-8 -*-
UDP_PORT = 6000 # 校巴终端上传数据端口
HTTP_PORT = 8001 # HTTP接口端口
| 100steps-bbt | server/config.py | Python | bsd | 110 |
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:b3mn="http://b3mn.org/2007/b3mn"
xmlns:ext="http://b3mn.org/2007/ext"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:atom="http://b3mn.org/2007/atom+xhtml">
<head profile="http://purl.org/NET/erdf/profile">
<title>Oryx</title>
<!-- libraries -->
<script src="../oryx/editor/libs.js" type="text/javascript"></script>
<!-- compresed oryx files -->
<script src="../oryx/editor/oryx.core.js" type="text/javascript" charset="utf-8"></script>
<!-- for profile file see function loadJavaScriptForProfile below-->
<style media="screen" type="text/css">
@import url("../oryx/editor/lib/ext-2.0.2/resources/css/ext-all.css");
@import url("../oryx/editor/lib/ext-2.0.2/resources/css/xtheme-gray.css");
@import url("../oryx/editor/lib/jquery-ui-1.8.1.custom/css/ui-lightness/jquery-ui-1.8.1.custom.css");
</style>
<!-- oryx editor -->
<link rel="Stylesheet" media="screen" href="../../oryx/editor/css/theme_norm.css" type="text/css" />
</head>
<body style="display: block; overflow: hidden;">
<script type="text/javascript">
<![CDATA[
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11641680-2']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
]]>
</script>
<script type='text/javascript'>
<![CDATA[
var ed;
var stencilSetName = _getStencilSetName();
loadJavaScriptForProfile();
function loadJavaScriptForProfile() {
var scriptTag = document.createElement('script');
scriptTag.setAttribute("type","text/javascript");
scriptTag.setAttribute("src", '../oryx/editor/profiles/' + stencilSetName + '.js');
scriptTag.setAttribute("charset", "utf-8");
document.getElementsByTagName("head")[0].appendChild(scriptTag);
}
function onOryxResourcesLoaded(){
ed = new ORYX.Editor({
'id': 'oryx-canvas',
'stencilset': {
'url': ORYX.CONFIG.ROOT_PATH + 'editor/stencilsets/' + stencilSetName + '/' + stencilSetName + '.json'
}
});
}
function _getStencilSetName() {
if (stencilSetName) {
return stencilSetName;
}
stencilSetName = "bpmn2.0";
var urlquery = location.href.split("?");
if (urlquery[1]) {
var urlterms = urlquery[1].split(",");
for (var i = 0; i < urlterms.length; i++) {
if (urlterms[i].indexOf("stencilSetName=") == 0) {
stencilSetName = urlterms[i].slice("stencilSetName=".length);
break;
}
}
}
return stencilSetName;
}
]]>
</script>
</body>
</html>
| 08to09-processwave | gadget/oryx_stable.xhtml | HTML | mit | 3,577 |
/**
* 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"
]; | 08to09-processwave | gadget/includes.js | JavaScript | mit | 1,845 |
/**
* 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);
}
}
}; | 08to09-processwave | gadget/stencilsetPolice.js | JavaScript | mit | 2,077 |
/**
* 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;
} | 08to09-processwave | gadget/static/console.js | JavaScript | mit | 2,974 |
/**
* 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}; | 08to09-processwave | gadget/static/splash.js | JavaScript | mit | 8,923 |
/**
* 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); | 08to09-processwave | gadget/static/splash_stable.js | JavaScript | mit | 6,210 |
/**
* 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);
}
}
} | 08to09-processwave | gadget/farbrausch.js | JavaScript | mit | 4,536 |
/**
* 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");
}
}
} | 08to09-processwave | gadget/oryx.js | JavaScript | mit | 4,387 |
<!-- ATTENTION ! If you change the included JavaScript files here make sure to also change the build.xml and profile.xml accordingly!-->
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:b3mn="http://b3mn.org/2007/b3mn"
xmlns:ext="http://b3mn.org/2007/ext"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:atom="http://b3mn.org/2007/atom+xhtml">
<head profile="http://purl.org/NET/erdf/profile">
<title>Oryx</title>
<!-- define console if undefined -->
<script src="static/console.js" type="text/javascript" charset="utf-8"></script>
<!-- libraries -->
<script src="../oryx/editor/lib/prototype-1.5.1.js" type="text/javascript"></script>
<script src="../oryx/editor/lib/path_parser.js" type="text/javascript"></script>
<script src="../oryx/editor/lib/ext-2.0.2/adapter/ext/ext-base.js" type="text/javascript"></script>
<script src="../oryx/editor/lib/ext-2.0.2/ext-all.js" type="text/javascript"></script>
<script src="../oryx/editor/lib/ext-2.0.2/color-field.js" type="text/javascript"></script>
<script src="../oryx/editor/lib/jquery-ui-1.8.1.custom/js/jquery-1.4.2.min.noConflict.js"></script>
<script src="../oryx/editor/lib/jquery-ui-1.8.1.custom/js/jquery-ui-1.8.1.custom.min.js"></script>
<style media="screen" type="text/css">
@import url("../oryx/editor/lib/ext-2.0.2/resources/css/ext-all.css");
@import url("../oryx/editor/lib/ext-2.0.2/resources/css/xtheme-gray.css");
@import url("../oryx/editor/lib/jquery-ui-1.8.1.custom/css/ui-lightness/jquery-ui-1.8.1.custom.css");
@import url("../oryx/editor/css/theme_norm.css");
</style>
<!-- oryx editor -->
<script src="../oryx/editor/data/i18n/translation_en_us.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/utils.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/kickstart.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/erdfparser.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/clazz.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/config.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/oryx.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/SVG/editpathhandler.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/SVG/minmaxpathhandler.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/SVG/pointspathhandler.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/SVG/svgmarker.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/SVG/svgshape.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/SVG/label.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/Math/math.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/StencilSet/stencil.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/StencilSet/property.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/StencilSet/propertyitem.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/StencilSet/complexpropertyitem.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/StencilSet/rules.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/StencilSet/stencilset.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/StencilSet/stencilsets.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/bounds.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/uiobject.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/abstractshape.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/canvas.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/main.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/svgDrag.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/shape.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/Controls/control.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/Controls/docker.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/Controls/magnet.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/node.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/edge.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/command.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/abstractPlugin.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/abstractLayouter.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Core/abstractcommand.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/sideTabs.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/addDocker.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/arrangementLight.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/canvasResize.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/dragDocker.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/dragdropresize.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/edit.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/keysMove.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/overlay.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/renameShapes.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/selectionframe.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/shapeHighlighting.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/shapemenu.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/toolbar.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/waveGlobalUndo.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/view.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/bpmn2.0.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/uml.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/wave.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/farbrausch.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/farbrausch_shadow.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/farbrausch_afterglow.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/farbrausch_legend.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/shapeTooltip.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/propertytab.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/syncro.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/syncroOryx.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/paint.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/changelog.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/newshaperepository.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/dockerCreation.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/schlaumeier.js" type="text/javascript"></script>
<script src="../oryx/editor/client/scripts/Plugins/json_export.js" type="text/javascript"></script>
</head>
<body style="display: block;">
<script type='text/javascript'>
<![CDATA[
var ed;
var stencilSetName = _getStencilSetName();
function onOryxResourcesLoaded(){
ed = new ORYX.Editor({
'id': 'oryx-canvas',
'stencilset': {
'url': ORYX.CONFIG.ROOT_PATH + 'editor/data/stencilsets/' + stencilSetName + '/' + stencilSetName + '.json'
}
});
}
function _getStencilSetName() {
if (stencilSetName) {
return stencilSetName;
}
stencilSetName = "bpmn2.0";
var urlquery = location.href.split("?");
if (urlquery[1]) {
var urlterms = urlquery[1].split(",");
for (var i = 0; i < urlterms.length; i++) {
if (urlterms[i].indexOf("stencilSetName=") == 0) {
stencilSetName = urlterms[i].slice("stencilSetName=".length);
break;
}
}
}
return stencilSetName;
}
]]>
</script>
</body>
</html>
| 08to09-processwave | gadget/oryx.xhtml | HTML | mit | 10,585 |
/**
* 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);
}
} | 08to09-processwave | gadget/adapter.js | JavaScript | mit | 12,108 |
/**
* 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));
}
}
} | 08to09-processwave | gadget/syncroWave.js | JavaScript | mit | 2,907 |
package org.oryxeditor.buildapps.sscompress;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
public class SSCompressor {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
if(args.length < 1)
throw new Exception("Missing argument! Usage: java SSCompressor <SSDirectory>");
//get stencil set directory from arguments
String ssDirString = args[0];
//get stencil set configuration file
File ssConf = new File(ssDirString + "/stencilsets.json");
if(!ssConf.exists())
throw new Exception("File " + ssDirString + "/stencilsets.json does not exist.");
//read stencil set configuration
StringBuffer jsonObjStr = readFile(ssConf);
JSONArray jsonObj = new JSONArray(jsonObjStr.toString());
//iterate all stencil set configurations
for(int i = 0; i < jsonObj.length(); i++) {
JSONObject ssObj = jsonObj.getJSONObject(i);
//get stencil set location
if(ssObj.has("uri")) {
String ssUri = ssObj.getString("uri");
File ssFile = new File(ssDirString + ssUri);
if(!ssFile.exists())
throw new Exception("Stencil set " + ssDirString + ssUri + " that is referenced in stencil set configuration file does not exist.");
String ssDir = ssFile.getParent();
//read stencil set file
StringBuffer ssString = readFile(ssFile);
// store copy of original stencilset file (w/o SVG includes) with postfix '-nosvg'
int pIdx = ssUri.lastIndexOf('.');
File ssNoSvgFile = new File(ssDirString + ssUri.substring(0, pIdx) + "-nosvg" + ssUri.substring(pIdx));
writeFile(ssNoSvgFile, ssString.toString());
//***include svg files***
//get view property
Pattern pattern = Pattern.compile("[\"\']view[\"\']\\s*:\\s*[\"\']\\S+[\"\']");
Matcher matcher = pattern.matcher(ssString);
StringBuffer tempSS = new StringBuffer();
int lastIndex = 0;
//iterate all view properties
while(matcher.find()) {
tempSS.append(ssString.substring(lastIndex, matcher.start()));
lastIndex = matcher.end();
//get svg file name
String filename = matcher.group().replaceFirst("[\"\']view[\"\']\\s*:\\s*[\"\']", "");
filename = filename.substring(0, filename.length()-1);
//get svg file
File svgFile = new File(ssDir + "/view/" + filename);
if(!svgFile.exists())
throw new Exception("SVG File " + svgFile.getPath() + " does not exists!. Compressing stencil sets aborted!");
StringBuffer svgString = readFile(svgFile);
//check, if svgString is a valid xml file
/*try {
DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
DocumentBuilder document = builder.newDocumentBuilder();
document.parse(svgString.toString());
} catch(Exception e) {
throw new Exception("File " + svgFile.getCanonicalPath() + " is not a valid XML file: " + e.getMessage());
}*/
//append file content to output json file (replacing existing json file)
tempSS.append("\"view\":\"");
tempSS.append(svgString.toString().replaceAll("[\\t\\n\\x0B\\f\\r]", " ").replaceAll("\"", "\\\\\""));
//newSS.append(filename);
tempSS.append("\"");
}
tempSS.append(ssString.substring(lastIndex));
//***end include svg files***
/*
* BAD IDEA, BECAUSE IT INCREASES THROUGHPUT
//***include png files
//get icon property
pattern = Pattern.compile("[\"\']icon[\"\']\\s*:\\s*[\"\']\\S+[\"\']");
matcher = pattern.matcher(tempSS);
StringBuffer finalSS = new StringBuffer();
lastIndex = 0;
//iterate all icon properties
while(matcher.find()) {
finalSS.append(tempSS.substring(lastIndex, matcher.start()));
lastIndex = matcher.end();
//get icon file name
String filename = matcher.group().replaceFirst("[\"\']icon[\"\']\\s*:\\s*[\"\']", "");
filename = filename.substring(0, filename.length()-1);
//get icon file
File pngFile = new File(ssDir + "/icons/" + filename);
if(!pngFile.exists())
throw new Exception("SVG File " + pngFile.getPath() + " does not exists!. Compressing stencil sets aborted!");
StringBuffer pngString = readFile(pngFile);
//append file content to output json file (replacing existing json file)
finalSS.append("\"icon\":\"javascript:");
finalSS.append(encodeBase64(pngString.toString()));
finalSS.append("\"");
}
finalSS.append(tempSS.substring(lastIndex));
//***end include png files
*/
//write compressed stencil set file
writeFile(ssFile, tempSS.toString());
System.out.println("Compressed stencil set file " + ssFile.getCanonicalPath());
}
}
}
private static StringBuffer readFile(File file) throws Exception {
FileInputStream fin = new FileInputStream(file);
StringBuffer result = new StringBuffer();
String thisLine = "";
BufferedReader myInput = new BufferedReader(new InputStreamReader(fin, "utf-8"));
while ((thisLine = myInput.readLine()) != null) {
result.append(thisLine);
result.append("\n");
}
myInput.close();
fin.close();
return result;
}
private static void writeFile(File file, String text) throws Exception {
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter myOutput = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
myOutput.write(text);
myOutput.flush();
myOutput.close();
fos.close();
}
/*private static String encodeBase64(String text) {
byte[] encoded = Base64.encodeBase64(text.getBytes());
return new String(encoded);
}*/
}
| 08to09-processwave | buildApps/src/org/oryxeditor/buildapps/sscompress/SSCompressor.java | Java | mit | 6,393 |
package org.oryxeditor.buildapps;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.util.FileCopyUtils;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;
/**
* @author Philipp Berger
*
*/
public class ProfileCreator {
/**
* @param args
* path to plugin dir and output dir
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
* @throws JSONException
*/
public static void main(String[] args) throws IOException,
ParserConfigurationException, SAXException, JSONException {
if (args.length != 2) {
System.err.println("Wrong Number of Arguments!");
System.err.println(usage());
return;
}
String pluginDirPath = args[0];
;
String pluginXMLPath = pluginDirPath + "/plugins.xml";// args[0];
String profilePath = pluginDirPath + "/profiles.xml";// ;
String outputPath = args[1];
File outDir = new File(outputPath);
outDir.mkdir();
HashMap<String, String> nameSrc = new HashMap<String, String>();
HashMap<String, ArrayList<String>> profilName = new HashMap<String, ArrayList<String>>();
ArrayList<String> coreNames = new ArrayList<String>();
extractPluginData(pluginXMLPath, nameSrc, coreNames);
extractProfileData(profilePath, profilName);
for (String key : profilName.keySet()) {
ArrayList<String> pluginNames = profilName.get(key);
//add core plugins to each profile
pluginNames.addAll(coreNames);
writeProfileJS(pluginDirPath, outputPath, nameSrc, key, pluginNames);
writeProfileXML(pluginXMLPath, profilePath, outputPath, key,
pluginNames);
}
}
/**
* Create the profileName.js by reading all path out of the nameSrc Hashmap, the required names
* are given
* @param pluginDirPath
* @param outputPath
* @param nameSrc
* plugin name to js source file
* @param profileName
* name of the profile, serve as name for the js file
* @param pluginNames
* all plugins for this profile
* @throws IOException
* @throws FileNotFoundException
*/
private static void writeProfileJS(String pluginDirPath, String outputPath,
HashMap<String, String> nameSrc, String profileName,
ArrayList<String> pluginNames) throws IOException,
FileNotFoundException {
HashSet<String> pluginNameSet = new HashSet<String>();
pluginNameSet.addAll(pluginNames);
File profileFile = new File(outputPath + File.separator + profileName +"Uncompressed.js");
profileFile.createNewFile();
FileWriter writer = new FileWriter(profileFile);
for (String name : pluginNameSet) {
String source = nameSrc.get(name);
if(source==null)
throw new IllegalArgumentException("In profile '"+profileName+"' an unknown plugin is referenced named '"+ name+"'");
FileReader reader = new FileReader(pluginDirPath + File.separator + source);
writer.append(FileCopyUtils.copyToString(reader));
}
writer.close();
File compressOut=new File(outputPath + File.separator + profileName +".js");
FileReader reader = new FileReader(profileFile);
FileWriter writer2 = new FileWriter(compressOut);
try{
com.yahoo.platform.yui.compressor.JavaScriptCompressor x= new JavaScriptCompressor(reader, null);
x.compress(writer2, 1, true, false, false, false);
writer2.close();
reader.close();
}catch (Exception e) {
/*
* Fallback if yui compression fails
*/
System.err.println("Profile Compression failed! profile: "+compressOut.getAbsolutePath()+ " uncompressed version is used, please ensure javascript correctness and compatibility of YUI compressor with your system");
e.printStackTrace();
writer2.close();
reader.close();
FileWriter writer3 = new FileWriter(new File(outputPath + File.separator + profileName +".js"));
FileReader reader1 = new FileReader(profileFile);
FileCopyUtils.copy(reader1, writer3);
reader1.close();
writer3.close();
}
}
/**
* @param pluginDirPath
* @param outputPath
* @param ProfileName
* name of the profile, serve as name for the js file
* @param pluginNames
* all plugins for this profile
* @throws IOException
* @throws FileNotFoundException
* @throws JSONException
*/
private static void writeProfileXML(String pluginXMLPath,
String profileXMLPath, String outputPath, String ProfileName,
ArrayList<String> pluginNames) throws IOException,
FileNotFoundException, JSONException {
FileCopyUtils.copy(new FileInputStream(pluginXMLPath),
new FileOutputStream(outputPath + File.separator + ProfileName + ".xml"));
InputStream reader = new FileInputStream(outputPath + File.separator + ProfileName
+ ".xml");
DocumentBuilder builder;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
builder = factory.newDocumentBuilder();
Document outProfileXMLdocument = builder.parse(reader);
reader = new FileInputStream(profileXMLPath);
builder = factory.newDocumentBuilder();
Document profilesXMLdocument = builder.parse(reader);
NodeList pluginNodeList = outProfileXMLdocument
.getElementsByTagName("plugin");
Node profileNode = getProfileNodeFromDocument(ProfileName,
profilesXMLdocument);
if (profileNode == null)
throw new IllegalArgumentException(
"profile not defined in profile xml");
NamedNodeMap attr = profileNode.getAttributes();
JSONObject config=new JSONObject();
for(int i=0;i<attr.getLength();i++){
config.put(attr.item(i).getNodeName(), attr.item(i).getNodeValue());
}
for (int profilePluginNodeIndex = 0; profilePluginNodeIndex < profileNode
.getChildNodes().getLength(); profilePluginNodeIndex++) {
Node tmpNode = profileNode.getChildNodes().item(profilePluginNodeIndex);
if("plugin".equals(tmpNode.getNodeName()) || tmpNode==null)
continue;
JSONObject nodeObject = new JSONObject();
NamedNodeMap attr1 = tmpNode.getAttributes();
if(attr1==null)
continue;
for(int i=0;i<attr1.getLength();i++){
nodeObject.put(attr1.item(i).getNodeName(), attr1.item(i).getNodeValue());
}
if(config.has(tmpNode.getNodeName())){
config.getJSONArray(tmpNode.getNodeName()).put(nodeObject);
}else{
config.put(tmpNode.getNodeName(), new JSONArray().put(nodeObject));
}
}
FileCopyUtils.copy(config.toString(), new FileWriter(outputPath + File.separator+ProfileName+".conf"));
// for each plugin in the copied plugin.xml
for (int i = 0; i < pluginNodeList.getLength(); i++) {
Node pluginNode = pluginNodeList.item(i);
String pluginName = pluginNode.getAttributes().getNamedItem(
"name").getNodeValue();
// if plugin is in the current profile
if (pluginNames.contains(pluginName)) {
// mark plugin as active
((Element) pluginNode).setAttribute("engaged", "true");
// throw new
// IllegalArgumentException("profile not defined in profile xml");
// plugin defintion found copy or replace properties
Node profilePluginNode = getLastPluginNode(profileNode,
pluginName);
if(profilePluginNode==null){
//System.out.println("Plugin: "+pluginName+" assumed to be core");
break;}
saveOrUpdateProperties(pluginNode, profilePluginNode);
}else{
((Element) pluginNode).setAttribute("engaged", "false");
}
}
writeXMLToFile(outProfileXMLdocument, outputPath + File.separator
+ ProfileName + ".xml");
} catch (DOMException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
private static Node getLastPluginNode(Node profileNode, String pluginName) {
Node profilePluginNode = null;
// search plugin definition in profile xml
for (int profilePluginNodeIndex = 0; profilePluginNodeIndex < profileNode
.getChildNodes().getLength(); profilePluginNodeIndex++) {
Node tmpNode = profileNode.getChildNodes().item(
profilePluginNodeIndex);
if (tmpNode.getAttributes() != null
&& tmpNode.getAttributes().getNamedItem("name") != null
&& tmpNode.getAttributes().getNamedItem("name")
.getNodeValue().equals(pluginName))
profilePluginNode = tmpNode;
}
if (profilePluginNode == null) {
String[] dependsOnProfiles = getDependencies(profileNode);
if (dependsOnProfiles==null ||dependsOnProfiles.length == 0) {
return profilePluginNode;
}
for (String dependsProfile : dependsOnProfiles) {
profilePluginNode = getLastPluginNode(
getProfileNodeFromDocument(dependsProfile, profileNode
.getOwnerDocument()), pluginName);
if (profilePluginNode != null)
break;
}
// plugin definition not found, plugin defined in depended profiles
// TODO handle recursive property search
}
;
return profilePluginNode;
};
/**
* @param outProfileXMLdocument
* @param xmlFileName
* @throws FileNotFoundException
*/
private static void writeXMLToFile(Document outProfileXMLdocument,
String xmlFileName) throws FileNotFoundException {
// ---- Use a XSLT transformer for writing the new XML file ----
try {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
DOMSource source = new DOMSource(outProfileXMLdocument);
FileOutputStream os = new FileOutputStream(new File(xmlFileName));
StreamResult result = new StreamResult(os);
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
/**
*
* @param pluginNode
* @param profilePluginNode
* @throws DOMException
*/
private static void saveOrUpdateProperties(Node pluginNode,
Node profilePluginNode) throws DOMException {
// for(String dependent:getDependencies(profilePluginNode.getParentNode())){
// saveOrUpdateProperties(pluginNode,getProfileNodeFromDocument(dependent, profilePluginNode.getOwnerDocument()));
// };
// for each child node in the profile xml
for (int index = 0; index < profilePluginNode.getChildNodes()
.getLength(); index++) {
Node profilePluginChildNode = profilePluginNode.getChildNodes()
.item(index);
// check if property
if (profilePluginChildNode.getNodeName() == "property") {
boolean found = false;
// search for old definitions
for (int childIndex = 0; childIndex < pluginNode
.getChildNodes().getLength(); childIndex++) {
Node pluginChildNode = pluginNode.getChildNodes().item(
childIndex);
if (pluginChildNode.getNodeName() == "property") {
NamedNodeMap propertyAttributes = profilePluginChildNode
.getAttributes();
for (int attrIndex = 0; attrIndex < propertyAttributes
.getLength(); attrIndex++) {
String newPropertyName = profilePluginChildNode
.getAttributes().item(attrIndex)
.getNodeName();
Node oldPropertyNode = pluginChildNode
.getAttributes().getNamedItem(
newPropertyName);
if (oldPropertyNode != null) {
// old definition found replace value
found = true;
String newValue = profilePluginChildNode
.getAttributes().item(attrIndex).getNodeValue();
oldPropertyNode.setNodeValue(newValue);
}
}
}
}
if (!found) {
// no definition found add some
Node property = pluginNode.getOwnerDocument()
.createElement("property");
((Element) property).setAttribute("name",
profilePluginChildNode.getAttributes()
.getNamedItem("name").getNodeValue());
((Element) property).setAttribute("value",
profilePluginChildNode.getAttributes()
.getNamedItem("value").getNodeValue());
pluginNode.appendChild(property);
}
}
}
}
/**
* @param ProfileName
* @param profilesXMLdocument
* @throws DOMException
*/
private static Node getProfileNodeFromDocument(String ProfileName,
Document profilesXMLdocument) throws DOMException {
Node profileNode = null;
NodeList profileNodes = profilesXMLdocument
.getElementsByTagName("profile");
for (int i = 0; i < profileNodes.getLength(); i++) {
if (profileNodes.item(i).getAttributes().getNamedItem("name")
.getNodeValue().equals(ProfileName)) {
profileNode = profileNodes.item(i);
break;
}
}
return profileNode;
}
/**
* @param profilePath
* @param profilName
* @throws FileNotFoundException
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws DOMException
*/
private static void extractProfileData(String profilePath,
HashMap<String, ArrayList<String>> profilName)
throws FileNotFoundException, ParserConfigurationException,
SAXException, IOException, DOMException {
InputStream reader = new FileInputStream(profilePath);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document document = factory.newDocumentBuilder().parse(reader);
NodeList profiles = document.getElementsByTagName("profile");
for (int i = 0; i < profiles.getLength(); i++) {
Node profile = profiles.item(i);
String name = profile.getAttributes().getNamedItem("name")
.getNodeValue();
profilName.put(name, new ArrayList<String>());
for (int q = 0; q < profile.getChildNodes().getLength(); q++) {
if (profile.getChildNodes().item(q).getNodeName()
.equalsIgnoreCase("plugin")) {
profilName.get(name).add(
profile.getChildNodes().item(q).getAttributes()
.getNamedItem("name").getNodeValue());
}
;
}
}
resolveDependencies(profilName, profiles);
}
/**
* @param profilName
* @param profiles
* @throws DOMException
*/
private static void resolveDependencies(
HashMap<String, ArrayList<String>> profilName, NodeList profiles)
throws DOMException {
HashMap<String, String[]> profileDepends = new HashMap<String, String[]>();
for (int i = 0; i < profiles.getLength(); i++) {
Node profile = profiles.item(i);
String name = profile.getAttributes().getNamedItem("name")
.getNodeValue();
profileDepends.put(name, getDependencies(profile));
}
ArrayList<String> completedProfiles = new ArrayList<String>();
for (String key : profileDepends.keySet()) {
if (profileDepends.get(key) == null) {
completedProfiles.add(key);
}
}
for (String cur : completedProfiles)
profileDepends.remove(cur);
while (!profileDepends.isEmpty()) {
for (String key : profileDepends.keySet()) {
boolean allIn = true;
for (String name : profileDepends.get(key)) {
if (!completedProfiles.contains(name)) {
allIn = false;
break;
}
}
if (allIn) {
for (String name : profileDepends.get(key)) {
profilName.get(key).addAll(profilName.get(name));
completedProfiles.add(key);
}
}
}
for (String cur : completedProfiles)
profileDepends.remove(cur);
}
}
/**
* @param profile
* DocumentNode containing a profile
* @throws DOMException
*/
private static String[] getDependencies(Node profil) throws DOMException {
String[] dependencies = null;
if (profil.getAttributes().getNamedItem("depends") != null) {
dependencies = profil.getAttributes().getNamedItem("depends")
.getNodeValue().split(",");
}
return dependencies;
}
/**
* @param pluginXMLPath
* @param nameSrc
* HashMap links Pluginnames and Sourcefiles
* @param coreNames
* ArrayList containing Names of all core plugins
* @throws FileNotFoundException
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws DOMException
*/
private static void extractPluginData(String pluginXMLPath,
HashMap<String, String> nameSrc, ArrayList<String> coreNames)
throws FileNotFoundException, ParserConfigurationException,
SAXException, IOException, DOMException {
InputStream reader = new FileInputStream(pluginXMLPath);
DocumentBuilder builder;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
Document document = builder.parse(reader);
NodeList plugins = document.getElementsByTagName("plugin");
for (int i = 0; i < plugins.getLength(); i++) {
String name = plugins.item(i).getAttributes().getNamedItem("name")
.getNodeValue();
String src = plugins.item(i).getAttributes().getNamedItem("source")
.getNodeValue();
assert (src!=null);
nameSrc.put(name, src);
if (plugins.item(i).getAttributes().getNamedItem("core") != null) {
if (plugins.item(i).getAttributes().getNamedItem("core")
.getNodeValue().equalsIgnoreCase("true")) {
coreNames.add(name);
}
}
}
}
public static String usage() {
String use = "Profiles Creator\n"
+ "Use to parse the profiles.xml and creates\n"
+ "for each profile an .js-source. Therefore additional\n"
+ "information from the plugins.xml is required.\n"
+ "usage:\n" + "java ProfileCreator pluginPath outputDir";
return use;
}
}
| 08to09-processwave | buildApps/src/org/oryxeditor/buildapps/ProfileCreator.java | Java | mit | 18,637 |
/**
* 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 + '"';
}
}; | 08to09-processwave | oryx/editor/client/scripts/erdfparser.js | JavaScript | mit | 11,711 |
/**
* 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;
}; | 08to09-processwave | oryx/editor/client/scripts/clazz.js | JavaScript | mit | 3,085 |
/**
* 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);
//} | 08to09-processwave | oryx/editor/client/scripts/kickstart.js | JavaScript | mit | 4,253 |
/**
* 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);
})
}
}
}
| 08to09-processwave | oryx/editor/client/scripts/utils.js | JavaScript | mit | 2,601 |
/**
* 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); | 08to09-processwave | oryx/editor/client/scripts/Plugins/schlaumeier.js | JavaScript | mit | 5,501 |
/**
* 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);
}
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/renameShapes.js | JavaScript | mit | 13,476 |
/**
* 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();
}
}); | 08to09-processwave | oryx/editor/client/scripts/Plugins/json_export.js | JavaScript | mit | 4,649 |
/**
* 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");
}
}); | 08to09-processwave | oryx/editor/client/scripts/Plugins/wave.js | JavaScript | mit | 5,745 |
/**
* 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);
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/edit.js | JavaScript | mit | 27,268 |
/**
* 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";
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/selectionframe.js | JavaScript | mit | 5,793 |
/**
* 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;
// }
//
// }
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/keysMove.js | JavaScript | mit | 10,518 |
/**
* 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'});
}
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/shapeHighlighting.js | JavaScript | mit | 8,536 |
/**
* 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);
| 08to09-processwave | oryx/editor/client/scripts/Plugins/uml.js | JavaScript | mit | 8,383 |
/**
* 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);
}
}
}); | 08to09-processwave | oryx/editor/client/scripts/Plugins/shapeTooltip.js | JavaScript | mit | 9,430 |
/**
* 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);
}
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/shapemenu.js | JavaScript | mit | 58,836 |
/**
* 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]);
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/addDocker.js | JavaScript | mit | 6,344 |
/**
* 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());
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/dragdropresize.js | JavaScript | mit | 80,875 |
/**
* 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);
| 08to09-processwave | oryx/editor/client/scripts/Plugins/bpmn2.0.js | JavaScript | mit | 21,988 |
/**
* 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 + ")");
}
}
}
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/farbrausch_shadow.js | JavaScript | mit | 6,375 |
/**
* 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;
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/waveGlobalUndo.js | JavaScript | mit | 12,787 |
/**
* 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);
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/canvasResize.js | JavaScript | mit | 12,954 |
/**
* 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.
**/
Array.prototype.insertFrom = function(from, to){
to = Math.max(0, to);
from = Math.min( Math.max(0, from), this.length-1 );
var el = this[from];
var old = this.without(el);
var newA = old.slice(0, to);
newA.push(el);
if(old.length > to ){
newA = newA.concat(old.slice(to))
};
return newA;
}
if(!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Plugins.ArrangementLight = Clazz.extend({
facade: undefined,
construct: function(facade) {
this.facade = facade;
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_ARRANGEMENTLIGHT_TOP, this.setZLevel.bind(this, this.setToTop) );
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_ARRANGEMENTLIGHT_BACK, this.setZLevel.bind(this, this.setToBack) );
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_ARRANGEMENTLIGHT_FORWARD, this.setZLevel.bind(this, this.setForward) );
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_ARRANGEMENTLIGHT_BACKWARD, this.setZLevel.bind(this, this.setBackward) );
},
setZLevel:function(callback, event){
//Command-Pattern for dragging one docker
var zLevelCommand = ORYX.Core.Command.extend({
construct: function(callback, elements, facade){
this.callback = callback;
this.elements = elements;
// For redo, the previous elements get stored
this.elAndIndex = elements.map(function(el){ return {el:el, previous:el.parent.children[el.parent.children.indexOf(el)-1]} })
this.facade = facade;
},
execute: function(){
// Call the defined z-order callback with the elements
this.callback( this.elements )
},
rollback: function(){
// Sort all elements on the index of there containment
var sortedEl = this.elAndIndex.sortBy( function( el ) {
var value = el.el;
var t = $A(value.node.parentNode.childNodes);
return t.indexOf(value.node);
});
// Every element get setted back bevor the old previous element
for(var i=0; i<sortedEl.length; i++){
var el = sortedEl[i].el;
var p = el.parent;
var oldIndex = p.children.indexOf(el);
var newIndex = p.children.indexOf(sortedEl[i].previous);
newIndex = newIndex || 0
p.children = p.children.insertFrom(oldIndex, newIndex)
el.node.parentNode.insertBefore(el.node, el.node.parentNode.childNodes[newIndex+1]);
}
}
});
// Instanziate the dockCommand
var command = new zLevelCommand(callback, [event.shape], this.facade);
command.execute();
},
setToTop: function(elements) {
// Sortieren des Arrays nach dem Index des SVGKnotens im Bezug auf dem Elternknoten.
var tmpElem = elements.sortBy( function(value, index) {
var t = $A(value.node.parentNode.childNodes);
return t.indexOf(value.node);
});
// Sortiertes Array wird nach oben verschoben.
tmpElem.each( function(value) {
var p = value.parent
p.children = p.children.without( value )
p.children.push( value );
value.node.parentNode.appendChild(value.node);
});
},
setToBack: function(elements) {
// Sortieren des Arrays nach dem Index des SVGKnotens im Bezug auf dem Elternknoten.
var tmpElem = elements.sortBy( function(value, index) {
var t = $A(value.node.parentNode.childNodes);
return t.indexOf(value.node);
});
tmpElem = tmpElem.reverse();
// Sortiertes Array wird nach unten verschoben.
tmpElem.each( function(value) {
var p = value.parent
p.children = p.children.without( value )
p.children.unshift( value );
value.node.parentNode.insertBefore(value.node, value.node.parentNode.firstChild);
});
},
setBackward: function(elements) {
// Sortieren des Arrays nach dem Index des SVGKnotens im Bezug auf dem Elternknoten.
var tmpElem = elements.sortBy( function(value, index) {
var t = $A(value.node.parentNode.childNodes);
return t.indexOf(value.node);
});
// Reverse the elements
tmpElem = tmpElem.reverse();
// Delete all Nodes who are the next Node in the nodes-Array
var compactElem = tmpElem.findAll(function(el) {return !tmpElem.some(function(checkedEl){ return checkedEl.node == el.node.previousSibling})});
// Sortiertes Array wird nach eine Ebene nach oben verschoben.
compactElem.each( function(el) {
if(el.node.previousSibling === null) { return; }
var p = el.parent;
var index = p.children.indexOf(el);
p.children = p.children.insertFrom(index, index-1)
el.node.parentNode.insertBefore(el.node, el.node.previousSibling);
});
},
setForward: function(elements) {
// Sortieren des Arrays nach dem Index des SVGKnotens im Bezug auf dem Elternknoten.
var tmpElem = elements.sortBy( function(value, index) {
var t = $A(value.node.parentNode.childNodes);
return t.indexOf(value.node);
});
// Delete all Nodes who are the next Node in the nodes-Array
var compactElem = tmpElem.findAll(function(el) {return !tmpElem.some(function(checkedEl){ return checkedEl.node == el.node.nextSibling})});
// Sortiertes Array wird eine Ebene nach unten verschoben.
compactElem.each( function(el) {
var nextNode = el.node.nextSibling
if(nextNode === null) { return; }
var index = el.parent.children.indexOf(el);
var p = el.parent;
p.children = p.children.insertFrom(index, index+1)
el.node.parentNode.insertBefore(nextNode, el.node);
});
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/arrangementLight.js | JavaScript | mit | 6,953 |
/**
* 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.
*
*
* HOW to USE the OVERLAY PLUGIN:
* You can use it via the event mechanism from the editor
* by using facade.raiseEvent( <option> )
*
* As an example please have a look in the overlayexample.js
*
* The option object should/have to have following attributes:
*
* Key Value-Type Description
* ================================================================
*
* type ORYX.CONFIG.EVENT_OVERLAY_SHOW | ORYX.CONFIG.EVENT_OVERLAY_HIDE This is the type of the event
* id <String> You have to use an unified id for later on hiding this overlay
* shapes <ORYX.Core.Shape[]> The Shapes where the attributes should be changed
* attributes <Object> An object with svg-style attributes as key-value pair
* node <SVGElement> An SVG-Element could be specified for adding this to the Shape
* nodePosition "N"|"NE"|"E"|"SE"|"S"|"SW"|"W"|"NW"|"START"|"END" The position for the SVG-Element relative to the
* specified Shape. "START" and "END" are just using for a Edges, then
* the relation is the start or ending Docker of this edge.
*
*
**/
if (!ORYX.Plugins)
ORYX.Plugins = new Object();
ORYX.Plugins.Overlay = Clazz.extend({
facade: undefined,
styleNode: undefined,
construct: function(facade){
this.facade = facade;
this.changes = [];
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_OVERLAY_SHOW, this.show.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_OVERLAY_HIDE, this.hide.bind(this));
this.styleNode = document.createElement('style')
this.styleNode.setAttributeNS(null, 'type', 'text/css')
document.getElementsByTagName('head')[0].appendChild( this.styleNode )
},
/**
* Show the overlay for specific nodes
* @param {Object} options
*
* String options.id - MUST - Define the id of the overlay (is needed for the hiding of this overlay)
* ORYX.Core.Shape[] options.shapes - MUST - Define the Shapes for the changes
* attr-name:value options.changes - Defines all the changes which should be shown
*
*
*/
show: function( options ){
// Checks if all arguments are available
if(!options ||
!options.shapes || !options.shapes instanceof Array ||
!options.id || !options.id instanceof String || options.id.length == 0) {
return;
}
//if( this.changes[options.id]){
// this.hide( options )
//}
// Checked if attributes are set
if( options.attributes ){
// FOR EACH - Shape
options.shapes.each(function(el){
// Checks if the node is a Shape
if( !el instanceof ORYX.Core.Shape){ return }
this.setAttributes( el.node , options.attributes )
}.bind(this));
}
var isSVG = true
try {
isSVG = options.node && options.node instanceof SVGElement;
} catch(e){}
// Checks if node is set and if this is a SVGElement
if ( options.node && isSVG) {
options["_temps"] = [];
// FOR EACH - Node
options.shapes.each(function(el, index){
// Checks if the node is a Shape
if( !el instanceof ORYX.Core.Shape){ return }
var _temp = {};
_temp.svg = options.dontCloneNode ? options.node : options.node.cloneNode( true );
// Append the svg node to the ORYX-Shape
this.facade.getCanvas().getSvgContainer().appendChild(_temp.svg);
if (el instanceof ORYX.Core.Edge && !options.nodePosition) {
options['nodePosition'] = "START";
}
// If the node position is set, it has to be transformed
if (options.nodePosition && !options.nodePositionAbsolute) {
var b = el.absoluteBounds();
var p = options.nodePosition.toUpperCase();
// Check the values of START and END
if( el instanceof ORYX.Core.Node && p == "START"){
p = "NW";
} else if(el instanceof ORYX.Core.Node && p == "END"){
p = "SE";
} else if(el instanceof ORYX.Core.Edge && p == "START"){
b = el.getDockers().first().bounds;
} else if(el instanceof ORYX.Core.Edge && p == "END"){
b = el.getDockers().last().bounds;
}
// Create a callback for changing the position
// depending on the position string
_temp.callback = function() { this.positionCallback(el, p, b, options.keepInsideVisibleArea, _temp); }.bind(this);
_temp.element = el;
_temp.callback();
b.registerCallback( _temp.callback );
}
// Show the ghostpoint
if(options.ghostPoint){
var point={x:0, y:0};
point=options.ghostPoint;
_temp.callback = function(){
var x = 0; var y = 0;
x = point.x -7;
y = point.y -7;
_temp.svg.setAttributeNS(null, "transform", "translate(" + x + ", " + y + ")")
}.bind(this)
_temp.element = el;
_temp.callback();
b.registerCallback( _temp.callback );
}
options._temps.push( _temp )
}.bind(this))
}
// Store the changes
if( !this.changes[options.id] ){
this.changes[options.id] = [];
}
this.changes[options.id].push( options );
},
/**
* Hide the overlay with the spefic id
* @param {Object} options
*/
hide: function( options ){
// Checks if all arguments are available
if(!options ||
!options.id || !options.id instanceof String || options.id.length == 0 ||
!this.changes[options.id]) {
return;
}
// Delete all added attributes
// FOR EACH - Shape
this.changes[options.id].each(function(option){
option.shapes.each(function(el, index){
// Checks if the node is a Shape
if( !el instanceof ORYX.Core.Shape){ return }
this.deleteAttributes( el.node )
}.bind(this));
if( option._temps ){
option._temps.each(function(tmp){
// Delete the added Node, if there is one
if( tmp.svg && tmp.svg.parentNode ){
tmp.svg.parentNode.removeChild( tmp.svg )
}
// If
if( tmp.callback && tmp.element){
// It has to be unregistered from the edge
tmp.element.bounds.unregisterCallback( tmp.callback )
}
}.bind(this));
}
}.bind(this));
this.changes[options.id] = null;
},
/**
* Set the given css attributes to that node
* @param {HTMLElement} node
* @param {Object} attributes
*/
setAttributes: function( node, attributes ) {
// Get all the childs from ME
var childs = this.getAllChilds( node.firstChild.firstChild )
var ids = []
// Add all Attributes which have relation to another node in this document and concate the pure id out of it
// This is for example important for the markers of a edge
childs.each(function(e){ ids.push( $A(e.attributes).findAll(function(attr){ return attr.nodeValue.startsWith('url(#')}) )})
ids = ids.flatten().compact();
ids = ids.collect(function(s){return s.nodeValue}).uniq();
ids = ids.collect(function(s){return s.slice(5, s.length-1)})
// Add the node ID to the id
ids.unshift( node.id + ' .me')
var attr = $H(attributes);
var attrValue = attr.toJSON().gsub(',', ';').gsub('"', '');
var attrMarkerValue = attributes.stroke ? attrValue.slice(0, attrValue.length-1) + "; fill:" + attributes.stroke + ";}" : attrValue;
var attrTextValue;
if( attributes.fill ){
var copyAttr = Object.clone(attributes);
copyAttr.fill = "black";
attrTextValue = $H(copyAttr).toJSON().gsub(',', ';').gsub('"', '');
}
// Create the CSS-Tags Style out of the ids and the attributes
csstags = ids.collect(function(s, i){return "#" + s + " * " + (!i? attrValue : attrMarkerValue) + "" + (attrTextValue ? " #" + s + " text * " + attrTextValue : "") })
// Join all the tags
var s = csstags.join(" ") + "\n"
// And add to the end of the style tag
this.styleNode.appendChild(document.createTextNode(s));
},
/**
* Deletes all attributes which are
* added in a special style sheet for that node
* @param {HTMLElement} node
*/
deleteAttributes: function( node ) {
// Get all children which contains the node id
var delEl = $A(this.styleNode.childNodes)
.findAll(function(e){ return e.textContent.include( '#' + node.id ) });
// Remove all of them
delEl.each(function(el){
el.parentNode.removeChild(el);
});
},
getAllChilds: function( node ){
var childs = $A(node.childNodes)
$A(node.childNodes).each(function( e ){
childs.push( this.getAllChilds( e ) )
}.bind(this))
return childs.flatten();
},
isInsideVisibleArea: function(x, y, width, height) {
// get the div that is responsible for scrolling
var centerDiv = document.getElementById("oryx_center_region").children[0].children[0];
var viewportLeft = centerDiv.scrollLeft / this.facade.getCanvas().zoomLevel;
var viewportTop = centerDiv.scrollTop / this.facade.getCanvas().zoomLevel;
// yeah I'm fully aware of how much I suck: 20px is the width of the scrollbars
var viewportWidth = (centerDiv.offsetWidth - 20) / this.facade.getCanvas().zoomLevel;
var viewportHeight = (centerDiv.offsetHeight - 20) / this.facade.getCanvas().zoomLevel;
var insideX = (x > viewportLeft && x + width < viewportLeft + viewportWidth);
var insideY = (y > viewportTop && y + height < viewportTop + viewportHeight);
return insideX && insideY;
},
positionCallback: function(element, position, bounds, keepVisible, temp) {
var x, y;
try {
var overlayWidth = temp.svg.getBBox().width;
var overlayHeight = temp.svg.getBBox().height;
} catch(e) {
//workaround for SVG bug in Firefox
var xdadsd = 42;
}
var curPos, curPosIndex;
var positionPreference = ["N", "NW", "W", "NE", "SW", "SE", "INSIDE_NW", "INSIDE_W"];
var startAndEnd = { x: bounds.width() / 2, y: bounds.height() / 2 };
var positions = {
"NW": { x: -overlayWidth, y: -overlayHeight * 1.5 },
"N": { x: bounds.width() / 2 - overlayWidth / 2, y: -overlayHeight * 1.5 },
"NE": { x: bounds.width(), y: -overlayHeight * 1.5 },
"E": { x: bounds.width(), y: bounds.height() / 2 - overlayHeight / 2 },
"SE": { x: bounds.width(), y: bounds.height() },
"S": { x: bounds.width() / 2 - overlayWidth / 2, y: bounds.height() },
"SW": { x: -overlayWidth - 20, y: bounds.height() },
"W": { x: -overlayWidth - 20, y: bounds.height() / 2 - overlayHeight / 2 },
"INSIDE_NW": { x: bounds.width() - overlayWidth - 20, y: 0 },
"INSIDE_W": { x: 20, y: bounds.height() / 2 - overlayHeight / 2 },
"START": startAndEnd,
"END": startAndEnd
}
// get position and (if necessary) make sure the overlay is inside the visible part of the screen
curPos = position;
curPosIndex = 0;
do {
x = positions[curPos].x + bounds.upperLeft().x;
y = positions[curPos].y + bounds.upperLeft().y;
curPos = positionPreference[curPosIndex++];
if (typeof curPos === "undefined") {
break;
}
} while (keepVisible && !this.isInsideVisibleArea(x, y, overlayWidth, overlayHeight));
temp.svg.setAttributeNS(null, "transform", "translate(" + x + ", " + y + ")");
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/overlay.js | JavaScript | mit | 13,901 |
/**
* 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.Paint = ORYX.Plugins.AbstractPlugin.extend({
construct: function construct(facade) {
arguments.callee.$.construct.apply(this, arguments);
this.facade.offer({
name: ORYX.I18N.Paint.paint,
description: ORYX.I18N.Paint.paintDesc,
iconCls: 'pw-toolbar-button pw-toolbar-paint',
keyCodes: [],
functionality: this._togglePaint.bind(this),
group: ORYX.I18N.Paint.group,
isEnabled: function() { return true; },
toggle: true,
index: 0,
visibleInViewMode: true
});
this.facade.offer({
keyCodes: [{
keyCode: 46, // delete key
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}, {
metaKeys: [ORYX.CONFIG.META_KEY_META_CTRL],
keyCode: 8, // backspace key
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}],
functionality: this._onRemoveKey.bind(this)
});
this.users = [];
this.editMode = false;
this.showCanvas = false;
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_PAINT_NEWSHAPE, this._onNewShape.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_PAINT_REMOVESHAPE, this._onRemoveShape.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_CANVAS_RESIZED, this._onCanvasResized.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_CANVAS_RESIZE_SHAPES_MOVED, this._onCanvasResizedShapesMoved.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_CANVAS_ZOOMED, this._onCanvasZoomed.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_FARBRAUSCH_NEW_INFOS, this._updateFarbrauschInfos.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MODE_CHANGED, this._onModeChanged.bind(this));
},
onLoaded: function onLoaded() {
this.paintCanvas = this._createCanvas();
this._loadBrush(this.paintCanvas);
this.toolbar = this._createToolbar();
},
_onModeChanged: function _onModeChanged(event) {
this.editMode = event.mode.isEditMode();
if (event.mode.isPaintMode()) {
this.paintCanvas.show();
this._alignCanvasWithOryxCanvas();
} else {
this.paintCanvas.hide();
}
if (event.mode.isEditMode() && event.mode.isPaintMode()) {
if (typeof this.toolbar !== "undefined") {
this.toolbar.show();
}
this.paintCanvas.activate();
} else {
if (typeof this.toolbar !== "undefined") {
this.toolbar.hide();
}
this.paintCanvas.deactivate();
}
},
_activateTool: function _activateTool(toolClass) {
this.paintCanvas.setTool(toolClass);
},
_updateFarbrauschInfos: function _updateFarbrauschInfos(event) {
this.users = event.users;
this.paintCanvas.updateColor();
this.paintCanvas.redraw();
},
_onCanvasZoomed: function _onCanvasZoomed(event) {
if (typeof this.paintCanvas === 'undefined') {
return;
}
this.paintCanvas.scale(event.zoomLevel);
this._alignCanvasWithOryxCanvas();
},
_createCanvas: function _createCanvas() {
var canvas = this.facade.getCanvas();
var options = {
canvasId: "freehand-paint",
width: canvas.bounds.width(),
height: canvas.bounds.height(),
shapeDrawnCallback: this._onShapeExistenceCommand.bind(this, "Paint.DrawCommand"),
shapeDeletedCallback: this._onShapeExistenceCommand.bind(this, "Paint.RemoveCommand"),
getUsersCallback: function getUsers() { return this.users; }.bind(this),
getUserIdCallback: function getUserId() { return this.facade.getUserId(); }.bind(this),
isInEditModeCallback: function isInEditModeCallback() { return this.editMode; }.bind(this)
};
var paintCanvas = new ORYX.Plugins.Paint.PaintCanvas(options);
var canvasContainer = canvas.rootNode.parentNode;
canvasContainer.appendChild(paintCanvas.getDomElement());
return paintCanvas;
},
_loadBrush : function _loadBrush(paintCanvas) {
var img = new Image();
img.onload = paintCanvas.setBrush.bind(paintCanvas, img, 2);
img.src = this._getBasePath() + "/../oryx/editor/images/paint/brush.png";
},
_createToolbar: function _createToolbar() {
var basePath = this._getBasePath();
var toolbar = new ORYX.Plugins.Paint.Toolbar();
toolbar.addButton(basePath + "/../oryx/editor/images/paint/line.png",
this._activateTool.bind(this, ORYX.Plugins.Paint.PaintCanvas.LineTool));
toolbar.addButton(basePath + "/../oryx/editor/images/paint/arrow.png",
this._activateTool.bind(this, ORYX.Plugins.Paint.PaintCanvas.ArrowTool));
toolbar.addButton(basePath + "/../oryx/editor/images/paint/box.png",
this._activateTool.bind(this, ORYX.Plugins.Paint.PaintCanvas.BoxTool));
toolbar.addButton(basePath + "/../oryx/editor/images/paint/ellipse.png",
this._activateTool.bind(this, ORYX.Plugins.Paint.PaintCanvas.EllipseTool));
toolbar.hide();
return toolbar;
},
_getBasePath: function _getBasePath() {
var lastSlash = window.location.href.lastIndexOf("/");
return window.location.href.substring(0, lastSlash);
},
_togglePaint: function _togglePaint() {
this.showCanvas = !this.showCanvas;
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_PAINT_CANVAS_TOGGLED,
paintActive: this.showCanvas
});
},
_onNewShape: function _onNewShape(event) {
this.paintCanvas.addShapeAndDraw(event.shape);
},
_onRemoveShape: function _onRemoveShape(event) {
if (this.editMode) {
this.paintCanvas.removeShape(event.shapeId);
}
},
_onShapeExistenceCommand: function _onShapeExistenceCommand(cmdName, shape) {
var cmd = new ORYX.Core.Commands[cmdName](shape, this.facade);
this.facade.executeCommands([cmd]);
},
_onCanvasResized: function _onCanvasResized(event) {
this.paintCanvas.resize(event.bounds.width(), event.bounds.height());
this._alignCanvasWithOryxCanvas();
},
_onCanvasResizedShapesMoved: function _onCanvasResizedShapesMoved(event) {
this.paintCanvas.moveShapes(event.offsetX, event.offsetY);
},
_onRemoveKeyPressed: function _onRemoveKeyPressed(event) {
if (this.editMode) {
this.paintCanvas.deleteCurrentShape();
}
},
_alignCanvasWithOryxCanvas: function _alignCanvasWithOryxCanvas() {
var canvas = this.facade.getCanvas().rootNode.parentNode;
var offset = jQuery(canvas).offset();
this.paintCanvas.setOffset(offset);
},
_onRemoveKey: function _onRemoveKey(event) {
this.paintCanvas.removeShapesUnderCursor();
}
});
ORYX.Plugins.Paint.Toolbar = Clazz.extend({
construct: function construct() {
var canvasContainer = $$(".ORYX_Editor")[0].parentNode;
this.toolsList = document.createElement('div');
this.toolsList.id = 'paint-toolbar';
canvasContainer.appendChild(this.toolsList);
this.buttonsAdded = false;
},
show: function show() {
this.toolsList.show();
},
hide: function hide() {
this.toolsList.hide();
},
addButton: function addButton(image, callback) {
var button = this._createButton(image);
this.toolsList.appendChild(button);
var onClick = this._onButtonClicked.bind(this, button, callback);
jQuery(button).click(onClick);
// one button has to be pressed at all times,
// so if this is the first one, press it
if (!this.buttonsAdded) {
onClick();
this.buttonsAdded = true;
}
},
_createButton: function _createButton(image) {
var newElement = document.createElement('div');
newElement.className = 'paint-toolbar-button';
var stencilImage = document.createElement('div');
stencilImage.style.backgroundImage = 'url(' + image + ')';
newElement.appendChild(stencilImage);
return newElement;
},
_onButtonClicked: function _onButtonClicked(element, callback) {
jQuery(this.toolsList).children().removeClass("paint-toolbar-button-pressed");
jQuery(element).addClass("paint-toolbar-button-pressed");
callback();
}
});
ORYX.Plugins.Paint.CanvasWrapper = Clazz.extend({
construct: function construct(canvas) {
this.canvas = canvas;
this.context = canvas.getContext("2d");
this.scalingFactor = 1.0;
this.color = ORYX.CONFIG.FARBRAUSCH_DEFAULT_COLOR;
},
clear: function clear() {
this.canvas.width = this.canvas.width;
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.scale(this.scalingFactor);
},
resize: function resize(width, height) {
this.canvas.style.width = width + "px";
this.canvas.style.height = height + "px";
this.canvas.width = width;
this.canvas.height = height;
},
scale: function scale(factor) {
this.context.scale(factor, factor);
this.scalingFactor = factor;
},
setStyle: function setStyle(width, color) {
this.context.lineJoin = 'round';
this.context.lineWidth = width;
this.context.strokeStyle = color;
this._setColor(color);
},
setBrush: function setBrush(brushImage, dist) {
this.origBrush = brushImage;
this.brush = this._colorBrush(brushImage, this.color);
this.brushDist = dist;
},
drawLine: function drawLine(ax, ay, bx, by) {
(this.brush ? this._brushLine : this._simpleLine).apply(this, arguments);
},
drawEllipse: function drawLine(ax, ay, bx, by) {
(this.brush ? this._brushEllipse : this._simpleEllipse).apply(this, arguments);
},
drawArrow: function drawArrow(ax, ay, bx, by) {
this.drawLine.apply(this, arguments);
var angle = -Math.atan2(by - ay, bx - ax) + Math.PI / 2.0;
var tipLength = 20;
var tip1Angle = angle + 3/4 * Math.PI;
var tip1dx = Math.sin(tip1Angle) * tipLength;
var tip1dy = Math.cos(tip1Angle) * tipLength;
this.drawLine(bx, by, bx + tip1dx, by + tip1dy);
var tip2Angle = angle - 3/4 * Math.PI;
var tip2dx = Math.sin(tip2Angle) * tipLength;
var tip2dy = Math.cos(tip2Angle) * tipLength;
this.drawLine(bx, by, bx + tip2dx, by + tip2dy);
},
strokeRect: function strokeRect(x, y, width, height) {
this.drawLine(x, y, x + width, y);
this.drawLine(x, y + height, x + width, y + height);
this.drawLine(x, y, x, y + height);
this.drawLine(x + width, y, x + width, y + height);
},
_setColor: function _setColor(color) {
if (typeof this.origBrush !== "undefined") {
this.brush = this._colorBrush(this.origBrush, color);
}
this.color = color;
},
_simpleLine: function _simpleLine(ax, ay, bx, by) {
this.context.beginPath();
this.context.moveTo(ax, ay);
this.context.lineTo(bx, by);
this.context.stroke();
},
_brushLine: function _brushLine(ax, ay, bx, by) {
var makePoint = function(x, y) { return {x: x, y: y}; };
var totalDist = ORYX.Core.Math.getDistancePointToPoint(makePoint(ax, ay), makePoint(bx, by));
var steps = totalDist / this.brushDist;
var totalVec = makePoint(bx - ax, by - ay);
var divide = function(vec, by) { return {x: vec.x / by, y: vec.y / by}; };
var delta = divide(totalVec, steps);
for (var i = 0; i < steps; i++) {
this.context.drawImage(this.brush,
ax + i * delta.x - this.brush.width / 2,
ay + i * delta.y - this.brush.height / 2);
}
},
_simpleEllipse: function _simpleEllipse(x1, y1, x2, y2) {
// code by http://canvaspaint.org/blog/2006/12/ellipse/
var ell = this._getEllipseInRectParams.apply(this, arguments);
var KAPPA = 4 * ((Math.sqrt(2) -1) / 3);
this.context.beginPath();
this.context.moveTo(ell.cx, ell.cy - ell.ry);
this.context.bezierCurveTo(ell.cx + (KAPPA * ell.rx), ell.cy - ell.ry, ell.cx + ell.rx, ell.cy - (KAPPA * ell.ry), ell.cx + ell.rx, ell.cy);
this.context.bezierCurveTo(ell.cx + ell.rx, ell.cy + (KAPPA * ell.ry), ell.cx + (KAPPA * ell.rx), ell.cy + ell.ry, ell.cx, ell.cy + ell.ry);
this.context.bezierCurveTo(ell.cx - (KAPPA * ell.rx), ell.cy + ell.ry, ell.cx - ell.rx, ell.cy + (KAPPA * ell.ry), ell.cx - ell.rx, ell.cy);
this.context.bezierCurveTo(ell.cx - ell.rx, ell.cy - (KAPPA * ell.ry), ell.cx - (KAPPA * ell.rx), ell.cy - ell.ry, ell.cx, ell.cy - ell.ry);
this.context.stroke();
},
_brushEllipse: function _brushEllipse(x1, y1, x2, y2) {
var ell = this._getEllipseInRectParams.apply(this, arguments);
var delta = 2 * Math.PI / Math.max(ell.rx, ell.ry);
var points = [];
for (var t = 0; t < 2 * Math.PI; t += delta) {
points.push({
x: ell.cx + Math.cos(t) * ell.rx,
y: ell.cy + Math.sin(t) * ell.ry
});
}
var cur, next;
for (var i = 0; i < points.length - 1; i++) {
cur = points[i];
next = points[i + 1];
this._brushLine(cur.x, cur.y, next.x, next.y);
}
this._brushLine(points.last().x, points.last().y, points.first().x, points.first().y);
},
_getEllipseInRectParams: function _getEllipseInRectParams(x1, y1, x2, y2) {
var rx = (x2 - x1) / 2;
var ry = (y2 - y1) / 2;
return {
rx: rx,
ry: ry,
cx: x1 + rx,
cy: y1 + ry
};
},
_colorBrush: function _colorBrush(brush, color) {
var tempCanvas = this._createTempCanvas(brush.width, brush.height);
var context = tempCanvas.getContext("2d");
context.drawImage(brush, 0, 0);
this._recolorCanvas(context, color, brush.width, brush.height);
return tempCanvas;
},
_createTempCanvas: function _createTempCanvas(width, height) {
var tempCanvas = document.createElement("canvas");
tempCanvas.style.width = width + "px";
tempCanvas.style.height = height + "px";
tempCanvas.width = width;
tempCanvas.height = height;
return tempCanvas;
},
_recolorCanvas: function _recolorCanvas(context, color, width, height) {
var imgData = context.getImageData(0, 0, width, height);
var rgb = this._getRGB(color);
var data = imgData.data;
for (var i = 0; i < data.length; i += 4) {
data[i] = data[i] / 255 * rgb.r;
data[i+1] = data[i+1] / 255 * rgb.g;
data[i+2] = data[i+2] / 255 * rgb.b;
}
context.putImageData(imgData, 0, 0);
},
_getRGB: function _getRGB(hexColor) {
var hex = hexColor.substring(1, 7); // cut off leading #
return {
r: parseInt(hex.substring(0, 2), 16),
g: parseInt(hex.substring(2, 4), 16),
b: parseInt(hex.substring(4, 6), 16)
};
}
});
ORYX.Plugins.Paint.PaintCanvas = Clazz.extend({
construct: function construct(options) {
this.container = this._createCanvasContainer(options.canvasId, options.width, options.height);
var viewCanvas = this._createCanvas("view-canvas");
this.viewCanvas = new ORYX.Plugins.Paint.CanvasWrapper(viewCanvas);
this.viewCanvas.resize(options.width, options.height);
this.container.appendChild(viewCanvas);
var paintCanvas = this._createCanvas("paint-canvas");
this.paintCanvas = new ORYX.Plugins.Paint.CanvasWrapper(paintCanvas);
this.paintCanvas.resize(options.width, options.height);
this.container.appendChild(paintCanvas);
this.shapes = [];
this.shapeDrawnCallback = options.shapeDrawnCallback;
this.shapeDeletedCallback = options.shapeDeletedCallback;
this.getUsersCallback = options.getUsersCallback;
this.getUserIdCallback = options.getUserIdCallback;
this.isInEditModeCallback = options.isInEditModeCallback;
this.scalingFactor = 1.0;
this.width = options.width;
this.height = options.height;
this.mouseState = new ORYX.Plugins.Paint.PaintCanvas.MouseState(paintCanvas, {
onMouseDown: this._onMouseDown.bind(this),
onMouseUp: this._onMouseUp.bind(this),
onMouseMove: this._onMouseMove.bind(this)
});
},
activate: function activate() {
jQuery(this.container).addClass("paint-canvas-container-active");
},
deactivate: function deactivate() {
jQuery(this.container).removeClass("paint-canvas-container-active");
this.currentAction.mouseUp(this.mouseState.parameters.pos);
this.paintCanvas.clear();
},
setTool: function setTool(toolClass) {
var color = this._getColor(this.getUserIdCallback());
this.currentAction = new toolClass(this.getUserIdCallback.bind(this), color, this.paintCanvas, this._onShapeDone.bind(this));
},
setBrush: function setBrush(brushImage, dist) {
this.viewCanvas.setBrush(brushImage, dist);
this.paintCanvas.setBrush(brushImage, dist);
this._redrawShapes();
},
scale: function scale(factor) {
this._setDimensions(this.width * factor, this.height * factor, factor);
this._redrawShapes();
this.scalingFactor = factor;
},
setPosition: function setPosition(top, left) {
this.container.style.top = top + 'px';
this.container.style.left = left + 'px';
},
getDomElement: function getDomElement() {
return this.container;
},
setOffset: function setOffset(offset) {
jQuery(this.container).offset(offset);
},
addShapeAndDraw: function addShapeAndDraw(shape) {
this.shapes.push(shape);
this._drawShape(this.viewCanvas, shape);
},
removeShape: function removeShape(shapeId) {
this.shapes = this.shapes.reject(function(s) { return s.id === shapeId; });
this.redraw();
},
removeShapesUnderCursor: function removeShapesUnderCursor() {
this._getShapesUnderCursor().each(function removeShape(s) {
this.shapeDeletedCallback(s);
}.bind(this));
this.paintCanvas.clear();
},
hide: function hide() {
this.container.style.display = "none";
},
show: function show() {
this.container.style.display = "block";
},
isVisible: function isVisible() {
return this.container.style.display !== "none";
},
redraw: function redraw() {
this.viewCanvas.clear();
this._redrawShapes();
},
moveShapes: function moveShapes(x, y) {
this.shapes.each(function moveShape(s) {
s.move(x, y);
});
if (typeof this.currentAction !== "undefined") {
this.currentAction.move(x, y);
}
this.viewCanvas.clear();
this.paintCanvas.clear();
this._redrawShapes();
},
resize: function resize(width, height) {
this.width = width;
this.height = height;
this._setDimensions(width * this.scalingFactor, height * this.scalingFactor, this.scalingFactor);
this._redrawShapes();
},
updateColor: function updateColor() {
var color = this._getColor(this.getUserIdCallback());
this.currentAction.setColor(color);
},
_onMouseDown: function _onMouseDown(params) {
if (params.inside && this.isInEditModeCallback()) {
this.currentAction.mouseDown(this._translateMouse(params.pos));
}
},
_onMouseMove: function _onMouseMove(params) {
if (!params.inside || !this.isInEditModeCallback()) {
return;
}
if (this.isInEditModeCallback()) {
if (params.mouseDown) {
this.currentAction.mouseMove(this._translateMouse(params.pos));
} else {
this.paintCanvas.clear();
this._highlightShapesUnderCursor();
}
}
},
_onMouseUp: function _onMouseUp(params) {
this.currentAction.mouseUp(this._translateMouse(params.pos));
},
_onShapeDone: function _onShapeDone(shape) {
if (typeof this.shapeDrawnCallback === "function") {
this.shapeDrawnCallback(shape);
}
this.paintCanvas.clear();
},
_highlightShapesUnderCursor: function _highlightShapesUnderCursor() {
this._getShapesUnderCursor().each(function drawShape(s) {
this._drawShape(this.paintCanvas, s, 3);
}.bind(this));
},
_getShapesUnderCursor: function _getShapesUnderCursor() {
if (!this.mouseState.parameters.inside) {
return [];
}
return this.shapes.select(function isUnderCursor(s) {
return s.isUnderCursor(this._translateMouse(this.mouseState.parameters.pos));
}.bind(this));
},
_redrawShapes: function _redrawShapes() {
for (var i = 0; i < this.shapes.length; i++) {
this._drawShape(this.viewCanvas, this.shapes[i]);
}
if (typeof this.currentAction !== "undefined") {
this.currentAction.redraw();
}
},
_getColor: function _getColor(userId) {
var user = this._getUser(userId);
if (typeof user === 'undefined' || typeof user.color === 'undefined') {
return ORYX.CONFIG.FARBRAUSCH_DEFAULT_COLOR;
}
return user.color;
},
_getUser: function _getUser(id) {
return this.getUsersCallback()[id];
},
_setDimensions: function _setDimensions(width, height, factor) {
this._resizeDiv(this.container, width, height);
this.paintCanvas.resize(width, height);
this.paintCanvas.scale(factor);
this.viewCanvas.resize(width, height);
this.viewCanvas.scale(factor);
},
_drawShape: function _drawShape(canvas, shape, width) {
var shapeColor = this._getColor(shape.creatorId);
shape.draw(canvas, shapeColor, width);
},
_createCanvasContainer: function _createCanvasContainer(canvasId, width, height) {
var container = document.createElement('div');
container.className = "paint-canvas-container";
container.id = canvasId;
container.style.width = width + "px";
container.style.height = height + "px";
return container;
},
_createCanvas: function _createCanvas(id, width, height) {
var canvas = document.createElement('canvas');
canvas.className = "paint-canvas";
canvas.id = id;
return canvas;
},
_resizeDiv: function _resizeDiv(div, width, height) {
div.style.width = width + "px";
div.style.height = height + "px";
},
_translateMouse: function _translateMouse(pos) {
if (typeof pos === "undefined") {
return undefined;
}
return { left: pos.left / this.scalingFactor,
top: pos.top / this.scalingFactor };
}
});
ORYX.Plugins.Paint.PaintCanvas.MouseState = Clazz.extend({
construct: function construct(element, callbacks) {
this.element = element;
this.callbacks = callbacks;
this.parameters = {
inside: undefined,
mouseDown: false,
pos: undefined
};
document.documentElement.addEventListener("mousedown", this._onMouseDown.bind(this), false);
window.addEventListener("mousemove", this._onMouseMove.bind(this), true);
window.addEventListener("mouseup", this._onMouseUp.bind(this), true);
jQuery(element).mouseleave = this._onMouseLeave.bind(this);
},
_onMouseDown: function _onMouseDown(event) {
if (this._isInside(event)) {
document.onselectstart = function () { return false; };
this.parameters.mouseDown = true;
} else {
this.parameters.mouseDown = false;
}
this._rememberPosition(event);
this._callback("onMouseDown");
},
_onMouseMove: function _onMouseMove(event) {
this._rememberPosition(event);
this._callback("onMouseMove");
},
_onMouseUp: function _onMouseUp(event) {
if (this.parameters.mouseDown) {
document.onselectstart = function () { return true; };
this.parameters.mouseDown = false;
}
this._rememberPosition(event);
this._callback("onMouseUp");
},
_onMouseLeave: function _onMouseLeave(event) {
this.parameters.mouseDown = false;
},
_rememberPosition: function _rememberPosition(event) {
this.parameters.inside = this._isInside(event);
this.parameters.pos = this._isInside(event) ? { left: event.layerX, top: event.layerY } : undefined;
},
_isInside: function _isInside(event) {
return (event.target === this.element);
},
_callback: function _callback(name) {
if (typeof this.callbacks[name] === "function") {
this.callbacks[name](this.parameters);
}
}
});
ORYX.Plugins.Paint.PaintCanvas.Tool = Clazz.extend({
construct: function construct(creatorCallback, color, canvas, doneCallback) {
this.done = doneCallback;
this.getCreator = creatorCallback;
this.canvas = canvas;
this.color = color;
},
getColor: function getColor() {
return this.color;
},
setColor: function setColor(color) {
this.color = color;
}
});
ORYX.Plugins.Paint.PaintCanvas.LineTool = ORYX.Plugins.Paint.PaintCanvas.Tool.extend({
construct: function construct(creatorCallback, color, canvas, doneCallback) {
arguments.callee.$.construct.apply(this, arguments);
this._reset();
},
mouseDown: function mouseDown(pos) {
this._addPoint(pos.left, pos.top);
this.prevX = pos.left;
this.prevY = pos.top;
},
mouseUp: function mouseUp(pos) {
if (typeof this.prevX !== "undefined" &&
typeof this.prevY !== "undefined") {
var shape = new ORYX.Plugins.Paint.PaintCanvas.Line(this.getCreator(), this.points);
this.done(shape);
}
this._reset();
},
mouseMove: function mouseMove(pos) {
this._addPoint(pos.left, pos.top);
if (typeof this.prevX !== "undefined" &&
typeof this.prevY !== "undefined") {
this._drawLineSegment(this.prevX, this.prevY, pos.left, pos.top);
}
this.prevX = pos.left;
this.prevY = pos.top;
},
redraw: function redraw() {
var i;
var cur, next;
for (i = 0; i < this.points.length - 1; i++) {
cur = this.points[i];
next = this.points[i + 1];
this._drawLineSegment(cur.x, cur.y, next.x, next.y);
}
},
move: function move(x, y) {
this.points.each(function movePoint(p) {
p.x += x;
p.y += y;
});
this.prevX += x;
this.prevY += y;
},
_drawLineSegment: function _drawLineSegment(x1, y1, x2, y2) {
this.canvas.setStyle(1, this.getColor());
this.canvas.drawLine(x1, y1, x2, y2);
},
_addPoint: function _addPoint(x, y) {
this.points.push({ x: x, y: y });
},
_reset: function _reset() {
this.points = [];
this.prevX = undefined;
this.prevY = undefined;
}
});
ORYX.Plugins.Paint.PaintCanvas.TwoPointTool = ORYX.Plugins.Paint.PaintCanvas.Tool.extend({
construct: function construct(creatorId, color, canvas, doneCallback, shapeClass) {
arguments.callee.$.construct.call(this, creatorId, color, canvas, doneCallback);
this.shapeClass = shapeClass;
this._reset();
},
mouseDown: function mouseDown(pos) {
this.start = pos;
},
mouseUp: function mouseUp(pos) {
var shape;
var endPos = pos || this.curEnd;
if (typeof this.start !== "undefined" &&
typeof endPos !== "undefined") {
shape = new this.shapeClass(this.getCreator(), this.start, endPos);
this.done(shape);
}
this._reset();
},
mouseMove: function mouseMove(pos) {
if (typeof this.start === "undefined")
return;
this.curEnd = pos;
this.canvas.clear();
this.draw(this.canvas, this.start, pos);
},
redraw: function redraw() {
if (typeof this.curEnd !== "undefined") {
this.draw(this.canvas, this.start, this.curEnd);
}
},
move: function move(x, y) {
var movePoint = function movePoint(p) {
if (typeof p !== "undefined") {
p.left += x;
p.top += y;
}
};
movePoint(this.start);
movePoint(this.curEnd);
},
_reset: function _reset() {
this.start = undefined;
this.curEnd = undefined;
}
});
ORYX.Plugins.Paint.PaintCanvas.ArrowTool = ORYX.Plugins.Paint.PaintCanvas.TwoPointTool.extend({
construct: function construct(creatorId, color, canvas, doneCallback) {
arguments.callee.$.construct.call(this, creatorId, color, canvas, doneCallback, ORYX.Plugins.Paint.PaintCanvas.Arrow);
},
draw: function draw(canvas, start, end) {
canvas.setStyle(1, this.getColor());
canvas.drawArrow(start.left, start.top, end.left, end.top);
}
});
ORYX.Plugins.Paint.PaintCanvas.BoxTool = ORYX.Plugins.Paint.PaintCanvas.TwoPointTool.extend({
construct: function construct(creatorId, color, canvas, doneCallback) {
arguments.callee.$.construct.call(this, creatorId, color, canvas, doneCallback, ORYX.Plugins.Paint.PaintCanvas.Box);
},
draw: function draw(canvas, start, end) {
canvas.setStyle(1, this.getColor());
canvas.strokeRect(start.left, start.top, end.left - start.left, end.top - start.top);
}
});
ORYX.Plugins.Paint.PaintCanvas.EllipseTool = ORYX.Plugins.Paint.PaintCanvas.TwoPointTool.extend({
construct: function construct(creatorId, color, canvas, doneCallback) {
arguments.callee.$.construct.call(this, creatorId, color, canvas, doneCallback, ORYX.Plugins.Paint.PaintCanvas.Ellipse);
},
draw: function draw(canvas, start, end) {
canvas.setStyle(1, this.getColor());
canvas.drawEllipse(start.left, start.top, end.left, end.top);
}
});
ORYX.Plugins.Paint.PaintCanvas.Shape = Clazz.extend({
construct: function construct(creatorId, id) {
this.id = id || ORYX.Editor.provideId();
this.creatorId = creatorId;
}
});
ORYX.Plugins.Paint.PaintCanvas.Line = ORYX.Plugins.Paint.PaintCanvas.Shape.extend({
construct: function construct(creatorId, points, id) {
arguments.callee.$.construct.call(this, creatorId, id);
this.points = points.map(Object.clone);
},
draw: function draw(canvas, color, width) {
var lines = this._getLines(this._smooth(this.points));
canvas.setStyle(width || 1, color);
lines.each(function drawLine(l) {
canvas.drawLine(l.a.x, l.a.y, l.b.x, l.b.y);
});
},
move: function move(x, y) {
this.points.each(function movePoint(p) {
p.x += x;
p.y += y;
});
},
isUnderCursor: function isUnderCursor(pos) {
var lines = this._getLines(this.points);
return lines.any(function isInLine(l) {
return ORYX.Core.Math.isPointInLine(pos.left, pos.top, l.a.x, l.a.y, l.b.x, l.b.y, 10);
});
},
pack: function pack() {
return {
id: this.id,
type: "Line",
creatorId: this.creatorId,
points: this.points
};
},
unpack: function unpack(obj) {
return new ORYX.Plugins.Paint.PaintCanvas.Line(obj.creatorId, obj.points, obj.id);
},
_getLines: function _getLines(points) {
var lines = [];
for (var i = 1; i < points.length; i++) {
lines.push({ a: points[i-1],
b: points[i] });
}
return lines;
},
_smooth: function _smooth(points) {
return this._mcMaster(this._fillPoints(points, 5));
},
_fillPoints: function _fillPoints(points, maxDist) {
var out = [points[0]];
for (var i = 1; i < points.length; i++) {
var pos = points[i];
var prevPos = points[i-1];
var distX = pos.x - prevPos.x;
var distY = pos.y - prevPos.y;
var dist = Math.sqrt(distX*distX + distY*distY);
if (dist > maxDist) {
var pointsToInsert = Math.floor(dist / maxDist);
var deltaX = distX / pointsToInsert;
var deltaY = distY / pointsToInsert;
for (var k = 0; k < pointsToInsert; k++) {
out.push({x: prevPos.x + k * deltaX,
y: prevPos.y + k * deltaY });
}
}
out.push(pos);
}
return out;
},
_mcMaster: function _mcMaster(points) {
var out = [];
var lookAhead = 10;
var halfLookAhead = Math.floor(lookAhead / 2);
if (points.length < lookAhead) {
return points;
}
for (var i = points.length - 1; i >= 0; i--) {
if (i >= points.length - halfLookAhead || i <= halfLookAhead) {
out = [points[i]].concat(out);
} else {
var accX = 0, accY = 0;
for (var k = -halfLookAhead; k < -halfLookAhead + lookAhead; k++) {
accX += points[i + k].x;
accY += points[i + k].y;
}
out = [{x: accX / lookAhead,
y: accY / lookAhead}].concat(out);
}
}
return out;
}
});
ORYX.Plugins.Paint.PaintCanvas.TwoPointShape = ORYX.Plugins.Paint.PaintCanvas.Shape.extend({
construct: function construct(creatorId, start, end, id) {
arguments.callee.$.construct.call(this, creatorId, id);
this.start = start;
this.end = end;
},
move: function move(x, y) {
var movePoint = function movePoint(p) {
p.left += x;
p.top += y;
};
movePoint(this.start);
movePoint(this.end);
},
abstractPack: function abstractPack(typeName) {
return {
id: this.id,
type: typeName,
creatorId: this.creatorId,
start: this.start,
end: this.end
};
},
abstractUnpack: function abstractUnpack(shapeClass, obj) {
return new shapeClass(obj.creatorId, obj.start, obj.end, obj.id);
}
});
ORYX.Plugins.Paint.PaintCanvas.Arrow = ORYX.Plugins.Paint.PaintCanvas.TwoPointShape.extend({
construct: function construct(creatorId, start, end, id) {
arguments.callee.$.construct.apply(this, arguments);
},
draw: function draw(canvas, color, width) {
canvas.setStyle(width || 1, color);
canvas.drawArrow(this.start.left, this.start.top, this.end.left, this.end.top);
},
isUnderCursor: function isUnderCursor(pos) {
return ORYX.Core.Math.isPointInLine(pos.left, pos.top, this.start.left, this.start.top, this.end.left, this.end.top, 10);
},
pack: function pack() {
return this.abstractPack("Arrow");
},
unpack: function unpack(obj) {
return this.abstractUnpack(ORYX.Plugins.Paint.PaintCanvas.Arrow, obj);
}
});
ORYX.Plugins.Paint.PaintCanvas.Box = ORYX.Plugins.Paint.PaintCanvas.TwoPointShape.extend({
construct: function construct(creatorId, start, end, id) {
arguments.callee.$.construct.apply(this, arguments);
},
draw: function draw(canvas, color, width) {
canvas.setStyle(width || 1, color);
canvas.strokeRect(this.start.left, this.start.top, this.end.left - this.start.left, this.end.top - this.start.top);
},
isUnderCursor: function isUnderCursor(pos) {
var hitHorizontal1 = ORYX.Core.Math.isPointInLine(pos.left, pos.top, this.start.left, this.start.top, this.end.left, this.start.top, 10);
var hitHorizontal2 = ORYX.Core.Math.isPointInLine(pos.left, pos.top, this.start.left, this.end.top, this.end.left, this.end.top, 10);
var hitVertical1 = ORYX.Core.Math.isPointInLine(pos.left, pos.top, this.start.left, this.start.top, this.start.left, this.end.top, 10);
var hitVertical2 = ORYX.Core.Math.isPointInLine(pos.left, pos.top, this.end.left, this.start.top, this.end.left, this.end.top, 10);
return hitHorizontal1 || hitHorizontal2 || hitVertical1 || hitVertical2;
},
pack: function pack() {
return this.abstractPack("Box");
},
unpack: function unpack(obj) {
return this.abstractUnpack(ORYX.Plugins.Paint.PaintCanvas.Box, obj);
}
});
ORYX.Plugins.Paint.PaintCanvas.Ellipse = ORYX.Plugins.Paint.PaintCanvas.TwoPointShape.extend({
construct: function construct(creatorId, start, end, id) {
var upperLeft = {
left: Math.min(start.left, end.left),
top: Math.min(start.top, end.top)
};
var lowerRight = {
left: Math.max(start.left, end.left),
top: Math.max(start.top, end.top)
};
arguments.callee.$.construct.call(this, creatorId, upperLeft, lowerRight, id);
var rx = (lowerRight.left - upperLeft.left)/2;
var ry = (lowerRight.top - upperLeft.top)/2;
var cx = upperLeft.left + rx;
var cy = upperLeft.top + ry;
this.isUnderCursor = function isUnderCursor(pos) {
var insideInner = false;
if (rx > 5 && ry > 5) {
insideInner = ORYX.Core.Math.isPointInEllipse(pos.left, pos.top, cx, cy, rx - 5, ry - 5);
}
return !insideInner && ORYX.Core.Math.isPointInEllipse(pos.left, pos.top, cx, cy, rx + 10, ry + 10);
};
},
draw: function draw(canvas, color, width) {
canvas.setStyle(width || 1, color);
canvas.drawEllipse(this.start.left, this.start.top, this.end.left, this.end.top);
},
pack: function pack() {
return this.abstractPack("Ellipse");
},
unpack: function unpack(obj) {
return this.abstractUnpack(ORYX.Plugins.Paint.PaintCanvas.Ellipse, obj);
}
});
ORYX.Plugins.Paint.PaintCanvas.ShapeExistenceCommand = ORYX.Core.AbstractCommand.extend({
construct: function construct(shape, facade) {
arguments.callee.$.construct.call(this, facade);
this.metadata.putOnStack = false;
this.shape = shape;
},
getCommandData: function getCommandData() {
return {
"shape": this.shape.pack()
};
},
abstractCreateFromCommandData: function abstractCreateFromCommandData(commandName, facade, commandObject) {
var shape = ORYX.Plugins.Paint.PaintCanvas[commandObject.shape.type].prototype.unpack(commandObject.shape);
return new ORYX.Core.Commands[commandName](shape, facade);
},
getAffectedShapes: function getAffectedShapes() {
return [];
},
createShape: function createShape() {
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_PAINT_NEWSHAPE,
shape: this.shape
});
},
deleteShape: function deleteShape() {
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_PAINT_REMOVESHAPE,
shapeId: this.shape.id
});
}
});
ORYX.Core.Commands["Paint.DrawCommand"] = ORYX.Plugins.Paint.PaintCanvas.ShapeExistenceCommand.extend({
construct: function construct(shape, facade) {
arguments.callee.$.construct.apply(this, arguments);
},
createFromCommandData: function createFromCommandData(facade, commandObject) {
return this.abstractCreateFromCommandData("Paint.DrawCommand", facade, commandObject);
},
getCommandName: function getCommandName() {
return "Paint.DrawCommand";
},
getDisplayName: function getDisplayName() {
return "Drew on paint layer";
},
execute: function execute() {
this.createShape();
},
rollback: function rollback() {
this.deleteShape();
}
});
ORYX.Core.Commands["Paint.RemoveCommand"] = ORYX.Plugins.Paint.PaintCanvas.ShapeExistenceCommand.extend({
construct: function construct(shape, facade) {
arguments.callee.$.construct.apply(this, arguments);
},
createFromCommandData: function createFromCommandData(facade, commandObject) {
return this.abstractCreateFromCommandData("Paint.RemoveCommand", facade, commandObject);
},
getCommandName: function getCommandName() {
return "Paint.RemoveCommand";
},
getDisplayName: function getDisplayName() {
return "Erased something from paint layer";
},
execute: function execute() {
this.deleteShape();
},
rollback: function rollback() {
this.createShape();
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/paint.js | JavaScript | mit | 44,028 |
/**
* 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.FarbrauschAfterglow = Clazz.extend({
excludedTags: Array.from(["defs", "text", "g", "a"]),
highlightClass: "highlight",
highlightIdAttribute: "highlight-id",
finalStrokeAttribute: "final-stroke",
finalStrokeWidthAttribute: "final-stroke-width",
finalFillAttribute: "final-fill",
millisecondsForStep: 40,
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());
if (!shape.lastChangeWasLocal()) {
this.showAfterglow(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;
},
showAfterglow: function showAfterglow(color, shape) {
var i;
var svgNode = shape.node;
var defsNode = this.facade.getCanvas().getDefsNode();
var highlightId = ORYX.Editor.provideId();
var highlightNodes = this.getHighlightNodes(shape, defsNode);
var highlightMarkers = this.getHighlightMarkersById(defsNode, shape.id);
var startStrokeWidth = 3;
for (i = 0; i < highlightNodes.length; i++) {
var highlightNode = highlightNodes[i];
highlightNode.setAttribute(this.highlightIdAttribute, highlightId);
this.setFinalStrokeAttributes(highlightNode);
this.fadeHighlight(highlightNode, highlightId, color, startStrokeWidth, 3000);
}
for (i = 0; i < highlightMarkers.length; i++) {
var isMarker = true;
var highlightMarker = highlightMarkers[i];
highlightMarker.setAttribute(this.highlightIdAttribute, highlightId);
this.setFinalStrokeAttributes(highlightMarker);
this.setFinalFillAttribute(highlightMarker);
this.fadeHighlight(highlightMarker, highlightId, color, startStrokeWidth, 3000, isMarker);
}
},
getHighlightNodes: function getHighlightNodes(shape, defsNode) {
var svgNode = shape.node;
var highlightNodes = Array.from(svgNode.getElementsByClassName("highlight"));
return highlightNodes;
},
getHighlightMarkersById: function getHighlightMarkersById(defsNode, id) {
var allHighlightMarkers = Array.from(defsNode.getElementsByClassName("highlight"));
var highlightMarkers = [];
for (var i = 0; i < allHighlightMarkers.length; i++) {
var currentHighlightMarker = allHighlightMarkers[i];
if (currentHighlightMarker.id.indexOf(id) !== -1) {
highlightMarkers.push(currentHighlightMarker);
}
}
return highlightMarkers;
},
setFinalStrokeAttributes: function setFinalStrokeAttributes(highlightNode) {
var finalStroke = highlightNode.getAttribute(this.finalStrokeAttribute);
if (finalStroke === null) {
finalStroke = highlightNode.getAttribute("stroke");
highlightNode.setAttribute(this.finalStrokeAttribute, finalStroke);
}
var finalStrokeWidth = highlightNode.getAttribute(this.finalStrokeWidthAttribute);
if (finalStrokeWidth === null) {
finalStrokeWidth = highlightNode.getAttribute("stroke-width") || "1";
highlightNode.setAttribute(this.finalStrokeWidthAttribute, finalStrokeWidth);
}
},
setFinalFillAttribute: function setFinalFillAttribute(highlightMarker) {
var finalFill = highlightMarker.getAttribute(this.finalFillAttribute);
if (finalFill === null) {
finalFill = highlightMarker.getAttribute("fill") || "#000000";
highlightMarker.setAttribute(this.finalFillAttribute, finalFill);
}
},
fadeHighlight: function fadeHighlight(highlightNode, highlightId, startStroke, startStrokeWidth, animationTime, isMarker, passedMilliseconds) {
var currentHighlightId = highlightNode.getAttribute(this.highlightIdAttribute);
// shape not visible or other animation running on shape, cancel this one
if ((highlightNode.getAttribute("visibility") === "hidden") || (currentHighlightId !== highlightId)) {
return;
}
if (typeof passedMilliseconds === "undefined") {
passedMilliseconds = 0;
}
if (isMarker !== true) {
isMarker = false;
}
if (animationTime > passedMilliseconds) {
// Animation in progress
var fraction = passedMilliseconds / animationTime;
this.fadeStroke(highlightNode, startStroke, fraction);
this.fadeStrokeWidth(highlightNode, startStrokeWidth, fraction);
if (isMarker) {
this.fadeFill(highlightNode, startStroke, fraction);
}
var callback = function() {
this.fadeHighlight(highlightNode, highlightId, startStroke, startStrokeWidth, animationTime, isMarker, passedMilliseconds + this.millisecondsForStep);
}.bind(this);
setTimeout(callback, this.millisecondsForStep);
} else {
// Animation expired set to finalValues
highlightNode.setAttribute("stroke", highlightNode.getAttribute(this.finalStrokeAttribute));
highlightNode.setAttribute("stroke-width", highlightNode.getAttribute(this.finalStrokeWidthAttribute));
if (isMarker) {
highlightNode.setAttribute("fill", highlightNode.getAttribute(this.finalFillAttribute));
}
}
},
fadeStroke: function fadeStroke(highlightNode, startStroke, fraction) {
var finalStroke = highlightNode.getAttribute(this.finalStrokeAttribute);
// stroke is not visible, so do not fade
if ((finalStroke === null) || (finalStroke === "none")) {
return;
}
var interpolatedStroke = this.interpolateColor(startStroke, finalStroke, fraction);
highlightNode.setAttribute("stroke", interpolatedStroke);
},
fadeStrokeWidth: function fadeStrokeWidth(highlightNode, startStrokeWidth, fraction) {
var finalStrokeWidth = parseInt(highlightNode.getAttribute(this.finalStrokeWidthAttribute), 10);
// stroke is not visible, so do not fade
if (finalStrokeWidth === 0) {
return;
}
var strokeWidth = finalStrokeWidth + (1 - fraction) * (startStrokeWidth - finalStrokeWidth);
highlightNode.setAttribute("stroke-width", strokeWidth);
},
fadeFill: function fadeStroke(highlightNode, startFill, fraction) {
var finalFill = highlightNode.getAttribute(this.finalFillAttribute);
// fill color is not visible, so do not fade
if ((finalFill === null) || (finalFill === "none")) {
return;
}
var interpolatedFill = this.interpolateColor(startFill, finalFill, fraction);
highlightNode.setAttribute("fill", interpolatedFill);
},
interpolateColor: function interpolateColor(startColor, finalColor, fraction) {
var startColorRgb = this.getRgbColor(startColor);
var finalColorRgb = this.getRgbColor(finalColor);
var interpolatedColorRgb = {};
interpolatedColorRgb["r"] = startColorRgb["r"] + parseInt(fraction * (finalColorRgb["r"] - startColorRgb["r"]), 10);
interpolatedColorRgb["g"] = startColorRgb["g"] + parseInt(fraction * (finalColorRgb["g"] - startColorRgb["g"]), 10);
interpolatedColorRgb["b"] = startColorRgb["b"] + parseInt(fraction * (finalColorRgb["b"] - startColorRgb["b"]), 10);
return this.getHexColor(interpolatedColorRgb);
},
getRgbColor: function getRgbColor(hexColorString) {
var rgbValue = {};
rgbValue["r"] = parseInt(hexColorString.substring(1, 3), 16);
rgbValue["g"] = parseInt(hexColorString.substring(3, 5), 16);
rgbValue["b"] = parseInt(hexColorString.substring(5, 7), 16);
return rgbValue;
},
getHexColor: function getHexColor(rgbColorHash) {
// If statements fill the color strings with leading zeroes
var red = rgbColorHash["r"].toString(16);
if (red.length === 1) {
red = "0" + red;
}
var green = rgbColorHash["g"].toString(16);
if (green.length === 1) {
green = "0" + green;
}
var blue = rgbColorHash["b"].toString(16);
if (blue.length === 1) {
blue = "0" + blue;
}
var hexColor = "#" + red + green + blue;
return hexColor;
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/farbrausch_afterglow.js | JavaScript | mit | 10,820 |
/**
* 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["DragDocker.DragDockerCommand"] = ORYX.Core.AbstractCommand.extend({
construct: function construct(docker, newPos, oldPos, newDockedShape, oldDockedShape, facade){
// call construct method of parent
arguments.callee.$.construct.call(this, facade);
this.docker = docker;
this.index = docker.parent.dockers.indexOf(docker);
this.newPosition = newPos;
this.oldPosition = oldPos;
this.newDockedShape = newDockedShape;
this.oldDockedShape = oldDockedShape;
this.facade = facade;
this.index = docker.parent.dockers.indexOf(docker);
this.shape = docker.parent;
},
getAffectedShapes: function getAffectedShapes() {
return [this.shape];
},
getCommandName: function getCommandName() {
return "DragDocker.DragDockerCommand";
},
getDisplayName: function getDisplayName() {
return "Docker moved";
},
getCommandData: function getCommandData() {
var getId = function(shape) {
if (typeof shape !== "undefined") {
return shape.resourceId
}
};
var commandData = {
"dockerId": this.docker.id,
"index": this.index,
"newPosition": this.newPosition,
"oldPosition": this.oldPosition,
"newDockedShapeId": getId(this.newDockedShape),
"oldDockedShapeId": getId(this.oldDockedShape),
"shapeId": getId(this.shape)
};
return commandData;
},
createFromCommandData: function createFromCommandData(facade, commandData) {
var canvas = facade.getCanvas();
var getShape = canvas.getChildShapeByResourceId.bind(canvas);
var newDockedShape = getShape(commandData.newDockedShapeId);
if (typeof commandData.newDockedShapeId !== 'undefined' && typeof newDockedShape === 'undefined') {
// Trying to dock to a shape that doesn't exist anymore.
return undefined;
}
var oldDockedShape = getShape(commandData.oldDockedShapeId);
var shape = getShape(commandData.shapeId);
if (typeof shape === 'undefined') {
// Trying to move a docker of a shape that doesn't exist anymore.
return undefined;
}
var docker;
for (var i = 0; i < shape.dockers.length; i++) {
if (shape.dockers[i].id == commandData.dockerId) {
docker = shape.dockers[i];
}
}
return new ORYX.Core.Commands["DragDocker.DragDockerCommand"](docker, commandData.newPosition, commandData.oldPosition, newDockedShape, oldDockedShape, facade);
},
execute: function execute(){
if (typeof this.docker !== "undefined") {
if (!this.docker.parent){
this.docker = this.shape.dockers[this.index];
}
this.dock( this.newDockedShape, this.newPosition );
// TODO locally deleting dockers might create inconsistent states across clients
//this.removedDockers = this.shape.removeUnusedDockers();
this.facade.updateSelection(this.isLocal());
}
},
rollback: function rollback(){
if (typeof this.docker !== "undefined") {
this.dock( this.oldDockedShape, this.oldPosition );
(this.removedDockers||$H({})).each(function(d){
this.shape.add(d.value, Number(d.key));
this.shape._update(true);
}.bind(this))
this.facade.updateSelection(this.isLocal());
}
},
dock: function dock(toDockShape, relativePosition){
var relativePos = relativePosition;
if (typeof toDockShape !== "undefined") {
/* if docker 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.5 and y = 0.5, shape will be docked at center*/
var absolutePosition = this.facade.getCanvas().node.ownerSVGElement.createSVGPoint();
if ((0 > relativePos.x) || (relativePos.x > 1) || (0 > relativePos.y) || (relativePos.y > 1)) {
relativePos.x = 0.5;
relativePos.y = 0.5;
}
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;
}
//it seems that for docker to be moved, the dockedShape need to be cleared first
this.docker.setDockedShape(undefined);
//this.docker.setReferencePoint(absolutePosition);
this.docker.bounds.centerMoveTo(absolutePosition);
this.docker.setDockedShape(toDockShape);
this.docker.update();
this.docker.parent._update();
this.facade.getCanvas().update();
}
});
ORYX.Plugins.DragDocker = Clazz.extend({
/**
* Constructor
* @param {Object} Facade: The Facade of the Editor
*/
construct: function(facade) {
this.facade = facade;
// Set the valid and invalid color
this.VALIDCOLOR = ORYX.CONFIG.SELECTION_VALID_COLOR;
this.INVALIDCOLOR = ORYX.CONFIG.SELECTION_INVALID_COLOR;
// Define Variables
this.shapeSelection = undefined;
this.docker = undefined;
this.dockerParent = undefined;
this.dockerSource = undefined;
this.dockerTarget = undefined;
this.lastUIObj = undefined;
this.isStartDocker = undefined;
this.isEndDocker = undefined;
this.undockTreshold = 10;
this.initialDockerPosition = undefined;
this.outerDockerNotMoved = undefined;
this.isValid = false;
// For the Drag and Drop
// Register on MouseDown-Event on a Docker
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MOUSEDOWN, this.handleMouseDown.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_DOCKERDRAG, this.handleDockerDrag.bind(this));
// Register on over/out to show / hide a docker
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MOUSEOVER, this.handleMouseOver.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MOUSEOUT, this.handleMouseOut.bind(this));
},
/**
* DockerDrag Handler
* delegates the uiEvent of the drag event to the mouseDown function
*/
handleDockerDrag: function handleDockerDrag(event, uiObj) {
this.handleMouseDown(event.uiEvent, uiObj);
},
/**
* MouseOut Handler
*
*/
handleMouseOut: function(event, uiObj) {
// If there is a Docker, hide this
if(!this.docker && uiObj instanceof ORYX.Core.Controls.Docker) {
uiObj.hide()
} else if(!this.docker && uiObj instanceof ORYX.Core.Edge) {
uiObj.dockers.each(function(docker){
docker.hide();
})
}
},
/**
* MouseOver Handler
*
*/
handleMouseOver: function(event, uiObj) {
// If there is a Docker, show this
if(!this.docker && uiObj instanceof ORYX.Core.Controls.Docker) {
uiObj.show()
} else if(!this.docker && uiObj instanceof ORYX.Core.Edge) {
uiObj.dockers.each(function(docker){
docker.show();
})
}
},
/**
* MouseDown Handler
*
*/
handleMouseDown: function(event, uiObj) {
// If there is a Docker
if(uiObj instanceof ORYX.Core.Controls.Docker && uiObj.isMovable) {
/* Buffering shape selection and clear selection*/
this.shapeSelection = this.facade.getSelection();
this.facade.setSelection();
this.docker = uiObj;
this.initialDockerPosition = this.docker.bounds.center();
this.outerDockerNotMoved = false;
this.dockerParent = uiObj.parent;
// Define command arguments
this._commandArg = {docker:uiObj, dockedShape:uiObj.getDockedShape(), refPoint:uiObj.referencePoint || uiObj.bounds.center()};
// Show the Docker
this.docker.show();
// If the Dockers Parent is an Edge,
// and the Docker is either the first or last Docker of the Edge
if(uiObj.parent instanceof ORYX.Core.Edge &&
(uiObj.parent.dockers.first() == uiObj || uiObj.parent.dockers.last() == uiObj)) {
// Get the Edge Source or Target
if(uiObj.parent.dockers.first() == uiObj && uiObj.parent.dockers.last().getDockedShape()) {
this.dockerTarget = uiObj.parent.dockers.last().getDockedShape()
} else if(uiObj.parent.dockers.last() == uiObj && uiObj.parent.dockers.first().getDockedShape()) {
this.dockerSource = uiObj.parent.dockers.first().getDockedShape()
}
} else {
// If there parent is not an Edge, undefined the Source and Target
this.dockerSource = undefined;
this.dockerTarget = undefined;
}
this.isStartDocker = this.docker.parent.dockers.first() === this.docker
this.isEndDocker = this.docker.parent.dockers.last() === this.docker
// add to canvas while dragging
this.facade.getCanvas().add(this.docker.parent);
// Hide all Labels from Docker
this.docker.parent.getLabels().each(function(label) {
label.hide();
});
// Undocked the Docker from current Shape
if ((!this.isStartDocker && !this.isEndDocker) || !this.docker.isDocked()) {
this.docker.setDockedShape(undefined)
// Set the Docker to the center of the mouse pointer
var evPos = this.facade.eventCoordinates(event);
this.docker.bounds.centerMoveTo(evPos);
//this.docker.update()
//this.facade.getCanvas().update();
this.dockerParent._update();
} else {
this.outerDockerNotMoved = true;
}
var option = {movedCallback: this.dockerMoved.bind(this), upCallback: this.dockerMovedFinished.bind(this)}
// Enable the Docker for Drag'n'Drop, give the mouseMove and mouseUp-Callback with
ORYX.Core.UIEnableDrag(event, uiObj, option);
}
},
/**
* Docker MouseMove Handler
*
*/
dockerMoved: function(event) {
this.outerDockerNotMoved = false;
var snapToMagnet = undefined;
if (this.docker.parent) {
if (this.isStartDocker || this.isEndDocker) {
// Get the EventPosition and all Shapes on these point
var evPos = this.facade.eventCoordinates(event);
if(this.docker.isDocked()) {
/* Only consider start/end dockers if they are moved over a treshold */
var distanceDockerPointer =
ORYX.Core.Math.getDistancePointToPoint(evPos, this.initialDockerPosition);
if(distanceDockerPointer < this.undockTreshold) {
this.outerDockerNotMoved = true;
return;
}
/* Undock the docker */
this.docker.setDockedShape(undefined)
// Set the Docker to the center of the mouse pointer
//this.docker.bounds.centerMoveTo(evPos);
this.dockerParent._update();
}
var shapes = this.facade.getCanvas().getAbstractShapesAtPosition(evPos);
// Get the top level Shape on these, but not the same as Dockers parent
var uiObj = shapes.pop();
if (this.docker.parent === uiObj) {
uiObj = shapes.pop();
}
// If the top level Shape the same as the last Shape, then return
if (this.lastUIObj == uiObj) {
//return;
// If the top level uiObj instance of Shape and this isn't the parent of the docker
}
else
if (uiObj instanceof ORYX.Core.Shape) {
// Get the StencilSet of the Edge
var sset = this.docker.parent.getStencil().stencilSet();
// Ask by the StencilSet if the source, the edge and the target valid connections.
if (this.docker.parent instanceof ORYX.Core.Edge) {
var highestParent = this.getHighestParentBeforeCanvas(uiObj);
/* Ensure that the shape to dock is not a child shape
* of the same edge.
*/
if(highestParent instanceof ORYX.Core.Edge
&& this.docker.parent === highestParent) {
this.isValid = false;
this.dockerParent._update();
return;
}
this.isValid = false;
var curObj = uiObj, orgObj = uiObj;
while(!this.isValid && curObj && !(curObj instanceof ORYX.Core.Canvas)){
uiObj = curObj;
this.isValid = this.facade.getRules().canConnect({
sourceShape: this.dockerSource ? // Is there a docked source
this.dockerSource : // than set this
(this.isStartDocker ? // if not and if the Docker is the start docker
uiObj : // take the last uiObj
undefined), // if not set it to undefined;
edgeShape: this.docker.parent,
targetShape: this.dockerTarget ? // Is there a docked target
this.dockerTarget : // than set this
(this.isEndDocker ? // if not and if the Docker is not the start docker
uiObj : // take the last uiObj
undefined) // if not set it to undefined;
});
curObj = curObj.parent;
}
// Reset uiObj if no
// valid parent is found
if (!this.isValid){
uiObj = orgObj;
}
}
else {
this.isValid = this.facade.getRules().canConnect({
sourceShape: uiObj,
edgeShape: this.docker.parent,
targetShape: this.docker.parent
});
}
// If there is a lastUIObj, hide the magnets
if (this.lastUIObj) {
this.hideMagnets(this.lastUIObj)
}
// If there is a valid connection, show the magnets
if (this.isValid) {
this.showMagnets(uiObj)
}
// Set the Highlight Rectangle by these value
this.showHighlight(uiObj, this.isValid ? this.VALIDCOLOR : this.INVALIDCOLOR);
// Buffer the current Shape
this.lastUIObj = uiObj;
}
else {
// If there is no top level Shape, then hide the highligting of the last Shape
this.hideHighlight();
this.lastUIObj ? this.hideMagnets(this.lastUIObj) : null;
this.lastUIObj = undefined;
this.isValid = false;
}
// Snap to the nearest Magnet
if (this.lastUIObj && this.isValid && !(event.shiftKey || event.ctrlKey)) {
snapToMagnet = this.lastUIObj.magnets.find(function(magnet){
return magnet.absoluteBounds().isIncluded(evPos)
});
if (snapToMagnet) {
this.docker.bounds.centerMoveTo(snapToMagnet.absoluteCenterXY());
//this.docker.update()
}
}
}
}
// Snap to on the nearest Docker of the same parent
if(!(event.shiftKey || event.ctrlKey) && !snapToMagnet) {
var minOffset = ORYX.CONFIG.DOCKER_SNAP_OFFSET;
var nearestX = minOffset + 1
var nearestY = minOffset + 1
var dockerCenter = this.docker.bounds.center();
if (this.docker.parent) {
this.docker.parent.dockers.each((function(docker){
if (this.docker == docker) {
return
};
var center = docker.referencePoint ? docker.getAbsoluteReferencePoint() : docker.bounds.center();
nearestX = Math.abs(nearestX) > Math.abs(center.x - dockerCenter.x) ? center.x - dockerCenter.x : nearestX;
nearestY = Math.abs(nearestY) > Math.abs(center.y - dockerCenter.y) ? center.y - dockerCenter.y : nearestY;
}).bind(this));
if (Math.abs(nearestX) < minOffset || Math.abs(nearestY) < minOffset) {
nearestX = Math.abs(nearestX) < minOffset ? nearestX : 0;
nearestY = Math.abs(nearestY) < minOffset ? nearestY : 0;
this.docker.bounds.centerMoveTo(dockerCenter.x + nearestX, dockerCenter.y + nearestY);
//this.docker.update()
} else {
var previous = this.docker.parent.dockers[Math.max(this.docker.parent.dockers.indexOf(this.docker)-1, 0)]
var next = this.docker.parent.dockers[Math.min(this.docker.parent.dockers.indexOf(this.docker)+1, this.docker.parent.dockers.length-1)]
if (previous && next && previous !== this.docker && next !== this.docker){
var cp = previous.bounds.center();
var cn = next.bounds.center();
var cd = this.docker.bounds.center();
// Checks if the point is on the line between previous and next
if (ORYX.Core.Math.isPointInLine(cd.x, cd.y, cp.x, cp.y, cn.x, cn.y, 10)) {
// Get the rise
var raise = (Number(cn.y)-Number(cp.y))/(Number(cn.x)-Number(cp.x));
// Calculate the intersection point
var intersecX = ((cp.y-(cp.x*raise))-(cd.y-(cd.x*(-Math.pow(raise,-1)))))/((-Math.pow(raise,-1))-raise);
var intersecY = (cp.y-(cp.x*raise))+(raise*intersecX);
if(isNaN(intersecX) || isNaN(intersecY)) {return;}
this.docker.bounds.centerMoveTo(intersecX, intersecY);
}
}
}
}
}
//this.facade.getCanvas().update();
this.dockerParent._update();
},
/**
* Docker MouseUp Handler
*
*/
dockerMovedFinished: function(event) {
// check if parent edge still exists on canvas, skip if not
var currentShape = this.facade.getCanvas().getChildShapeByResourceId(this.dockerParent.resourceId);
if (typeof currentShape !== "undefined") {
/* Reset to buffered shape selection */
this.facade.setSelection(this.shapeSelection);
// Hide the border
this.hideHighlight();
// Show all Labels from Docker
this.dockerParent.getLabels().each(function(label){
label.show();
//label.update();
});
// If there is a last top level Shape
if(this.lastUIObj && (this.isStartDocker || this.isEndDocker)){
// If there is a valid connection, the set as a docked Shape to them
if(this.isValid) {
this.docker.setDockedShape(this.lastUIObj);
this.facade.raiseEvent({
type :ORYX.CONFIG.EVENT_DRAGDOCKER_DOCKED,
docker : this.docker,
parent : this.docker.parent,
target : this.lastUIObj
});
}
this.hideMagnets(this.lastUIObj)
}
// Hide the Docker
this.docker.hide();
if(this.outerDockerNotMoved) {
// Get the EventPosition and all Shapes on these point
var evPos = this.facade.eventCoordinates(event);
var shapes = this.facade.getCanvas().getAbstractShapesAtPosition(evPos);
/* Remove edges from selection */
var shapeWithoutEdges = shapes.findAll(function(node) {
return node instanceof ORYX.Core.Node;
});
shapes = shapeWithoutEdges.length ? shapeWithoutEdges : shapes;
this.facade.setSelection(shapes);
} else {
if (this.docker.parent){
var oldDockedShape = this._commandArg.dockedShape;
var newPositionAbsolute = this.docker.bounds.center();
var oldPositionAbsolute = this._commandArg.refPoint;
var newDockedShape = this.docker.getDockedShape();
if (typeof newDockedShape !== "undefined") {
var newPositionRelative = this.facade.getCanvas().node.ownerSVGElement.createSVGPoint();
newPositionRelative.x = Math.abs((newDockedShape.bounds.lowerRight().x - newPositionAbsolute.x) / newDockedShape.bounds.width());
newPositionRelative.y = Math.abs((newDockedShape.bounds.lowerRight().y - newPositionAbsolute.y) / newDockedShape.bounds.height());
} else {
// if newDockedShape is not defined, i.e. it is the canvas, use absolutePositions, because positions relative to the canvas are absolute
newPositionRelative = newPositionAbsolute;
}
if (typeof oldDockedShape !== "undefined") {
var oldPositionRelative = this.facade.getCanvas().node.ownerSVGElement.createSVGPoint();
oldPositionRelative.x = Math.abs((oldDockedShape.bounds.lowerRight().x - oldPositionAbsolute.x) / oldDockedShape.bounds.width());
oldPositionRelative.y = Math.abs((oldDockedShape.bounds.lowerRight().y - oldPositionAbsolute.y) / oldDockedShape.bounds.height());
} else {
// if oldDockedShape is not defined, i.e. it is the canvas, use absolutePositions, because positions relative to the canvas are absolute
oldPositionRelative = oldPositionAbsolute;
}
// instanciate the dockCommand
var command = new ORYX.Core.Commands["DragDocker.DragDockerCommand"](this.docker, newPositionRelative, oldPositionRelative, newDockedShape, oldDockedShape, this.facade);
this.facade.executeCommands([command]);
}
}
}
// Update all Shapes
//this.facade.updateSelection();
// Undefined all variables
this.docker = undefined;
this.dockerParent = undefined;
this.dockerSource = undefined;
this.dockerTarget = undefined;
this.lastUIObj = undefined;
},
/**
* Hide the highlighting
*/
hideHighlight: function() {
this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_HIGHLIGHT_HIDE, highlightId:'validDockedShape'});
},
/**
* Show the highlighting
*
*/
showHighlight: function(uiObj, color) {
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_HIGHLIGHT_SHOW,
highlightId:'validDockedShape',
elements: [uiObj],
color: color
});
},
showMagnets: function(uiObj){
uiObj.magnets.each(function(magnet) {
magnet.show();
});
},
hideMagnets: function(uiObj){
uiObj.magnets.each(function(magnet) {
magnet.hide();
});
},
getHighestParentBeforeCanvas: function(shape) {
if(!(shape instanceof ORYX.Core.Shape)) {return undefined;}
var parent = shape.parent;
while(parent && !(parent.parent instanceof ORYX.Core.Canvas)) {
parent = parent.parent;
}
return parent;
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/dragDocker.js | JavaScript | mit | 23,800 |
/**
* 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.SideTabs =
{
construct: function construct(facade) {
this.facade = facade;
this.showCallbacks = {};
this.tabWidth = 233;
this.sidebar = document.createElement('div');
this.sidebar.setAttribute('id', 'pwave-tabbar');
this.sidebar.appendChild(document.createElement('ul'));
jQuery(this.sidebar)
.tabs({collapsible: true})
.removeClass('ui-corner-all');
jQuery(this.sidebar).children()
.removeClass('ui-corner-bottom')
.removeClass('ui-corner-top');
// Execute callback when tab is selected
jQuery(this.sidebar).bind('tabsshow', function(event, ui) {
if (typeof this.showCallbacks[ui.panel.id] === 'function') {
this.showCallbacks[ui.panel.id]();
}
}.bind(this));
jQuery(this.sidebar).bind('tabsadd', this._closeAllTabs.bind(this));
this.sidebarWrapper = document.createElement('div'); // used to position the bar fixed
this.sidebarWrapper.setAttribute('id', 'pwave-tabbar-wrapper');
this.sidebarWrapper.appendChild(this.sidebar);
this.canvasContainer = $$(".ORYX_Editor")[0].parentNode;
this.canvasContainer.appendChild(this.sidebarWrapper);
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_SIDEBAR_NEW_TAB, this.registerNewTab.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MODE_CHANGED, this._handleModeChanged.bind(this));
window.addEventListener("resize", this.handleWindowResize.bind(this), false);
this.facade.raiseEvent({
'type' : ORYX.CONFIG.EVENT_SIDEBAR_LOADED
});
},
registerNewTab: function registerNewTab(event) {
var tabObj = {
'tabid': event.tabid,
'title': event.tabTitle, // title text label for the new tab
'div': event.tabDivEl, // the HTML DIV Element to be rendered in the new tab
'order': event.tabOrder, // number determining the position in the tab list
'width': event.tabWidth, // dimensions for the new tab
'height': Math.max(150, event.tabHeight),
'displayHandler': event.displayHandler,
'storeRenameFunction': event.storeRenameFunction
};
jQuery(this.sidebar).tabs("add", "#tabs-" + tabObj.tabid, tabObj.title, tabObj.order);
var header = jQuery("<div>", {'class': 'pwave-tab-header'});
var headerHighlight = jQuery("<div>", {'class': 'pwave-tab-header-highlight'});
var headerLabel = jQuery("<div>", {'class': 'pwave-tab-header-label'}).html(tabObj.title);
var headerMinimize = jQuery("<div>", {'class': 'pwave-tab-header-minimize'});
jQuery(header).append(headerHighlight).append(headerLabel).append(headerMinimize);
jQuery(header).click(this._closeAllTabs.bind(this));
if (typeof tabObj.storeRenameFunction === 'function') {
tabObj.storeRenameFunction(function renameHeader(name) {
headerLabel.html(name);
});
}
var scrollContainer = jQuery("<div>", {
'class': 'scrollcontainer'
}).append(tabObj.div);
jQuery('#tabs-'+tabObj.tabid).append(header);
jQuery('#tabs-'+tabObj.tabid).append(scrollContainer);
this.showCallbacks['tabs-'+tabObj.tabid] = tabObj.displayHandler;
},
_handleModeChanged: function _handleModeChanged(event) {
if (event.mode.isEditMode()) {
this.sidebar.show();
} else {
this.sidebar.hide();
}
if (event.mode.isPaintMode()) {
this._closeAllTabs();
}
},
_closeAllTabs: function _closeAllTabs() {
if (jQuery(this.sidebar).tabs('option', 'selected') !== -1) {
jQuery(this.sidebar).tabs('select', -1);
}
},
handleWindowResize: function handleWindowResize() {
this.sidebarWrapper.style.bottom = 0 + this.getCanvasScrollbarOffsetForHeight() + 'px';
this.sidebarWrapper.style.right = 20 + this.getCanvasScrollbarOffsetForWidth() + 'px';
},
getCanvasScrollbarOffsetForWidth: function getCanvasScrollbarOffsetForWidth() {
return this.canvasContainer.offsetWidth - this.canvasContainer.clientWidth;
},
getCanvasScrollbarOffsetForHeight: function getCanvasScrollbarOffsetForHeight() {
return this.canvasContainer.offsetHeight - this.canvasContainer.clientHeight;
}
};
ORYX.Plugins.SideTabs = ORYX.Plugins.AbstractPlugin.extend(ORYX.Plugins.SideTabs);
| 08to09-processwave | oryx/editor/client/scripts/Plugins/sideTabs.js | JavaScript | mit | 6,211 |
/**
* 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.Farbrausch = Clazz.extend({
facade: undefined,
_userObjects: {},
_colorMapping: {},
_firstUpdateReceived: false,
_colorPalette: ["#cc0000",
"#33cc00",
"#ff9900",
"#9acd32",
"#0099cc",
"#000099",
"#336633",
"#cc00cc",
"#ffff66",
"#990066",
"#660000",
"#a9a9a9",
"#ffffff",
"#33ccff",
"#ff69b4",
"#ff9999",
"#2e8b57",
"#daa520"],
_defaultColor: "#000000",
construct: function construct(facade) {
this.facade = facade;
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_NEW_POST_MESSAGE_RECEIVED, this.handleNewPostMessageReceived.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MODE_CHANGED, this._handleModeChanged.bind(this));
},
_handleModeChanged: function _handleModeChanged(evt) {
if (evt.mode.isEditMode() && !(this.facade.getUserId() in this._colorMapping)) {
this.pickOwnColor();
}
},
pickOwnColor: function pickOwnColor() {
//it is possible that the mode_changed event arrives before the very first stateUpdated
//since we need the information of the stateUpdated-Callback, we have to wait
if (!this._firstUpdateReceived) {
setTimeout(this.pickOwnColor.bind(this), 1000 * Math.random());
return;
}
var selfId = this.facade.getUserId();
if (!(selfId in this._colorMapping)) {
this._saveColor(selfId, this._getNextFreeColor());
}
},
handleNewPostMessageReceived: function handleNewPostMessageReceived(event) {
var data = event.data;
if (data.target !== "farbrausch") {
return;
}
if (data.action === "update") {
this._firstUpdateReceived = true;
this._mergeColorMapping(data.message.mapping);
} else if (data.action === "participants") {
this._mergeParticipants(data.message.participants);
} else {
throw "Unknown farbrausch action: " + data.action;
}
this._raiseFarbrauschNewInfosEvent();
},
_mergeParticipants: function _mergeParticipants(participants) {
for (var i = 0; i < participants.length; i++) {
var participant = participants[i];
if (!this._userObjects.hasOwnProperty(participant.id)) {
this._userObjects[participant.id] = participant;
}
}
},
_mergeColorMapping: function _mergeColorMapping(mapping) {
var keys = this._getKeys(mapping);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
this._colorMapping[key] = mapping[key];
}
this._conflictHandling();
},
_raiseFarbrauschNewInfosEvent: function _raiseFarbrauschNewInfosEvent() {
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_FARBRAUSCH_NEW_INFOS,
users: this._getMergedColorMappingAndUserObjects(),
ownUserId: this.facade.getUserId()
});
},
_getMergedColorMappingAndUserObjects: function _getMergeColorMappingAndUserObjects() {
var eventData = {};
for (var key in this._colorMapping) {
if (this._colorMapping.hasOwnProperty(key) && this._userObjects.hasOwnProperty(key)) {
eventData[key] = {
id: this._userObjects[key].id,
thumbnailUrl: this._userObjects[key].thumbnailUrl,
displayName: this._userObjects[key].displayName,
color: this._colorMapping[key],
isCreator: this._userObjects[key].isCreator
};
}
}
return eventData;
},
_conflictHandling: function _conflictHandling() {
var selfId = this.facade.getUserId();
var ids = this._getKeys(this._colorMapping);
var selfColor = this._colorMapping[selfId];
if (selfColor === this._defaultColor) {
// No conflict resolution when default color.
return;
}
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
if (this._colorMapping[id] === selfColor && selfId < id) {
this._saveColor(selfId, this._getNextFreeColor());
break;
}
}
},
_saveColor: function _saveColor(userId, color) {
this._colorMapping[userId] = color;
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_POST_MESSAGE,
target: "farbrausch",
action: "setColor",
message: {
"id": userId,
"color": color
}
});
},
_getNextFreeColor: function _getNextFreeColor() {
var unusedColors = this._arrayDifference(this._colorPalette, this._getValues(this._colorMapping));
if (unusedColors.length !== 0) {
return unusedColors[0];
}
return this._defaultColor;
},
_getColor: function _getColor(index) {
if (index < this._colorPalette.length) {
return this._colorPalette[index];
}
return this._defaultColor;
},
_getKeys: function _getKeys(hash) {
var keys = [];
for(i in hash) {
if (hash.hasOwnProperty(i)) {
keys.push(i);
}
}
return keys;
},
_getValues: function _getValues(hash) {
var values = [];
for(i in hash) {
if (hash.hasOwnProperty(i)) {
values.push(hash[i]);
}
}
return values;
},
_arrayDifference: function _arrayDifference(a1, a2) {
var difference = [];
for (var i = 0; i < a1.length; i++) {
if (this._notIn(a1[i], a2)) {
difference.push(a1[i]);
}
}
return difference;
},
_notIn: function _notIn(element, array) {
for (var i = 0; i < array.length; i++) {
if (array[i] === element) {
return false;
}
}
return true;
}
}); | 08to09-processwave | oryx/editor/client/scripts/Plugins/farbrausch.js | JavaScript | mit | 8,262 |
/**
* 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.Toolbar = Clazz.extend({
facade: undefined,
plugs: [],
construct: function(facade, ownPluginData) {
this.facade = facade;
this.groupIndex = new Hash();
ownPluginData.properties.each((function(value){
if(value.group && value.index != undefined) {
this.groupIndex[value.group] = value.index
}
}).bind(this));
Ext.QuickTips.init();
this.buttons = [];
this.mode;
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_BUTTON_UPDATE, this.onButtonUpdate.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_AFTER_COMMANDS_EXECUTED, this.onAfterCommandsExecutedOrRollbacked.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_AFTER_COMMANDS_ROLLBACK, this.onAfterCommandsExecutedOrRollbacked.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MODE_CHANGED, this.handleModeChanged.bind(this));
},
/**
* Can be used to manipulate the state of a button.
* @example
* this.facade.raiseEvent({
* type: ORYX.CONFIG.EVENT_BUTTON_UPDATE,
* id: this.buttonId, // have to be generated before and set in the offer method
* pressed: true
* });
* @param {Object} event
*/
onButtonUpdate: function(event){
var button = this.buttons.find(function(button){
return button.id === event.id;
});
if(event.pressed !== undefined){
button.buttonInstance.toggle(event.pressed);
}
},
registryChanged: function(pluginsData) {
// Sort plugins by group and index
var newPlugs = pluginsData.sortBy((function(value) {
return ((this.groupIndex[value.group] != undefined ? this.groupIndex[value.group] : "" ) + value.group + "" + value.index).toLowerCase();
}).bind(this));
var plugs = $A(newPlugs).findAll(function(value){
return !this.plugs.include( value )
}.bind(this));
if(plugs.length<1)
return;
this.buttons = [];
ORYX.Log.trace("Creating a toolbar.")
var canvasContainer = $$(".ORYX_Editor")[0].parentNode;
if(!this.toolbar){
this.toolbar = new Ext.ux.SlicedToolbar();
var region = this.facade.addToRegion("center", this.toolbar, "Toolbar");
//this.canvasContainer = $$(".ORYX_Editor")[0].parentNode;
//this.canvasContainer.appendChild(this.toolbar.getEl());
}
var currentGroupsName = this.plugs.last()?this.plugs.last().group:plugs[0].group;
// Map used to store all drop down buttons of current group
var currentGroupsDropDownButton = {};
plugs.each((function(value) {
if(!value.name) {return}
this.plugs.push(value);
// Add seperator if new group begins
if(currentGroupsName != value.group) {
this.toolbar.add('-');
currentGroupsName = value.group;
currentGroupsDropDownButton = {};
}
//add eventtracking
var tmp = value.functionality;
value.functionality = function(){
if ("undefined" != typeof(pageTracker) && "function" == typeof(pageTracker._trackEvent) )
{
pageTracker._trackEvent("ToolbarButton",value.name)
}
return tmp.apply(this, arguments);
}
// If an drop down group icon is provided, a split button should be used
if(value.dropDownGroupIcon){
var splitButton = currentGroupsDropDownButton[value.dropDownGroupIcon];
// Create a new split button if this is the first plugin using it
if(splitButton === undefined){
splitButton = currentGroupsDropDownButton[value.dropDownGroupIcon] = new Ext.Toolbar.SplitButton({
cls: "x-btn-icon", //show icon only
icon: value.dropDownGroupIcon,
menu: new Ext.menu.Menu({
items: [] // items are added later on
}),
listeners: {
click: function(button, event){
// The "normal" button should behave like the arrow button
if(!button.menu.isVisible() && !button.ignoreNextClick){
button.showMenu();
} else {
button.hideMenu();
}
}
}
});
this.toolbar.add(splitButton);
}
// General config button which will be used either to create a normal button
// or a check button (if toggling is enabled)
var buttonCfg = {
icon: value.icon,
iconCls: value.iconClass,
text: value.name,
itemId: value.id,
handler: value.toggle ? undefined : value.functionality,
checkHandler: value.toggle ? value.functionality : undefined,
listeners: {
render: function(item){
// After rendering, a tool tip should be added to component
if (value.description) {
new Ext.ToolTip({
target: item.getEl(),
title: value.description
})
}
}
}
}
// Create buttons depending on toggle
if(value.toggle) {
var button = new Ext.menu.CheckItem(buttonCfg);
} else {
var button = new Ext.menu.Item(buttonCfg);
}
splitButton.menu.add(button);
} else { // create normal, simple button
var button = new Ext.Toolbar.Button({
icon: value.icon, // icons can also be specified inline
cls: 'x-btn-icon', // Class who shows only the icon
iconCls: value.iconCls,
itemId: value.id,
tooltip: value.description, // Set the tooltip
tooltipType: 'title', // Tooltip will be shown as in the html-title attribute
handler: value.toggle ? null : value.functionality, // Handler for mouse click
enableToggle: value.toggle, // Option for enabling toggling
toggleHandler: value.toggle ? value.functionality : null // Handler for toggle (Parameters: button, active)
});
this.toolbar.add(button);
button.getEl().onclick = function() {this.blur()}
}
value['buttonInstance'] = button;
this.buttons.push(value);
}).bind(this));
this.enableButtons([]);
},
onAfterCommandsExecutedOrRollbacked: function onAfterCommandsExecutedOrRollbacked(event) {
this.enableButtons(this.facade.getSelection());
},
onSelectionChanged: function(event) {
this.enableButtons(event.elements);
},
enableButtons: function(elements) {
// Show the Buttons
this.buttons.each((function(value){
value.buttonInstance.enable();
// If there is less elements than minShapes
if (value.minShape && value.minShape > elements.length)
value.buttonInstance.disable();
// If there is more elements than minShapes
if (value.maxShape && value.maxShape < elements.length)
value.buttonInstance.disable();
// If the plugin is not enabled
if (value.isEnabled && !value.isEnabled())
value.buttonInstance.disable();
// If mode is not defined disable Buttons
if (!this.mode && !value.visibleInViewMode)
value.buttonInstance.disable();
// If in editMode disable Buttons
if ((this.mode && !this.mode.isEditMode() && !value.visibleInViewMode))
value.buttonInstance.disable();
// If in paintMode disableButtons
if ((this.mode && this.mode.isPaintMode() && !value.visibleInViewMode))
value.buttonInstance.disable();
}).bind(this));
},
handleModeChanged: function handleModeChanged(event) {
this.mode = event.mode;
this.enableButtons(this.facade.getSelection())
//Hide Buttons in ViewMode
if (!event.mode.isEditMode()) {
this.buttons.each(function (value) {
if (!value.visibleInViewMode) {
value.buttonInstance.hide();
}
});
var hideDelimiter = true;
this.toolbar.items.each(function (item) {
if (item instanceof Ext.Toolbar.Separator && hideDelimiter) {
item.hide();
} else if (!(item instanceof Ext.Toolbar.Separator)) {
hideDelimiter = item.hidden;
}
});
} else {
this.toolbar.items.each(function (item) {
item.show();
});
}
}
});
Ext.ns("Ext.ux");
Ext.ux.SlicedToolbar = Ext.extend(Ext.Toolbar, {
currentSlice: 0,
iconStandardWidth: 22, //22 px
seperatorStandardWidth: 2, //2px, minwidth for Ext.Toolbar.Fill
toolbarStandardPadding: 2,
initComponent: function(){
Ext.apply(this, {
});
Ext.ux.SlicedToolbar.superclass.initComponent.apply(this, arguments);
},
onRender: function(){
Ext.ux.SlicedToolbar.superclass.onRender.apply(this, arguments);
},
onResize: function(){
Ext.ux.SlicedToolbar.superclass.onResize.apply(this, arguments);
}
/*calcSlices: function(){
var slice = 0;
this.sliceMap = {};
var sliceWidth = 0;
var toolbarWidth = this.getEl().getWidth();
this.items.getRange().each(function(item, index){
//Remove all next and prev buttons
if (item.helperItem) {
item.destroy();
return;
}
var itemWidth = item.getEl().getWidth();
if(sliceWidth + itemWidth + 5 * this.iconStandardWidth > toolbarWidth){
var itemIndex = this.items.indexOf(item);
this.insertSlicingButton("next", slice, itemIndex);
if (slice !== 0) {
this.insertSlicingButton("prev", slice, itemIndex);
}
this.insertSlicingSeperator(slice, itemIndex);
slice += 1;
sliceWidth = 0;
}
this.sliceMap[item.id] = slice;
sliceWidth += itemWidth;
}.bind(this));
// Add prev button at the end
if(slice > 0){
this.insertSlicingSeperator(slice, this.items.getCount()+1);
this.insertSlicingButton("prev", slice, this.items.getCount()+1);
var spacer = new Ext.Toolbar.Spacer();
this.insertSlicedHelperButton(spacer, slice, this.items.getCount()+1);
Ext.get(spacer.id).setWidth(this.iconStandardWidth);
}
this.maxSlice = slice;
// Update view
this.setCurrentSlice(this.currentSlice);
},
insertSlicedButton: function(button, slice, index){
this.insertButton(index, button);
this.sliceMap[button.id] = slice;
},
insertSlicedHelperButton: function(button, slice, index){
button.helperItem = true;
this.insertSlicedButton(button, slice, index);
},
insertSlicingSeperator: function(slice, index){
// Align right
this.insertSlicedHelperButton(new Ext.Toolbar.Fill(), slice, index);
},
// type => next or prev
insertSlicingButton: function(type, slice, index){
var nextHandler = function(){this.setCurrentSlice(this.currentSlice+1)}.bind(this);
var prevHandler = function(){this.setCurrentSlice(this.currentSlice-1)}.bind(this);
var button = new Ext.Toolbar.Button({
cls: "x-btn-icon",
icon: ORYX.CONFIG.ROOT_PATH + "images/toolbar_"+type+".png",
handler: (type === "next") ? nextHandler : prevHandler
});
this.insertSlicedHelperButton(button, slice, index);
},
setCurrentSlice: function(slice){
if(slice > this.maxSlice || slice < 0) return;
this.currentSlice = slice;
this.items.getRange().each(function(item){
item.setVisible(slice === this.sliceMap[item.id]);
}.bind(this));
}*/
}); | 08to09-processwave | oryx/editor/client/scripts/Plugins/toolbar.js | JavaScript | mit | 14,829 |
/**
* 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.FarbrauschLegend = ORYX.Plugins.AbstractPlugin.extend({
_users: {},
usersDiv: null,
tabEntriesLastActivity: {},
tabEntries: {},
construct: function construct() {
arguments.callee.$.construct.apply(this, arguments);
this.usersDiv = this.createUsersTab();
Element.extend(this.usersDiv);
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_FARBRAUSCH_NEW_INFOS, this.handleFarbrauschEvent.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_AFTER_COMMANDS_EXECUTED, this.handleEventExecuted.bind(this));
},
onLoaded: function onLoaded(event) {
this.addUsersTab();
},
addUsersTab: function addUsersTab() {
this.facade.raiseEvent({
'tabid': 'pwave-users',
'type': ORYX.CONFIG.EVENT_SIDEBAR_NEW_TAB,
'forceExecution': true,
'tabTitle': 'Editors',
'tabOrder': 0,
'tabDivEl': this.usersDiv
});
},
createUsersTab: function createUsersTab() {
return document.createElement('div');
},
addEntryForId: function addEntryForId(userId) {
var entry = Element.extend(document.createElement('div'));
entry.className = "entry";
var colorDiv = Element.extend(document.createElement('div'));
colorDiv.className = "userColor";
entry.appendChild(colorDiv);
var imgDiv = Element.extend(document.createElement('div'));
imgDiv.className = "userAvatar";
var img = Element.extend(document.createElement('img'));
imgDiv.appendChild(img);
entry.appendChild(imgDiv);
var infoDiv = Element.extend(document.createElement('div'));
infoDiv.className = "userInfo";
entry.appendChild(infoDiv);
var lastActivity = Element.extend(document.createElement('div'));
lastActivity.className = "userLastActivity";
this.tabEntriesLastActivity[userId] = lastActivity;
entry.appendChild(lastActivity);
this.tabEntries[userId] = entry;
this.updateEntryForId(userId);
this.usersDiv.appendChild(entry);
},
updateEntryForId: function updateEntryForId(userId) {
var entry = this.tabEntries[userId];
if (typeof entry === "undefined") {
return;
}
entry.getElementsByClassName("userColor")[0].style.backgroundColor = this._getColorById(userId);
entry.getElementsByClassName("userAvatar")[0].firstChild.setAttribute("src", this._getThumbnailUrlById(userId));
entry.getElementsByClassName("userInfo")[0].update(this._getDisplayNameById(userId));
},
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") {
this._users[userId] = evtUser;
this.addEntryForId(userId);
} else if (evtUser.color !== user.color || evtUser.displayName !== user.displayName || evtUser.thumbnailUrl !== user.thumbnailUrl){
this._users[userId] = evtUser;
this.updateEntryForId(userId);
}
}
},
handleEventExecuted: function handleEventExecuted(evt) {
var command = evt.commands[0];
var userId = command.getCreatorId()
this.updateLastAction(userId, command.getCreatedAt());
},
updateLastAction: function updateLastAction(userId, timestamp) {
var date = new Date(timestamp);
var day = String(date.getDate());
if (day.length === 1) {
day = "0" + day;
}
var month = String(date.getMonth() + 1);
if (month.length === 1) {
month = "0" + month;
}
var year = String(date.getFullYear());
var hour = String(date.getHours());
if (hour.length === 1) {
hour = "0" + hour;
}
var minute = String(date.getMinutes());
if (minute.length === 1) {
minute = "0" + minute;
}
var userEntry = this.tabEntriesLastActivity[userId];
if (typeof userEntry !== "undefined") {
this.tabEntriesLastActivity[userId].update("Last Action: " + day + "." + month + "." + year + ", " + hour + ":" + minute);
}
},
_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";
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/farbrausch_legend.js | JavaScript | mit | 6,903 |
/**
* 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["DockerCreation.NewDockerCommand"] = ORYX.Core.AbstractCommand.extend({
construct: function construct(addEnabled, deleteEnabled, edge, docker, pos, facade, args){
// call construct method of parent
arguments.callee.$.construct.call(this, facade);
this.addEnabled = addEnabled;
this.deleteEnabled = deleteEnabled;
this.edge = edge;
this.docker = docker;
this.pos = pos;
this.facade = facade;
this.id = args.dockerId;
this.index = args.index;
this.options = args.options;
},
execute: function(){
if (this.addEnabled) {
this.docker = this.edge.addDocker(this.pos, this.docker, this.id);
if (typeof this.docker === "undefined") {
this.docker = this.edge.createDocker(this.index, this.pos, this.id);
} else {
this.index = this.edge.dockers.indexOf(this.docker);
}
} else if (this.deleteEnabled) {
if (typeof this.docker !== "undefined") {
this.index = this.edge.dockers.indexOf(this.docker);
this.pos = this.docker.bounds.center();
this.edge.removeDocker(this.docker);
}
}
this.facade.getCanvas().update();
this.facade.updateSelection();
this.options.docker = this.docker;
},
rollback: function(){
if (this.addEnabled) {
if (this.docker instanceof ORYX.Core.Controls.Docker) {
this.edge.removeDocker(this.docker);
}
} else if (this.deleteEnabled) {
if (typeof this.docker !== "undefined") {
this.edge.add(this.docker, this.index);
}
}
this.facade.getCanvas().update();
this.facade.updateSelection();
},
getCommandData: function getCommandData() {
var getId = function(shape) { return shape.resourceId; };
var getDockerId = function(docker) {
var dockerId;
if (typeof docker !== "undefined") {
dockerId = docker.id;
}
return dockerId;
};
var cmd = {
"index": this.index,
"name": "DockerCreation.NewDockerCommand",
"addEnabled": this.addEnabled,
"deleteEnabled": this.deleteEnabled,
"edgeId": getId(this.edge),
"dockerPositionArray": this.pos,
"dockerId": getDockerId(this.docker)
};
return cmd;
} ,
createFromCommandData: function createFromCommandData(facade, cmdData){
var addEnabled = cmdData.addEnabled;
var deleteEnabled = cmdData.deleteEnabled;
var canvas = facade.getCanvas();
var getShape = canvas.getChildShapeByResourceId.bind(canvas);
var edge = getShape(cmdData.edgeId);
var docker;
if (typeof edge === 'undefined') {
// Trying to add a docker to a already deleted edge.
return undefined;
}
if (deleteEnabled) {
for (var i = 0; i < edge.dockers.length; i++) {
if (edge.dockers[i].id == cmdData.dockerId) {
docker = edge.dockers[i];
}
}
}
if (addEnabled) {
var dockerPositionArray = cmdData.dockerPositionArray;
var position = canvas.node.ownerSVGElement.createSVGPoint();
position.x = dockerPositionArray.x;
position.y = dockerPositionArray.y;
}
var args = {
"dockerId": cmdData.dockerId,
"index": cmdData.index,
"options": {}
};
return new ORYX.Core.Commands["DockerCreation.NewDockerCommand"](addEnabled, deleteEnabled, edge, docker, position, facade, args);
},
getCommandName: function getCommandName() {
return "DockerCreation.NewDockerCommand";
},
getDisplayName: function getDisplayName() {
if (this.addEnabled) {
return "Docker added";
}
return "Docker deleted";
},
getAffectedShapes: function getAffectedShapes() {
return [this.edge];
}
});
ORYX.Plugins.DockerCreation = Clazz.extend({
construct: function( facade ){
this.facade = facade;
this.active = false; //true-> a ghostdocker is shown; false->ghostdocker is hidden
this.point = {x:0, y:0}; //Ghostdocker
this.ctrlPressed = false;
this.creationAllowed = true; // should be false if the addDocker button is pressed, otherwise there are always two dockers added when ALT+Clicking in docker-mode!
//visual representation of the Ghostdocker
this.circle = ORYX.Editor.graft("http://www.w3.org/2000/svg", null ,
['g', {"pointer-events":"none"},
['circle', {cx: "8", cy: "8", r: "3", fill:"yellow"}]]);
this.facade.offer({
keyCodes: [{
keyCode: 18,
keyAction: ORYX.CONFIG.KEY_ACTION_UP
}],
functionality: this.keyUp.bind(this)
});
this.facade.offer({
keyCodes: [{
metaKeys: [ORYX.CONFIG.META_KEY_ALT],
keyCode: 18,
keyAction: ORYX.CONFIG.KEY_ACTION_DOWN
}],
functionality: this.keyDown.bind(this)
});
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MOUSEDOWN, this.handleMouseDown.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MOUSEOVER, this.handleMouseOver.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MOUSEOUT, this.handleMouseOut.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MOUSEMOVE, this.handleMouseMove.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_DISABLE_DOCKER_CREATION, this.handleDisableDockerCreation.bind(this));
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_ENABLE_DOCKER_CREATION, this.handleEnableDockerCreation.bind(this));
/*
* Double click is reserved for label access, so abort action
*/
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_DBLCLICK, function() { window.clearTimeout(this.timer); }.bind(this));
/*
* click is reserved for selecting, so abort action when mouse goes up
*/
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_MOUSEUP, function() { window.clearTimeout(this.timer); }.bind(this));
},
keyDown: function keyDown(event) {
this.ctrlPressed = true;
},
keyUp: function keyUp(event) {
this.ctrlPressed = false;
this.hideOverlay();
this.active = false;
},
handleDisableDockerCreation: function handleDisableDockerCreation(event) {
this.creationAllowed = false;
},
handleEnableDockerCreation: function handleEnableDockerCreation(event) {
this.creationAllowed = true;
},
/**
* MouseOut Handler
*
*hide the Ghostpoint when Leaving the mouse from an edge
*/
handleMouseOut: function handleMouseOut(event, uiObj) {
if (this.active) {
this.hideOverlay();
this.active = false;
}
},
/**
* MouseOver Handler
*
*show the Ghostpoint if the edge is selected
*/
handleMouseOver: function handleMouseOver(event, uiObj) {
this.point.x = this.facade.eventCoordinates(event).x;
this.point.y = this.facade.eventCoordinates(event).y;
// show the Ghostdocker on the edge
if (uiObj instanceof ORYX.Core.Edge && this.ctrlPressed && this.creationAllowed) {
this.showOverlay(uiObj, this.point);
//ghostdocker is active
this.active = true;
}
},
/**
* MouseDown Handler
*
*create a Docker when clicking on a selected edge
*/
handleMouseDown: function handleMouseDown(event, uiObj) {
if (this.ctrlPressed && this.creationAllowed && event.which==1) {
if (uiObj instanceof ORYX.Core.Edge){
this.addDockerCommand({
edge: uiObj,
event: event,
position: this.facade.eventCoordinates(event)
});
this.hideOverlay();
} else if (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.deleteDockerCommand({
edge: uiObj.parent,
docker: uiObj
});
}
}
}
},
//
/**
* MouseMove Handler
*
*refresh the ghostpoint when moving the mouse over an edge
*/
handleMouseMove: function handleMouseMove(event, uiObj) {
if (uiObj instanceof ORYX.Core.Edge && this.ctrlPressed && this.creationAllowed) {
this.point.x = this.facade.eventCoordinates(event).x;
this.point.y = this.facade.eventCoordinates(event).y;
if (this.active) {
//refresh Ghostpoint
this.hideOverlay();
this.showOverlay(uiObj, this.point);
} else {
this.showOverlay(uiObj, this.point);
}
}
},
/**
* Command for creating a new Docker
*
* @param {Object} options
*/
addDockerCommand: function addDockerCommand(options){
if(!options.edge)
return;
var args = {
"options": options
};
var command = new ORYX.Core.Commands["DockerCreation.NewDockerCommand"](true, false, options.edge, options.docker, options.position, this.facade, args);
this.facade.executeCommands([command]);
this.facade.raiseEvent({
uiEvent: options.event,
type: ORYX.CONFIG.EVENT_DOCKERDRAG
}, options.docker );
},
deleteDockerCommand: function deleteDockerCommand(options){
if(!options.edge) {
return;
}
var args = { "options": options };
var command = new ORYX.Core.Commands["DockerCreation.NewDockerCommand"](false, true, options.edge, options.docker, options.position, this.facade, args);
this.facade.executeCommands([command]);
},
/**
*show the ghostpoint overlay
*
*@param {Shape} edge
*@param {Point} point
*/
showOverlay: function showOverlay(edge, point) {
if (this.facade.isReadOnlyMode()) {
return;
}
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_OVERLAY_SHOW,
id: "ghostpoint",
shapes: [edge],
node: this.circle,
ghostPoint: point,
dontCloneNode: true
});
},
/**
*hide the ghostpoint overlay
*/
hideOverlay: function hideOverlay() {
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_OVERLAY_HIDE,
id: "ghostpoint"
});
}
});
| 08to09-processwave | oryx/editor/client/scripts/Plugins/dockerCreation.js | JavaScript | mit | 13,065 |