text
stringlengths
54
60.6k
<commit_before>#ifndef PHPCXX_ARRAY_TCC #define PHPCXX_ARRAY_TCC #ifndef PHPCXX_ARRAY_H #error "Please do not include this file directly, use array.h instead" #endif namespace phpcxx { template<typename T> Array& Array::operator=(const vector<T>& v) { zval* z = &this->m_z; ZVAL_DEREF(z); zval_ptr_dtor(z); _array_init(z, v.size() ZEND_FILE_LINE_CC); for (std::size_t i=0; i<v.size(); ++i) { zval x; construct_zval(x, v[i]); zend_hash_next_index_insert_new(Z_ARR_P(z), &x); } return *this; } template<typename K, typename V, enable_if_t<std::is_integral<K>::value>*> Array& Array::operator=(const map<K, V>& v) { zval* z = &this->m_z; ZVAL_DEREF(z); zval_ptr_dtor(z); _array_init(z, 8 ZEND_FILE_LINE_CC); for (auto const& it : v) { zval x; construct_zval(x, it.second); zend_hash_index_add(Z_ARR_P(z), static_cast<zend_ulong>(it.first), &x); } return *this; } template<typename K, typename V, enable_if_t<is_pchar<K>::value || is_string<K>::value>*> Array& Array::operator=(const map<K, V>& v) { zval* z = &this->m_z; ZVAL_DEREF(z); zval_ptr_dtor(z); _array_init(z, 8 ZEND_FILE_LINE_CC); for (auto const& it : v) { zval x; construct_zval(x, it.second); ZendString key(it.first); zend_hash_add(Z_ARR_P(z), key.get(), &x); } return *this; } } #endif /* PHPCXX_ARRAY_TCC */ <commit_msg>Use map.size() in call to _array_init()<commit_after>#ifndef PHPCXX_ARRAY_TCC #define PHPCXX_ARRAY_TCC #ifndef PHPCXX_ARRAY_H #error "Please do not include this file directly, use array.h instead" #endif namespace phpcxx { template<typename T> Array& Array::operator=(const vector<T>& v) { zval* z = &this->m_z; ZVAL_DEREF(z); zval_ptr_dtor(z); _array_init(z, v.size() ZEND_FILE_LINE_CC); for (std::size_t i=0; i<v.size(); ++i) { zval x; construct_zval(x, v[i]); zend_hash_next_index_insert_new(Z_ARR_P(z), &x); } return *this; } template<typename K, typename V, enable_if_t<std::is_integral<K>::value>*> Array& Array::operator=(const map<K, V>& v) { zval* z = &this->m_z; ZVAL_DEREF(z); zval_ptr_dtor(z); _array_init(z, v.size() ZEND_FILE_LINE_CC); for (auto const& it : v) { zval x; construct_zval(x, it.second); zend_hash_index_add(Z_ARR_P(z), static_cast<zend_ulong>(it.first), &x); } return *this; } template<typename K, typename V, enable_if_t<is_pchar<K>::value || is_string<K>::value>*> Array& Array::operator=(const map<K, V>& v) { zval* z = &this->m_z; ZVAL_DEREF(z); zval_ptr_dtor(z); _array_init(z, v.size() ZEND_FILE_LINE_CC); for (auto const& it : v) { zval x; construct_zval(x, it.second); ZendString key(it.first); zend_hash_add(Z_ARR_P(z), key.get(), &x); } return *this; } } #endif /* PHPCXX_ARRAY_TCC */ <|endoftext|>
<commit_before>#include "apfMPAS.h" #include <apfMesh2.h> #include <apfNumbering.h> #include <diffMC/src/parma_ghostOwner.h> #include <netcdf> namespace apf { using namespace netCDF; struct MpasFile { ~MpasFile() { delete [] x; delete [] y; delete [] z; delete [] conn; } int elements; int nodes; int nodesPerElement; double* x; double* y; double* z; /* conn[i * vertexDegree + j] - 1 is the index of the j'th node of element i */ int* conn; }; static int readDim(NcFile& f, const char* name) { return f.getDim(name).getSize(); } static double* readDoubles(NcFile& f, const char* name, int n) { double* a = new double[n]; NcVar v = f.getVar(name); v.getVar(a); return a; } static int* readInts(NcFile& f, const char* name, int n) { int* a = new int[n]; NcVar v = f.getVar(name); v.getVar(a); return a; } void readMpasFile(MpasFile& out, const char* filename) { NcFile in(filename, NcFile::read); /* this is the dual of a hexagonal mesh, hence the reversing of terms */ out.nodes = readDim(in, "nCells"); printf("%d nodes\n", out.nodes); out.elements = readDim(in, "nVertices"); printf("%d elements\n", out.elements); out.nodesPerElement = readDim(in, "vertexDegree"); out.x = readDoubles(in, "xCell", out.nodes); out.y = readDoubles(in, "yCell", out.nodes); out.z = readDoubles(in, "zCell", out.nodes); out.conn = readInts(in, "cellsOnVertex", out.elements * out.nodesPerElement); } static int getType(int nodesPerElement) { if (nodesPerElement == 3) return apf::Mesh::TRIANGLE; if (nodesPerElement == 4) return apf::Mesh::QUAD; abort(); return 0; } void numberInitialNodes(MpasFile& in, apf::Mesh2* out, apf::MeshEntity** v) { apf::Numbering* n = apf::createNumbering(out, "mpas_id", out->getShape(), 1); for (int i = 0; i < in.nodes; ++i) apf::number(n, v[i], 0, 0, i); } void buildInitialMesh(MpasFile& in, apf::Mesh2* out) { apf::MeshEntity** v = new apf::MeshEntity* [in.nodes]; /* fake classification for now, deriveMdsModel will fix this up */ apf::ModelEntity* c = out->findModelEntity(2, 0); int t = getType(in.nodesPerElement); for (int i = 0; i < in.nodes; ++i) v[i] = out->createVert(c); for (int i = 0; i < in.nodes; ++i) { apf::Vector3 x(in.x[i], in.y[i], in.z[i]); out->setPoint(v[i], 0, x); } for (int i = 0; i < in.elements; ++i) { apf::Downward ev; for (int j = 0; j < in.nodesPerElement; ++j) { int vi = in.conn[i * in.nodesPerElement + j] - 1; /* zero indices (-1 after conversion) indicate that an MPAS vertex does not have an adjacent cell in that direction (it is a boundary vertex). In our dual mesh, we simply omit that dual element. This is correct and should not cause problems. */ if (vi < 0) goto bad_vi; assert(vi < in.nodes); ev[j] = v[vi]; } apf::buildElement(out, c, t, ev); bad_vi: continue; } numberInitialNodes(in, out, v); delete [] v; } void removeIsolatedNodes(apf::Mesh2* m) { /* another problem with the dual: MPAS cells without adjacent cells become vertices with no adjacent elements in the dual mesh, which our codes don't handle. We have to give up on these cells, but tell the user about it. We also need to be aware of these omitted cells going forward */ //apf::Numbering* nums = apf::createNumbering(m, "mpas_id", m->getShape(), 1); apf::MeshIterator* it = m->begin(0); int n = 0; apf::MeshEntity* e; while ((e = m->iterate(it))) if ( ! m->countUpward(e)) { /*int num =getNumber(nums, e, 0, 0); fprintf(stdout, "Missing vertex with number %d\n",num); */ m->destroy(e); ++n; } m->end(it); if (n) fprintf(stderr, "warning: removed %d isolated nodes from MPAS dual mesh\n", n); } void loadMpasMesh(apf::Mesh2* m, const char* filename) { assert(PCU_Comm_Peers() == 1); MpasFile f; readMpasFile(f, filename); buildInitialMesh(f, m); removeIsolatedNodes(m); } void writeMpasAssignments(apf::Mesh2* m, const char* filename) { NcFile in(filename, NcFile::read); /* this is the dual of a hexagonal mesh, hence the reversing of terms */ int numMpasVtx = readDim(in, "nCells"); apf::Numbering* n = apf::createNumbering(m, "mpas_id", m->getShape(), 1); /* collect N/#parts contiguous vertex assignments on each process (and deal with any remainders) */ int numPerPart = numMpasVtx / PCU_Comm_Peers(); apf::MeshIterator* itr = m->begin(0); apf::MeshEntity* e; int size; if (PCU_Comm_Self()==PCU_Comm_Peers()-1) size=numMpasVtx%numPerPart+numPerPart; else size=numPerPart; std::vector<int> vtxs(size,-1); PCU_Comm_Begin(); while ((e = m->iterate(itr))) { if (!parma::isOwned(m, e)) continue; int num = getNumber(n, e, 0, 0); int target = num / numPerPart; if (target>=PCU_Comm_Peers()) target = PCU_Comm_Peers()-1; if (target == PCU_Comm_Self()) vtxs[num%size] = PCU_Comm_Self(); else PCU_COMM_PACK(target,num); } m->end(itr); PCU_Comm_Send(); while (PCU_Comm_Receive()) { int owner =PCU_Comm_Sender(); int num; PCU_COMM_UNPACK(num); vtxs[num%size]=owner; } // assign missing vertices to a random part id int count = 0; for (int i = 0; (i < size); i++) if (vtxs[i]==-1) { vtxs[i] = 0; //to be random //fprintf(stdout,"missing vertex %d\n",i+numPerPart*PCU_Comm_Self()); count++; } fprintf(stdout,"missing vertices found %d\n",count); // use MPI IO to write the contiguous blocks to a single graph.info.part.<#parts> file // see https://gist.github.com/cwsmith/166d5beb400f3a8136f7 and the comments double startTime=MPI_Wtime(); FILE* file; char name[32]; sprintf(name,"graph.info.part.%d",PCU_Comm_Peers()); file = fopen(name, "w"); fseek(file,numPerPart*PCU_Comm_Self()*16,SEEK_SET); for (int i=0;i<size;i++) fprintf(file,"%-15d\n",vtxs[i]); fclose(file); double totalTime= MPI_Wtime()-startTime; PCU_Max_Doubles(&totalTime,1); if (!PCU_Comm_Self()) fprintf(stdout,"File writing time: %f seconds\n", totalTime); } } <commit_msg>almost fixed, prints lines correctly and adds extra lines<commit_after>#include "apfMPAS.h" #include <apfMesh2.h> #include <apfNumbering.h> #include <diffMC/src/parma_ghostOwner.h> #include <netcdf> namespace apf { using namespace netCDF; struct MpasFile { ~MpasFile() { delete [] x; delete [] y; delete [] z; delete [] conn; } int elements; int nodes; int nodesPerElement; double* x; double* y; double* z; /* conn[i * vertexDegree + j] - 1 is the index of the j'th node of element i */ int* conn; }; static int readDim(NcFile& f, const char* name) { return f.getDim(name).getSize(); } static double* readDoubles(NcFile& f, const char* name, int n) { double* a = new double[n]; NcVar v = f.getVar(name); v.getVar(a); return a; } static int* readInts(NcFile& f, const char* name, int n) { int* a = new int[n]; NcVar v = f.getVar(name); v.getVar(a); return a; } void readMpasFile(MpasFile& out, const char* filename) { NcFile in(filename, NcFile::read); /* this is the dual of a hexagonal mesh, hence the reversing of terms */ out.nodes = readDim(in, "nCells"); printf("%d nodes\n", out.nodes); out.elements = readDim(in, "nVertices"); printf("%d elements\n", out.elements); out.nodesPerElement = readDim(in, "vertexDegree"); out.x = readDoubles(in, "xCell", out.nodes); out.y = readDoubles(in, "yCell", out.nodes); out.z = readDoubles(in, "zCell", out.nodes); out.conn = readInts(in, "cellsOnVertex", out.elements * out.nodesPerElement); } static int getType(int nodesPerElement) { if (nodesPerElement == 3) return apf::Mesh::TRIANGLE; if (nodesPerElement == 4) return apf::Mesh::QUAD; abort(); return 0; } void numberInitialNodes(MpasFile& in, apf::Mesh2* out, apf::MeshEntity** v) { apf::Numbering* n = apf::createNumbering(out, "mpas_id", out->getShape(), 1); for (int i = 0; i < in.nodes; ++i) apf::number(n, v[i], 0, 0, i); } void buildInitialMesh(MpasFile& in, apf::Mesh2* out) { apf::MeshEntity** v = new apf::MeshEntity* [in.nodes]; /* fake classification for now, deriveMdsModel will fix this up */ apf::ModelEntity* c = out->findModelEntity(2, 0); int t = getType(in.nodesPerElement); for (int i = 0; i < in.nodes; ++i) v[i] = out->createVert(c); for (int i = 0; i < in.nodes; ++i) { apf::Vector3 x(in.x[i], in.y[i], in.z[i]); out->setPoint(v[i], 0, x); } for (int i = 0; i < in.elements; ++i) { apf::Downward ev; for (int j = 0; j < in.nodesPerElement; ++j) { int vi = in.conn[i * in.nodesPerElement + j] - 1; /* zero indices (-1 after conversion) indicate that an MPAS vertex does not have an adjacent cell in that direction (it is a boundary vertex). In our dual mesh, we simply omit that dual element. This is correct and should not cause problems. */ if (vi < 0) goto bad_vi; assert(vi < in.nodes); ev[j] = v[vi]; } apf::buildElement(out, c, t, ev); bad_vi: continue; } numberInitialNodes(in, out, v); delete [] v; } void removeIsolatedNodes(apf::Mesh2* m) { /* another problem with the dual: MPAS cells without adjacent cells become vertices with no adjacent elements in the dual mesh, which our codes don't handle. We have to give up on these cells, but tell the user about it. We also need to be aware of these omitted cells going forward */ //apf::Numbering* nums = apf::createNumbering(m, "mpas_id", m->getShape(), 1); apf::MeshIterator* it = m->begin(0); int n = 0; apf::MeshEntity* e; while ((e = m->iterate(it))) if ( ! m->countUpward(e)) { /*int num =getNumber(nums, e, 0, 0); fprintf(stdout, "Missing vertex with number %d\n",num); */ m->destroy(e); ++n; } m->end(it); if (n) fprintf(stderr, "warning: removed %d isolated nodes from MPAS dual mesh\n", n); } void loadMpasMesh(apf::Mesh2* m, const char* filename) { assert(PCU_Comm_Peers() == 1); MpasFile f; readMpasFile(f, filename); buildInitialMesh(f, m); removeIsolatedNodes(m); } void writeMpasAssignments(apf::Mesh2* m, const char* filename) { NcFile in(filename, NcFile::read); /* this is the dual of a hexagonal mesh, hence the reversing of terms */ int numMpasVtx = readDim(in, "nCells"); apf::Numbering* n = apf::createNumbering(m, "mpas_id", m->getShape(), 1); /* collect N/#parts contiguous vertex assignments on each process (and deal with any remainders) */ int numPerPart = numMpasVtx / PCU_Comm_Peers(); apf::MeshIterator* itr = m->begin(0); apf::MeshEntity* e; int size; if (PCU_Comm_Self()==PCU_Comm_Peers()-1) size=numMpasVtx%numPerPart+numPerPart; else size=numPerPart; std::vector<int> vtxs(size,-1); PCU_Comm_Begin(); while ((e = m->iterate(itr))) { if (!parma::isOwned(m, e)) continue; int num = getNumber(n, e, 0, 0); int target = num / numPerPart; if (target>=PCU_Comm_Peers()) target = PCU_Comm_Peers()-1; if (target == PCU_Comm_Self()) vtxs[num%size] = PCU_Comm_Self(); else PCU_COMM_PACK(target,num); } m->end(itr); PCU_Comm_Send(); while (PCU_Comm_Receive()) { int owner =PCU_Comm_Sender(); int num; PCU_COMM_UNPACK(num); vtxs[num%size]=owner; } // assign missing vertices to a random part id int count = 0; for (int i = 0; (i < size); i++) if (vtxs[i]==-1) { vtxs[i] = 0; //to be random //fprintf(stdout,"missing vertex %d\n",i+numPerPart*PCU_Comm_Self()); count++; } if (count) fprintf(stdout,"missing vertices found %d on part %d\n",count,PCU_Comm_Self()); // use MPI IO to write the contiguous blocks to a single graph.info.part.<#parts> file // see https://gist.github.com/cwsmith/166d5beb400f3a8136f7 and the comments double startTime=MPI_Wtime(); MPI_File file; char name[32]; sprintf(name,"graph.info.part.%d",PCU_Comm_Peers()); MPI_File_open(MPI_COMM_WORLD, name, MPI_MODE_CREATE|MPI_MODE_WRONLY, MPI_INFO_NULL, &file); MPI_Offset offset = numPerPart*PCU_Comm_Self()*16; MPI_File_seek(file, offset, MPI_SEEK_SET); MPI_Datatype filetype; MPI_Type_contiguous(size,MPI_CHAR,&filetype); MPI_Type_commit(&filetype); MPI_File_set_view(file,offset,MPI_CHAR,MPI_CHAR,"internal",MPI_INFO_NULL); char* str = new char[16*size]; for (int i=0; i<size; i++) { sprintf(str,"%s%-15d\n",str,vtxs[i]); } MPI_Status status; MPI_File_write(file,str,strlen(str),MPI_CHAR,&status); delete [] str; MPI_File_close(&file); double totalTime= MPI_Wtime()-startTime; PCU_Max_Doubles(&totalTime,1); if (!PCU_Comm_Self()) fprintf(stdout,"File writing time: %f seconds\n", totalTime); } } <|endoftext|>
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html #include "bsecategories.hh" #include "bsesource.hh" #include "bseprocedure.hh" #include "bsemain.hh" #include "bsestandardsynths.hh" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> static gchar *indent_inc = NULL; static guint spacing = 1; static FILE *f_out = NULL; static GType root = 0; static gboolean recursion = TRUE; static gboolean feature_blurb = FALSE; static gboolean feature_channels = FALSE; /* #define O_SPACE "\\as" #define O_ESPACE " " #define O_BRANCH "\\aE" #define O_VLINE "\\al" #define O_LLEAF "\\aL" #define O_KEY_FILL "_" */ #define O_SPACE " " #define O_ESPACE "" #define O_BRANCH "+" #define O_VLINE "|" #define O_LLEAF "`" #define O_KEY_FILL "_" static void show_nodes (GType type, GType sibling, const gchar *indent) { GType *children; guint i; if (!type) return; children = g_type_children (type, NULL); if (type != root) for (i = 0; i < spacing; i++) fprintf (f_out, "%s%s\n", indent, O_VLINE); fprintf (f_out, "%s%s%s%s", indent, sibling ? O_BRANCH : (type != root ? O_LLEAF : O_SPACE), O_ESPACE, g_type_name (type)); for (i = strlen (g_type_name (type)); i <= strlen (indent_inc); i++) fputs (O_KEY_FILL, f_out); if (feature_blurb && bse_type_get_blurb (type)) { fputs ("\t[", f_out); fputs (bse_type_get_blurb (type), f_out); fputs ("]", f_out); } if (G_TYPE_IS_ABSTRACT (type)) fputs ("\t(abstract)", f_out); if (feature_channels && g_type_is_a (type, BSE_TYPE_SOURCE)) { BseSourceClass *klass = (BseSourceClass*) g_type_class_ref (type); gchar buffer[1024]; sprintf (buffer, "\t(ichannels %u) (ochannels %u)", klass->channel_defs.n_ichannels, klass->channel_defs.n_ochannels); fputs (buffer, f_out); g_type_class_unref (klass); } fputc ('\n', f_out); if (children && recursion) { gchar *new_indent; GType *child; if (sibling) new_indent = g_strconcat (indent, O_VLINE, indent_inc, NULL); else new_indent = g_strconcat (indent, O_SPACE, indent_inc, NULL); for (child = children; *child; child++) show_nodes (child[0], child[1], new_indent); g_free (new_indent); } g_free (children); } static void show_cats (void) { BseCategorySeq *cseq; guint i; cseq = bse_categories_match_typed ("*", 0); for (i = 0; i < cseq->n_cats; i++) fprintf (f_out, "%s\t(%s)\n", cseq->cats[i]->category, cseq->cats[i]->type); bse_category_seq_free (cseq); } static void show_procdoc (void) { BseCategorySeq *cseq; guint i; const gchar *nullstr = ""; // "???"; cseq = bse_categories_match_typed ("*", BSE_TYPE_PROCEDURE); for (i = 0; i < cseq->n_cats; i++) { GType type = g_type_from_name (cseq->cats[i]->type); BseProcedureClass *klass = (BseProcedureClass*) g_type_class_ref (type); gchar *pname = g_type_name_to_sname (cseq->cats[i]->type); const gchar *blurb = bse_type_get_blurb (type); guint j; fprintf (f_out, "/**\n * %s\n", pname); for (j = 0; j < klass->n_in_pspecs; j++) { GParamSpec *pspec = G_PARAM_SPEC (klass->in_pspecs[j]); fprintf (f_out, " * @%s: %s\n", pspec->name, g_param_spec_get_blurb (pspec) ? g_param_spec_get_blurb (pspec) : nullstr); } for (j = 0; j < klass->n_out_pspecs; j++) { GParamSpec *pspec = G_PARAM_SPEC (klass->out_pspecs[j]); fprintf (f_out, " * @Returns: %s: %s\n", pspec->name, g_param_spec_get_blurb (pspec) ? g_param_spec_get_blurb (pspec) : nullstr); } if (blurb) fprintf (f_out, " * %s\n", blurb); fprintf (f_out, " **/\n"); g_type_class_unref (klass); g_free (pname); } bse_category_seq_free (cseq); } static gint help (gchar *arg) { fprintf (stderr, "usage: query <qualifier> [-r <type>] [-{i|b} \"\"] [-s #] [-{h|x|y}]\n"); fprintf (stderr, " -r specifiy root type\n"); fprintf (stderr, " -n don't descend type tree\n"); fprintf (stderr, " -p include plugins\n"); fprintf (stderr, " -x show type blurbs\n"); fprintf (stderr, " -y show source channels\n"); fprintf (stderr, " -h guess what ;)\n"); fprintf (stderr, " -b specifiy indent string\n"); fprintf (stderr, " -i specifiy incremental indent string\n"); fprintf (stderr, " -s specifiy line spacing\n"); fprintf (stderr, " -:f make all warnings fatal\n"); fprintf (stderr, "qualifiers:\n"); fprintf (stderr, " froots iterate over fundamental roots\n"); fprintf (stderr, " tree print BSE type tree\n"); fprintf (stderr, " cats print categories\n"); fprintf (stderr, " procdoc print procedure documentation\n"); fprintf (stderr, " synth <x> dump standard synth <x> definition\n"); return arg != NULL; } int main (gint argc, gchar *argv[]) { gboolean gen_froots = 0; gboolean gen_tree = 0; gboolean gen_cats = 0; gboolean gen_procdoc = 0; gchar *show_synth = NULL; gchar *root_name = NULL; const char *iindent = ""; const char *pluginbool = "load-core-plugins=0"; const char *scriptbool = "load-core-scripts=0"; f_out = stdout; bse_init_test (&argc, argv); int i; for (i = 1; i < argc; i++) { if (strcmp ("-s", argv[i]) == 0) { i++; if (i < argc) spacing = atoi (argv[i]); } else if (strcmp ("-i", argv[i]) == 0) { i++; if (i < argc) { char *p; guint n; p = argv[i]; while (*p) p++; n = p - argv[i]; indent_inc = g_new (gchar, n * strlen (O_SPACE) + 1); *indent_inc = 0; while (n) { n--; strcpy (indent_inc, O_SPACE); } } } else if (strcmp ("-b", argv[i]) == 0) { i++; if (i < argc) iindent = argv[i]; } else if (strcmp ("-r", argv[i]) == 0) { i++; if (i < argc) root_name = argv[i]; } else if (strcmp ("-n", argv[i]) == 0) { recursion = FALSE; } else if (strcmp ("-x", argv[i]) == 0) { feature_blurb = TRUE; } else if (strcmp ("-y", argv[i]) == 0) { feature_channels = TRUE; } else if (strcmp ("froots", argv[i]) == 0) { gen_froots = 1; } else if (strcmp ("synth", argv[i]) == 0 && i + 1 < argc) { show_synth = argv[++i]; } else if (strcmp ("tree", argv[i]) == 0) { gen_tree = 1; } else if (strcmp ("cats", argv[i]) == 0) { gen_cats = 1; } else if (strcmp ("procdoc", argv[i]) == 0) { gen_procdoc = 1; } else if (strcmp ("-p", argv[i]) == 0) pluginbool = "load-core-plugins=1"; else if (strcmp ("-:f", argv[i]) == 0) { g_log_set_always_fatal (GLogLevelFlags (G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | g_log_set_always_fatal (GLogLevelFlags (G_LOG_FATAL_MASK)))); } else if (strcmp ("-h", argv[i]) == 0) { return help (NULL); } else if (strcmp ("--help", argv[i]) == 0) { return help (NULL); } else return help (argv[i]); } bse_init_inprocess (&argc, argv, "BseQuery", Bse::cstrings_to_vector (pluginbool, scriptbool, NULL)); if (root_name) root = g_type_from_name (root_name); else root = BSE_TYPE_OBJECT; if (!gen_froots && !gen_tree && !gen_cats && !gen_procdoc && !show_synth) return help (argv[i-1]); if (!indent_inc) { indent_inc = g_new (gchar, strlen (O_SPACE) + 1); *indent_inc = 0; strcpy (indent_inc, O_SPACE); strcpy (indent_inc, O_SPACE); strcpy (indent_inc, O_SPACE); } if (gen_tree) show_nodes (root, 0, iindent); if (gen_froots) { root = ~0; for (i = 0; i <= G_TYPE_FUNDAMENTAL_MAX; i += G_TYPE_MAKE_FUNDAMENTAL (1)) { const char *name = g_type_name (i); if (name) show_nodes (i, 0, iindent); } } if (gen_cats) show_cats (); if (gen_procdoc) show_procdoc (); if (show_synth) { gchar *text = bse_standard_synth_inflate (show_synth, NULL); g_print ("%s", text); g_free (text); } return 0; } <commit_msg>BSE: fix bsequery initialization to avoid crashing<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html #include "bsecategories.hh" #include "bsesource.hh" #include "bseprocedure.hh" #include "bsemain.hh" #include "bsestandardsynths.hh" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> static gchar *indent_inc = NULL; static guint spacing = 1; static FILE *f_out = NULL; static GType root = 0; static gboolean recursion = TRUE; static gboolean feature_blurb = FALSE; static gboolean feature_channels = FALSE; /* #define O_SPACE "\\as" #define O_ESPACE " " #define O_BRANCH "\\aE" #define O_VLINE "\\al" #define O_LLEAF "\\aL" #define O_KEY_FILL "_" */ #define O_SPACE " " #define O_ESPACE "" #define O_BRANCH "+" #define O_VLINE "|" #define O_LLEAF "`" #define O_KEY_FILL "_" static void show_nodes (GType type, GType sibling, const gchar *indent) { GType *children; guint i; if (!type) return; children = g_type_children (type, NULL); if (type != root) for (i = 0; i < spacing; i++) fprintf (f_out, "%s%s\n", indent, O_VLINE); fprintf (f_out, "%s%s%s%s", indent, sibling ? O_BRANCH : (type != root ? O_LLEAF : O_SPACE), O_ESPACE, g_type_name (type)); for (i = strlen (g_type_name (type)); i <= strlen (indent_inc); i++) fputs (O_KEY_FILL, f_out); if (feature_blurb && bse_type_get_blurb (type)) { fputs ("\t[", f_out); fputs (bse_type_get_blurb (type), f_out); fputs ("]", f_out); } if (G_TYPE_IS_ABSTRACT (type)) fputs ("\t(abstract)", f_out); if (feature_channels && g_type_is_a (type, BSE_TYPE_SOURCE)) { BseSourceClass *klass = (BseSourceClass*) g_type_class_ref (type); gchar buffer[1024]; sprintf (buffer, "\t(ichannels %u) (ochannels %u)", klass->channel_defs.n_ichannels, klass->channel_defs.n_ochannels); fputs (buffer, f_out); g_type_class_unref (klass); } fputc ('\n', f_out); if (children && recursion) { gchar *new_indent; GType *child; if (sibling) new_indent = g_strconcat (indent, O_VLINE, indent_inc, NULL); else new_indent = g_strconcat (indent, O_SPACE, indent_inc, NULL); for (child = children; *child; child++) show_nodes (child[0], child[1], new_indent); g_free (new_indent); } g_free (children); } static void show_cats (void) { BseCategorySeq *cseq; guint i; cseq = bse_categories_match_typed ("*", 0); for (i = 0; i < cseq->n_cats; i++) fprintf (f_out, "%s\t(%s)\n", cseq->cats[i]->category, cseq->cats[i]->type); bse_category_seq_free (cseq); } static void show_procdoc (void) { BseCategorySeq *cseq; guint i; const gchar *nullstr = ""; // "???"; cseq = bse_categories_match_typed ("*", BSE_TYPE_PROCEDURE); for (i = 0; i < cseq->n_cats; i++) { GType type = g_type_from_name (cseq->cats[i]->type); BseProcedureClass *klass = (BseProcedureClass*) g_type_class_ref (type); gchar *pname = g_type_name_to_sname (cseq->cats[i]->type); const gchar *blurb = bse_type_get_blurb (type); guint j; fprintf (f_out, "/**\n * %s\n", pname); for (j = 0; j < klass->n_in_pspecs; j++) { GParamSpec *pspec = G_PARAM_SPEC (klass->in_pspecs[j]); fprintf (f_out, " * @%s: %s\n", pspec->name, g_param_spec_get_blurb (pspec) ? g_param_spec_get_blurb (pspec) : nullstr); } for (j = 0; j < klass->n_out_pspecs; j++) { GParamSpec *pspec = G_PARAM_SPEC (klass->out_pspecs[j]); fprintf (f_out, " * @Returns: %s: %s\n", pspec->name, g_param_spec_get_blurb (pspec) ? g_param_spec_get_blurb (pspec) : nullstr); } if (blurb) fprintf (f_out, " * %s\n", blurb); fprintf (f_out, " **/\n"); g_type_class_unref (klass); g_free (pname); } bse_category_seq_free (cseq); } static gint help (gchar *arg) { fprintf (stderr, "usage: query <qualifier> [-r <type>] [-{i|b} \"\"] [-s #] [-{h|x|y}]\n"); fprintf (stderr, " -r specifiy root type\n"); fprintf (stderr, " -n don't descend type tree\n"); fprintf (stderr, " -p include plugins\n"); fprintf (stderr, " -x show type blurbs\n"); fprintf (stderr, " -y show source channels\n"); fprintf (stderr, " -h guess what ;)\n"); fprintf (stderr, " -b specifiy indent string\n"); fprintf (stderr, " -i specifiy incremental indent string\n"); fprintf (stderr, " -s specifiy line spacing\n"); fprintf (stderr, " -:f make all warnings fatal\n"); fprintf (stderr, "qualifiers:\n"); fprintf (stderr, " froots iterate over fundamental roots\n"); fprintf (stderr, " tree print BSE type tree\n"); fprintf (stderr, " cats print categories\n"); fprintf (stderr, " procdoc print procedure documentation\n"); fprintf (stderr, " synth <x> dump standard synth <x> definition\n"); return arg != NULL; } int main (gint argc, gchar *argv[]) { gboolean gen_froots = 0; gboolean gen_tree = 0; gboolean gen_cats = 0; gboolean gen_procdoc = 0; gchar *show_synth = NULL; gchar *root_name = NULL; const char *iindent = ""; const char *pluginbool = "load-core-plugins=0"; const char *scriptbool = "load-core-scripts=0"; f_out = stdout; bse_init_inprocess (&argc, argv, "BseQuery", Bse::cstrings_to_vector (pluginbool, scriptbool, NULL)); // bse_init_test (&argc, argv); int i; for (i = 1; i < argc; i++) { if (strcmp ("-s", argv[i]) == 0) { i++; if (i < argc) spacing = atoi (argv[i]); } else if (strcmp ("-i", argv[i]) == 0) { i++; if (i < argc) { char *p; guint n; p = argv[i]; while (*p) p++; n = p - argv[i]; indent_inc = g_new (gchar, n * strlen (O_SPACE) + 1); *indent_inc = 0; while (n) { n--; strcpy (indent_inc, O_SPACE); } } } else if (strcmp ("-b", argv[i]) == 0) { i++; if (i < argc) iindent = argv[i]; } else if (strcmp ("-r", argv[i]) == 0) { i++; if (i < argc) root_name = argv[i]; } else if (strcmp ("-n", argv[i]) == 0) { recursion = FALSE; } else if (strcmp ("-x", argv[i]) == 0) { feature_blurb = TRUE; } else if (strcmp ("-y", argv[i]) == 0) { feature_channels = TRUE; } else if (strcmp ("froots", argv[i]) == 0) { gen_froots = 1; } else if (strcmp ("synth", argv[i]) == 0 && i + 1 < argc) { show_synth = argv[++i]; } else if (strcmp ("tree", argv[i]) == 0) { gen_tree = 1; } else if (strcmp ("cats", argv[i]) == 0) { gen_cats = 1; } else if (strcmp ("procdoc", argv[i]) == 0) { gen_procdoc = 1; } else if (strcmp ("-p", argv[i]) == 0) pluginbool = "load-core-plugins=1"; else if (strcmp ("-:f", argv[i]) == 0) { g_log_set_always_fatal (GLogLevelFlags (G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | g_log_set_always_fatal (GLogLevelFlags (G_LOG_FATAL_MASK)))); } else if (strcmp ("-h", argv[i]) == 0) { return help (NULL); } else if (strcmp ("--help", argv[i]) == 0) { return help (NULL); } else return help (argv[i]); } // bse_init_inprocess (&argc, argv, "BseQuery", Bse::cstrings_to_vector (pluginbool, scriptbool, NULL)); if (root_name) root = g_type_from_name (root_name); else root = BSE_TYPE_OBJECT; if (!gen_froots && !gen_tree && !gen_cats && !gen_procdoc && !show_synth) return help (argv[i-1]); if (!indent_inc) { indent_inc = g_new (gchar, strlen (O_SPACE) + 1); *indent_inc = 0; strcpy (indent_inc, O_SPACE); strcpy (indent_inc, O_SPACE); strcpy (indent_inc, O_SPACE); } if (gen_tree) show_nodes (root, 0, iindent); if (gen_froots) { root = ~0; for (i = 0; i <= G_TYPE_FUNDAMENTAL_MAX; i += G_TYPE_MAKE_FUNDAMENTAL (1)) { const char *name = g_type_name (i); if (name) show_nodes (i, 0, iindent); } } if (gen_cats) show_cats (); if (gen_procdoc) show_procdoc (); if (show_synth) { gchar *text = bse_standard_synth_inflate (show_synth, NULL); g_print ("%s", text); g_free (text); } return 0; } <|endoftext|>
<commit_before><commit_msg>Cast Buffers to Char * for Winsock<commit_after><|endoftext|>
<commit_before>#include <cassert> #include <climits> #include <cmath> #include "rational.hh" #include "zs_error.hh" #include "zs_memory.hh" static_assert(sizeof(int) < sizeof(long long), "integer overflow cannot be treated properly"); using namespace std; // TODO: make this as constructor. Rational& Rational::normalized_reset(long long n, long long d){ if(d == 0) throw_zs_error({}, "Rational::denominator is 0"); auto gcd_val = gcd(n, d); n /= gcd_val; d /= gcd_val; if(d < 0){ n = -n; d = -d; } if(n < INT_MIN || n > INT_MAX || d < INT_MIN || d > INT_MAX){ overflow_ = true; float_ = (double)n / (double)d; }else{ ratio_.n_ = static_cast<int>(n); ratio_.d_ = static_cast<int>(d); } return *this; } Rational::operator double() const{ assert(is_convertible<double>()); if(overflow_){ return float_; }else{ return static_cast<double>(numerator()) / static_cast<double>(denominator()); } } Rational& Rational::expt(const Rational& other){ if(other.denominator() != 1){ overflow_ = true; float_ = std::pow(static_cast<double>(*this), static_cast<double>(other)); return *this; } const auto base_r = *this; normalized_reset(1, 1); auto ex = other.numerator(); for(; ex > 0; --ex){ operator*=(base_r); if(overflow_) break; } if(overflow_){ auto base_d = static_cast<double>(base_r); for(; ex > 0; --ex) float_ *= base_d; } return *this; } Rational rationalize(double answer, double error){ // from: // http://en.wikipedia.org/wiki/Continued_fraction#Infinite_continued_fractions double d = answer; int h_2 = 0, h_1 = 1; int k_2 = 1, k_1 = 0; long long h_0; long long k_0; while(1){ auto int_p = (long long)floor(d); auto frac_p = d - floor(d); d = 1 / frac_p; h_0 = int_p * h_1 + h_2; k_0 = int_p * k_1 + k_2; if(h_0 < INT_MIN || h_0 > INT_MAX || k_0 < INT_MIN || k_0 > INT_MAX){ // integer overflow break; } auto sub_ans = (double)h_0 / (double)k_0; if(abs(sub_ans - answer) <= error){ break; } h_2 = h_1; h_1 = (int)h_0; k_2 = k_1; k_1 = (int)k_0; } return Rational{h_0 , k_0}; } // utilities template<> int coerce(Lisp_ptr p){ if(p.tag() == Ptr_tag::integer){ return p.get<int>(); }else{ UNEXP_DEFAULT(); } } template<> Rational coerce(Lisp_ptr p){ if(p.tag() == Ptr_tag::rational){ return *p.get<Rational*>(); }else{ return Rational(coerce<int>(p), 1); } } template<> double coerce(Lisp_ptr p){ if(p.tag() == Ptr_tag::real){ return *(p.get<double*>()); }else{ return static_cast<double>(coerce<Rational>(p)); } } template<> Complex coerce(Lisp_ptr p){ if(p.tag() == Ptr_tag::complex){ return *(p.get<Complex*>()); }else{ return Complex(coerce<double>(p), 0); } } bool is_numeric_type(Lisp_ptr p){ switch(p.tag()){ case Ptr_tag::integer: case Ptr_tag::rational: case Ptr_tag::real: case Ptr_tag::complex: return true; case Ptr_tag::undefined: case Ptr_tag::boolean: case Ptr_tag::character: case Ptr_tag::cons: case Ptr_tag::symbol: case Ptr_tag::i_procedure: case Ptr_tag::n_procedure: case Ptr_tag::continuation: case Ptr_tag::syntax_rules: case Ptr_tag::string: case Ptr_tag::vector: case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: case Ptr_tag::syntactic_closure: case Ptr_tag::vm_op: case Ptr_tag::vm_argcount: case Ptr_tag::notation: default: return false; } } bool is_numeric_convertible(Lisp_ptr p, Ptr_tag tag){ switch(p.tag()){ case Ptr_tag::integer: if(tag == Ptr_tag::integer) return true; // fall through case Ptr_tag::rational: if(tag == Ptr_tag::rational) return true; // fall through case Ptr_tag::real: if(tag == Ptr_tag::real) return true; // fall through case Ptr_tag::complex: return (tag == Ptr_tag::complex); case Ptr_tag::undefined: case Ptr_tag::boolean: case Ptr_tag::character: case Ptr_tag::cons: case Ptr_tag::symbol: case Ptr_tag::i_procedure: case Ptr_tag::n_procedure: case Ptr_tag::continuation: case Ptr_tag::syntax_rules: case Ptr_tag::string: case Ptr_tag::vector: case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: case Ptr_tag::syntactic_closure: case Ptr_tag::vm_op: case Ptr_tag::vm_argcount: case Ptr_tag::notation: default: return false; } } Lisp_ptr wrap_number(const Rational& q){ if(q.is_convertible<int>()){ return Lisp_ptr{static_cast<int>(q)}; }else if(q.is_convertible<Rational>()){ return {zs_new<Rational>(q)}; }else{ print_zs_warning("integer overflow occured. coerced into real."); return {zs_new<double>(static_cast<double>(q))}; } } Lisp_ptr wrap_number(double d){ return {zs_new<double>(d)}; } Lisp_ptr wrap_number(const Complex& z){ return {zs_new<Complex>(z)}; } Lisp_ptr to_exact(Lisp_ptr p){ switch(p.tag()){ case Ptr_tag::integer: case Ptr_tag::rational: return p; case Ptr_tag::real: return wrap_number(static_cast<int>(*p.get<double*>())); case Ptr_tag::complex: throw_zs_error(p, "number error: conversion from complex to exact number is not supprted.\n"); case Ptr_tag::undefined: case Ptr_tag::boolean: case Ptr_tag::character: case Ptr_tag::cons: case Ptr_tag::symbol: case Ptr_tag::i_procedure: case Ptr_tag::n_procedure: case Ptr_tag::continuation: case Ptr_tag::string: case Ptr_tag::vector: case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: case Ptr_tag::syntactic_closure: case Ptr_tag::syntax_rules: case Ptr_tag::vm_op: case Ptr_tag::vm_argcount: case Ptr_tag::notation: default: UNEXP_DEFAULT(); } } Lisp_ptr to_inexact(Lisp_ptr p){ switch(p.tag()){ case Ptr_tag::integer: case Ptr_tag::rational: return wrap_number(coerce<double>(p)); case Ptr_tag::real: case Ptr_tag::complex: return p; case Ptr_tag::undefined: case Ptr_tag::boolean: case Ptr_tag::character: case Ptr_tag::cons: case Ptr_tag::symbol: case Ptr_tag::i_procedure: case Ptr_tag::n_procedure: case Ptr_tag::continuation: case Ptr_tag::string: case Ptr_tag::vector: case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: case Ptr_tag::syntactic_closure: case Ptr_tag::syntax_rules: case Ptr_tag::vm_op: case Ptr_tag::vm_argcount: case Ptr_tag::notation: default: UNEXP_DEFAULT(); } } <commit_msg>trivial cleanup<commit_after>#include <cassert> #include <climits> #include <cmath> #include "rational.hh" #include "zs_error.hh" #include "zs_memory.hh" static_assert(sizeof(int) < sizeof(long long), "integer overflow cannot be treated properly"); using namespace std; // TODO: make this as constructor. Rational& Rational::normalized_reset(long long n, long long d){ if(d == 0) throw_zs_error({}, "Rational::denominator is 0"); auto gcd_val = gcd(n, d); n /= gcd_val; d /= gcd_val; if(d < 0){ n = -n; d = -d; } if(n < INT_MIN || n > INT_MAX || d < INT_MIN || d > INT_MAX){ overflow_ = true; float_ = (double)n / (double)d; }else{ ratio_.n_ = static_cast<int>(n); ratio_.d_ = static_cast<int>(d); } return *this; } Rational::operator double() const{ assert(is_convertible<double>()); if(overflow_){ return float_; }else{ return static_cast<double>(numerator()) / static_cast<double>(denominator()); } } Rational& Rational::expt(const Rational& other){ if(other.denominator() != 1){ overflow_ = true; float_ = std::pow(static_cast<double>(*this), static_cast<double>(other)); return *this; } const auto base_r = *this; normalized_reset(1, 1); auto ex = other.numerator(); for(; ex > 0; --ex){ operator*=(base_r); if(overflow_) break; } if(overflow_){ auto base_d = static_cast<double>(base_r); for(; ex > 0; --ex) float_ *= base_d; } return *this; } Rational rationalize(double answer, double error){ // from: // http://en.wikipedia.org/wiki/Continued_fraction#Infinite_continued_fractions double d = answer; int h_2 = 0, h_1 = 1; int k_2 = 1, k_1 = 0; long long h_0; long long k_0; while(1){ auto int_p = (long long)floor(d); auto frac_p = d - floor(d); d = 1 / frac_p; h_0 = int_p * h_1 + h_2; k_0 = int_p * k_1 + k_2; if(h_0 < INT_MIN || h_0 > INT_MAX || k_0 < INT_MIN || k_0 > INT_MAX){ // integer overflow break; } auto sub_ans = (double)h_0 / (double)k_0; if(abs(sub_ans - answer) <= error){ break; } h_2 = h_1; h_1 = (int)h_0; k_2 = k_1; k_1 = (int)k_0; } return Rational{h_0 , k_0}; } // utilities template<> int coerce(Lisp_ptr p){ if(p.tag() == Ptr_tag::integer){ return p.get<int>(); }else{ UNEXP_DEFAULT(); } } template<> Rational coerce(Lisp_ptr p){ if(p.tag() == Ptr_tag::rational){ return *p.get<Rational*>(); }else{ return Rational(coerce<int>(p)); } } template<> double coerce(Lisp_ptr p){ if(p.tag() == Ptr_tag::real){ return *(p.get<double*>()); }else{ return static_cast<double>(coerce<Rational>(p)); } } template<> Complex coerce(Lisp_ptr p){ if(p.tag() == Ptr_tag::complex){ return *(p.get<Complex*>()); }else{ return Complex(coerce<double>(p), 0); } } bool is_numeric_type(Lisp_ptr p){ switch(p.tag()){ case Ptr_tag::integer: case Ptr_tag::rational: case Ptr_tag::real: case Ptr_tag::complex: return true; case Ptr_tag::undefined: case Ptr_tag::boolean: case Ptr_tag::character: case Ptr_tag::cons: case Ptr_tag::symbol: case Ptr_tag::i_procedure: case Ptr_tag::n_procedure: case Ptr_tag::continuation: case Ptr_tag::syntax_rules: case Ptr_tag::string: case Ptr_tag::vector: case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: case Ptr_tag::syntactic_closure: case Ptr_tag::vm_op: case Ptr_tag::vm_argcount: case Ptr_tag::notation: default: return false; } } bool is_numeric_convertible(Lisp_ptr p, Ptr_tag tag){ switch(p.tag()){ case Ptr_tag::integer: if(tag == Ptr_tag::integer) return true; // fall through case Ptr_tag::rational: if(tag == Ptr_tag::rational) return true; // fall through case Ptr_tag::real: if(tag == Ptr_tag::real) return true; // fall through case Ptr_tag::complex: return (tag == Ptr_tag::complex); case Ptr_tag::undefined: case Ptr_tag::boolean: case Ptr_tag::character: case Ptr_tag::cons: case Ptr_tag::symbol: case Ptr_tag::i_procedure: case Ptr_tag::n_procedure: case Ptr_tag::continuation: case Ptr_tag::syntax_rules: case Ptr_tag::string: case Ptr_tag::vector: case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: case Ptr_tag::syntactic_closure: case Ptr_tag::vm_op: case Ptr_tag::vm_argcount: case Ptr_tag::notation: default: return false; } } Lisp_ptr wrap_number(const Rational& q){ if(q.is_convertible<int>()){ return Lisp_ptr{static_cast<int>(q)}; }else if(q.is_convertible<Rational>()){ return {zs_new<Rational>(q)}; }else{ print_zs_warning("integer overflow occured. coerced into real."); return {zs_new<double>(static_cast<double>(q))}; } } Lisp_ptr wrap_number(double d){ return {zs_new<double>(d)}; } Lisp_ptr wrap_number(const Complex& z){ return {zs_new<Complex>(z)}; } Lisp_ptr to_exact(Lisp_ptr p){ switch(p.tag()){ case Ptr_tag::integer: case Ptr_tag::rational: return p; case Ptr_tag::real: return wrap_number(static_cast<int>(*p.get<double*>())); case Ptr_tag::complex: throw_zs_error(p, "number error: conversion from complex to exact number is not supprted.\n"); case Ptr_tag::undefined: case Ptr_tag::boolean: case Ptr_tag::character: case Ptr_tag::cons: case Ptr_tag::symbol: case Ptr_tag::i_procedure: case Ptr_tag::n_procedure: case Ptr_tag::continuation: case Ptr_tag::string: case Ptr_tag::vector: case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: case Ptr_tag::syntactic_closure: case Ptr_tag::syntax_rules: case Ptr_tag::vm_op: case Ptr_tag::vm_argcount: case Ptr_tag::notation: default: UNEXP_DEFAULT(); } } Lisp_ptr to_inexact(Lisp_ptr p){ switch(p.tag()){ case Ptr_tag::integer: case Ptr_tag::rational: return wrap_number(coerce<double>(p)); case Ptr_tag::real: case Ptr_tag::complex: return p; case Ptr_tag::undefined: case Ptr_tag::boolean: case Ptr_tag::character: case Ptr_tag::cons: case Ptr_tag::symbol: case Ptr_tag::i_procedure: case Ptr_tag::n_procedure: case Ptr_tag::continuation: case Ptr_tag::string: case Ptr_tag::vector: case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: case Ptr_tag::syntactic_closure: case Ptr_tag::syntax_rules: case Ptr_tag::vm_op: case Ptr_tag::vm_argcount: case Ptr_tag::notation: default: UNEXP_DEFAULT(); } } <|endoftext|>
<commit_before><commit_msg>Updated FormattedString function to use precision argument.<commit_after><|endoftext|>
<commit_before>// Demonstrates atomically decrementing a counter in shared memory between // multiple processes using boost named_mutex and interprocess APIs. // // To run: // ./harness.o -num_processes 2 ./test.o // // Author: Sam Xi #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/managed_mapped_file.hpp> #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/sync/named_mutex.hpp> #include "mpkeys.h" int main() { using namespace boost::interprocess; using namespace xiosim::shared; managed_shared_memory shm(open_or_create, XIOSIM_SHARED_MEMORY_KEY.c_str(), DEFAULT_SHARED_MEMORY_SIZE); std::cout << "Opened shared memory" << std::endl; named_mutex init_lock(open_only, XIOSIM_INIT_SHARED_LOCK.c_str()); std::cout << "Opened lock" << std::endl; init_lock.lock(); std::cout << "Lock acquired" << std::endl; int *counter = shm.find_or_construct<int>(XIOSIM_INIT_COUNTER_KEY.c_str())(0); std::cout << "Counter value is: " << *counter << std::endl; (*counter)--; init_lock.unlock(); while (*counter > 0); std::cout << "COntinuing execution." << std::endl; return 0; } <commit_msg>Changed std::string to c strings<commit_after>// Demonstrates atomically decrementing a counter in shared memory between // multiple processes using boost named_mutex and interprocess APIs. // // To run: // ./harness.o -num_processes 2 ./test.o // // Author: Sam Xi #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/managed_mapped_file.hpp> #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/sync/named_mutex.hpp> #include "mpkeys.h" int main() { using namespace boost::interprocess; using namespace xiosim::shared; managed_shared_memory shm(open_or_create, XIOSIM_SHARED_MEMORY_KEY, DEFAULT_SHARED_MEMORY_SIZE); std::cout << "Opened shared memory" << std::endl; named_mutex init_lock(open_only, XIOSIM_INIT_SHARED_LOCK); std::cout << "Opened lock" << std::endl; init_lock.lock(); std::cout << "Lock acquired" << std::endl; int *counter = shm.find_or_construct<int>(XIOSIM_INIT_COUNTER_KEY)(0); std::cout << "Counter value is: " << *counter << std::endl; (*counter)--; init_lock.unlock(); while (*counter > 0); std::cout << "COntinuing execution." << std::endl; return 0; } <|endoftext|>
<commit_before><commit_msg>fix msgs, add optional args to chain/wallet RPC-API additions<commit_after><|endoftext|>
<commit_before><commit_msg>Mark btf as depending on libbpf in --info<commit_after><|endoftext|>
<commit_before><commit_msg>Using MsgPack::select() to filter results<commit_after><|endoftext|>
<commit_before>/* * HttpEndPoint.cpp - Kurento Media Server * * Copyright (C) 2013 Kurento * Contact: Miguel París Díaz <mparisdiaz@gmail.com> * Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "HttpEndPoint.hpp" namespace kurento { HttpEndPoint::HttpEndPoint (std::shared_ptr<MediaPipeline> parent) : EndPoint (parent) { this->type.__set_endPoint (EndPointType::type::HTTP_END_POINT); } HttpEndPoint::~HttpEndPoint() throw () { this->url = "DUMMY URL"; } std::string HttpEndPoint::getUrl () { return url; } } // kurento <commit_msg>Implement constructor and destructor for HttpEndPoint class<commit_after>/* * HttpEndPoint.cpp - Kurento Media Server * * Copyright (C) 2013 Kurento * Contact: Miguel París Díaz <mparisdiaz@gmail.com> * Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "HttpEndPoint.hpp" namespace kurento { HttpEndPoint::HttpEndPoint (std::shared_ptr<MediaPipeline> parent) : EndPoint (parent) { gchar *name; this->type.__set_endPoint (EndPointType::type::HTTP_END_POINT); name = getIdStr (); element = gst_element_factory_make ("httpendpoint", name); g_free (name); g_object_ref (element); gst_bin_add (GST_BIN (parent->pipeline), element); gst_element_sync_state_with_parent (element); } HttpEndPoint::~HttpEndPoint() throw () { gst_bin_remove (GST_BIN ( ( (std::shared_ptr<MediaPipeline> &) parent)->pipeline), element); gst_element_set_state (element, GST_STATE_NULL); g_object_unref (element); } std::string HttpEndPoint::getUrl () { return url; } } // kurento <|endoftext|>
<commit_before>/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #include <ode/ode.h> #include <drawstuff/drawstuff.h> #ifdef _MSC_VER #pragma warning(disable:4244 4305) // for VC++, no precision loss complaints #endif // select correct drawing functions #ifdef dDOUBLE #define dsDrawBox dsDrawBoxD #endif // some constants #define SIDE (0.5f) // side length of a box #define MASS (1.0) // mass of a box // dynamics and collision objects static dWorldID world; static dBodyID body[2]; static dGeomID geom[2]; static dJointID lmotor[2]; static dJointID amotor[2]; static dSpaceID space; static dJointGroupID contactgroup; // start simulation - set viewpoint static void start() { static float xyz[3] = {1.0382f,-1.0811f,1.4700f}; static float hpr[3] = {135.0000f,-19.5000f,0.0000f}; dsSetViewpoint (xyz,hpr); printf ("Press 'q,a,z' to control one axis of lmotor connectiong two bodies. (q is +,a is 0, z is -)\n"); printf ("Press 'w,e,r' to control one axis of lmotor connectiong first body with world. (w is +,e is 0, r is -)\n"); } // called when a key pressed static void command (int cmd) { if (cmd == 'q' || cmd == 'Q') { dJointSetLMotorParam(lmotor[0],dParamVel,0); dJointSetLMotorParam(lmotor[0],dParamVel2,0); dJointSetLMotorParam(lmotor[0],dParamVel3,0.1); } else if (cmd == 'a' || cmd == 'A') { dJointSetLMotorParam(lmotor[0],dParamVel,0); dJointSetLMotorParam(lmotor[0],dParamVel2,0); dJointSetLMotorParam(lmotor[0],dParamVel3,0); } else if (cmd == 'z' || cmd == 'Z') { dJointSetLMotorParam(lmotor[0],dParamVel,0); dJointSetLMotorParam(lmotor[0],dParamVel2,0); dJointSetLMotorParam(lmotor[0],dParamVel3,-0.1); } else if (cmd == 'w' || cmd == 'W') { dJointSetLMotorParam(lmotor[1],dParamVel,0.1); dJointSetLMotorParam(lmotor[1],dParamVel2,0); dJointSetLMotorParam(lmotor[1],dParamVel3,0); } else if (cmd == 'e' || cmd == 'E') { dJointSetLMotorParam(lmotor[1],dParamVel,0); dJointSetLMotorParam(lmotor[1],dParamVel2,0); dJointSetLMotorParam(lmotor[1],dParamVel3,0); } else if (cmd == 'r' || cmd == 'R') { dJointSetLMotorParam(lmotor[1],dParamVel,-0.1); dJointSetLMotorParam(lmotor[1],dParamVel2,0); dJointSetLMotorParam(lmotor[1],dParamVel3,0); } } static void nearCallback (void *data, dGeomID o1, dGeomID o2) { // exit without doing anything if the two bodies are connected by a joint dBodyID b1 = dGeomGetBody(o1); dBodyID b2 = dGeomGetBody(o2); dContact contact; contact.surface.mode = 0; contact.surface.mu = dInfinity; if (dCollide (o1,o2,0,&contact.geom,sizeof(dContactGeom))) { dJointID c = dJointCreateContact (world,contactgroup,&contact); dJointAttach (c,b1,b2); } } // simulation loop static void simLoop (int pause) { if (!pause) { dSpaceCollide(space,0,&nearCallback); dWorldQuickStep (world,0.05); dJointGroupEmpty(contactgroup); } dReal sides1[3]; dGeomBoxGetLengths(geom[0], sides1); dReal sides2[3]; dGeomBoxGetLengths(geom[1], sides2); dsSetTexture (DS_WOOD); dsSetColor (1,1,0); dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides1); dsSetColor (0,1,1); dsDrawBox (dBodyGetPosition(body[1]),dBodyGetRotation(body[1]),sides2); } int main (int argc, char **argv) { // setup pointers to drawstuff callback functions dsFunctions fn; fn.version = DS_VERSION; fn.start = &start; fn.step = &simLoop; fn.command = &command; fn.stop = 0; fn.path_to_textures = "../../drawstuff/textures"; // create world contactgroup = dJointGroupCreate(0); world = dWorldCreate(); space = dSimpleSpaceCreate(0); dMass m; dMassSetBox (&m,1,SIDE,SIDE,SIDE); dMassAdjust (&m,MASS); body[0] = dBodyCreate (world); dBodySetMass (body[0],&m); dBodySetPosition (body[0],0,0,1); geom[0] = dCreateBox(space,SIDE,SIDE,SIDE); body[1] = dBodyCreate (world); dBodySetMass (body[1],&m); dBodySetPosition (body[1],0,0,2); geom[1] = dCreateBox(space,SIDE,SIDE,SIDE); dGeomSetBody(geom[0],body[0]); dGeomSetBody(geom[1],body[1]); lmotor[0] = dJointCreateLMotor (world,0); dJointAttach (lmotor[0],body[0],body[1]); lmotor[1] = dJointCreateLMotor (world,0); dJointAttach (lmotor[1],body[0],0); amotor[0] = dJointCreateAMotor(world,0); dJointAttach(amotor[0], body[0],body[1]); amotor[1] = dJointCreateAMotor(world,0); dJointAttach(amotor[1], body[0], 0); for (int i=0; i<2; i++) { dJointSetAMotorNumAxes(amotor[i], 3); dJointSetAMotorAxis(amotor[i],0,1,1,0,0); dJointSetAMotorAxis(amotor[i],1,1,0,1,0); dJointSetAMotorAxis(amotor[i],2,1,0,0,1); dJointSetAMotorParam(amotor[i],dParamFMax,0.00001); dJointSetAMotorParam(amotor[i],dParamFMax2,0.00001); dJointSetAMotorParam(amotor[i],dParamFMax3,0.00001); dJointSetAMotorParam(amotor[i],dParamVel,0); dJointSetAMotorParam(amotor[i],dParamVel2,0); dJointSetAMotorParam(amotor[i],dParamVel3,0); dJointSetLMotorNumAxes(lmotor[i],3); dJointSetLMotorAxis(lmotor[i],0,1,1,0,0); dJointSetLMotorAxis(lmotor[i],1,1,0,1,0); dJointSetLMotorAxis(lmotor[i],2,1,0,0,1); dJointSetLMotorParam(lmotor[i],dParamFMax,0.0001); dJointSetLMotorParam(lmotor[i],dParamFMax2,0.0001); dJointSetLMotorParam(lmotor[i],dParamFMax3,0.0001); } // run simulation dsSimulationLoop (argc,argv,352,288,&fn); dWorldDestroy (world); dSpaceDestroy (space); dJointGroupDestroy(contactgroup); return 0; } <commit_msg>accept a path to textures<commit_after>/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #include <ode/ode.h> #include <drawstuff/drawstuff.h> #ifdef _MSC_VER #pragma warning(disable:4244 4305) // for VC++, no precision loss complaints #endif // select correct drawing functions #ifdef dDOUBLE #define dsDrawBox dsDrawBoxD #endif // some constants #define SIDE (0.5f) // side length of a box #define MASS (1.0) // mass of a box // dynamics and collision objects static dWorldID world; static dBodyID body[2]; static dGeomID geom[2]; static dJointID lmotor[2]; static dJointID amotor[2]; static dSpaceID space; static dJointGroupID contactgroup; // start simulation - set viewpoint static void start() { static float xyz[3] = {1.0382f,-1.0811f,1.4700f}; static float hpr[3] = {135.0000f,-19.5000f,0.0000f}; dsSetViewpoint (xyz,hpr); printf ("Press 'q,a,z' to control one axis of lmotor connectiong two bodies. (q is +,a is 0, z is -)\n"); printf ("Press 'w,e,r' to control one axis of lmotor connectiong first body with world. (w is +,e is 0, r is -)\n"); } // called when a key pressed static void command (int cmd) { if (cmd == 'q' || cmd == 'Q') { dJointSetLMotorParam(lmotor[0],dParamVel,0); dJointSetLMotorParam(lmotor[0],dParamVel2,0); dJointSetLMotorParam(lmotor[0],dParamVel3,0.1); } else if (cmd == 'a' || cmd == 'A') { dJointSetLMotorParam(lmotor[0],dParamVel,0); dJointSetLMotorParam(lmotor[0],dParamVel2,0); dJointSetLMotorParam(lmotor[0],dParamVel3,0); } else if (cmd == 'z' || cmd == 'Z') { dJointSetLMotorParam(lmotor[0],dParamVel,0); dJointSetLMotorParam(lmotor[0],dParamVel2,0); dJointSetLMotorParam(lmotor[0],dParamVel3,-0.1); } else if (cmd == 'w' || cmd == 'W') { dJointSetLMotorParam(lmotor[1],dParamVel,0.1); dJointSetLMotorParam(lmotor[1],dParamVel2,0); dJointSetLMotorParam(lmotor[1],dParamVel3,0); } else if (cmd == 'e' || cmd == 'E') { dJointSetLMotorParam(lmotor[1],dParamVel,0); dJointSetLMotorParam(lmotor[1],dParamVel2,0); dJointSetLMotorParam(lmotor[1],dParamVel3,0); } else if (cmd == 'r' || cmd == 'R') { dJointSetLMotorParam(lmotor[1],dParamVel,-0.1); dJointSetLMotorParam(lmotor[1],dParamVel2,0); dJointSetLMotorParam(lmotor[1],dParamVel3,0); } } static void nearCallback (void *data, dGeomID o1, dGeomID o2) { // exit without doing anything if the two bodies are connected by a joint dBodyID b1 = dGeomGetBody(o1); dBodyID b2 = dGeomGetBody(o2); dContact contact; contact.surface.mode = 0; contact.surface.mu = dInfinity; if (dCollide (o1,o2,0,&contact.geom,sizeof(dContactGeom))) { dJointID c = dJointCreateContact (world,contactgroup,&contact); dJointAttach (c,b1,b2); } } // simulation loop static void simLoop (int pause) { if (!pause) { dSpaceCollide(space,0,&nearCallback); dWorldQuickStep (world,0.05); dJointGroupEmpty(contactgroup); } dReal sides1[3]; dGeomBoxGetLengths(geom[0], sides1); dReal sides2[3]; dGeomBoxGetLengths(geom[1], sides2); dsSetTexture (DS_WOOD); dsSetColor (1,1,0); dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides1); dsSetColor (0,1,1); dsDrawBox (dBodyGetPosition(body[1]),dBodyGetRotation(body[1]),sides2); } int main (int argc, char **argv) { // setup pointers to drawstuff callback functions dsFunctions fn; fn.version = DS_VERSION; fn.start = &start; fn.step = &simLoop; fn.command = &command; fn.stop = 0; fn.path_to_textures = "../../drawstuff/textures"; if(argc>=2) { fn.path_to_textures = argv[1]; } // create world contactgroup = dJointGroupCreate(0); world = dWorldCreate(); space = dSimpleSpaceCreate(0); dMass m; dMassSetBox (&m,1,SIDE,SIDE,SIDE); dMassAdjust (&m,MASS); body[0] = dBodyCreate (world); dBodySetMass (body[0],&m); dBodySetPosition (body[0],0,0,1); geom[0] = dCreateBox(space,SIDE,SIDE,SIDE); body[1] = dBodyCreate (world); dBodySetMass (body[1],&m); dBodySetPosition (body[1],0,0,2); geom[1] = dCreateBox(space,SIDE,SIDE,SIDE); dGeomSetBody(geom[0],body[0]); dGeomSetBody(geom[1],body[1]); lmotor[0] = dJointCreateLMotor (world,0); dJointAttach (lmotor[0],body[0],body[1]); lmotor[1] = dJointCreateLMotor (world,0); dJointAttach (lmotor[1],body[0],0); amotor[0] = dJointCreateAMotor(world,0); dJointAttach(amotor[0], body[0],body[1]); amotor[1] = dJointCreateAMotor(world,0); dJointAttach(amotor[1], body[0], 0); for (int i=0; i<2; i++) { dJointSetAMotorNumAxes(amotor[i], 3); dJointSetAMotorAxis(amotor[i],0,1,1,0,0); dJointSetAMotorAxis(amotor[i],1,1,0,1,0); dJointSetAMotorAxis(amotor[i],2,1,0,0,1); dJointSetAMotorParam(amotor[i],dParamFMax,0.00001); dJointSetAMotorParam(amotor[i],dParamFMax2,0.00001); dJointSetAMotorParam(amotor[i],dParamFMax3,0.00001); dJointSetAMotorParam(amotor[i],dParamVel,0); dJointSetAMotorParam(amotor[i],dParamVel2,0); dJointSetAMotorParam(amotor[i],dParamVel3,0); dJointSetLMotorNumAxes(lmotor[i],3); dJointSetLMotorAxis(lmotor[i],0,1,1,0,0); dJointSetLMotorAxis(lmotor[i],1,1,0,1,0); dJointSetLMotorAxis(lmotor[i],2,1,0,0,1); dJointSetLMotorParam(lmotor[i],dParamFMax,0.0001); dJointSetLMotorParam(lmotor[i],dParamFMax2,0.0001); dJointSetLMotorParam(lmotor[i],dParamFMax3,0.0001); } // run simulation dsSimulationLoop (argc,argv,352,288,&fn); dWorldDestroy (world); dSpaceDestroy (space); dJointGroupDestroy(contactgroup); return 0; } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2015 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "query_pagers.hh" #include "query_pager.hh" #include "cql3/selection/selection.hh" #include "log.hh" #include "service/storage_proxy.hh" #include "to_string.hh" static logging::logger qlogger("paging"); class service::pager::query_pagers::impl : public query_pager { public: impl(schema_ptr s, ::shared_ptr<cql3::selection::selection> selection, service::query_state& state, const cql3::query_options& options, lw_shared_ptr<query::read_command> cmd, dht::partition_range_vector ranges) : _has_clustering_keys(has_clustering_keys(*s, *cmd)) , _max(cmd->row_limit) , _schema(std::move(s)) , _selection(selection) , _state(state) , _options(options) , _cmd(std::move(cmd)) , _ranges(std::move(ranges)) {} private: static bool has_clustering_keys(const schema& s, const query::read_command& cmd) { return s.clustering_key_size() > 0 && !cmd.slice.options.contains<query::partition_slice::option::distinct>(); } future<> fetch_page(cql3::selection::result_set_builder& builder, uint32_t page_size, gc_clock::time_point now) override { auto state = _options.get_paging_state(); if (!_last_pkey && state) { _max = state->get_remaining(); _last_pkey = state->get_partition_key(); _last_ckey = state->get_clustering_key(); _cmd->query_uuid = state->get_query_uuid(); _cmd->is_first_page = false; } else { // Reusing readers is currently only supported for singular queries. if (_ranges.front().is_singular()) { _cmd->query_uuid = utils::make_random_uuid(); } _cmd->is_first_page = true; } qlogger.trace("fetch_page query id {}", _cmd->query_uuid); if (_last_pkey) { auto dpk = dht::global_partitioner().decorate_key(*_schema, *_last_pkey); dht::ring_position lo(dpk); auto reversed = _cmd->slice.options.contains<query::partition_slice::option::reversed>(); qlogger.trace("PKey={}, CKey={}, reversed={}", dpk, _last_ckey, reversed); // Note: we're assuming both that the ranges are checked // and "cql-compliant", and that storage_proxy will process // the ranges in order // // If the original query has singular restrictions like "col in (x, y, z)", // we will eventually generate an empty range. This is ok, because empty range == nothing, // which is what we thus mean. auto modify_ranges = [reversed](auto& ranges, auto& lo, bool inclusive, const auto& cmp) { typedef typename std::remove_reference_t<decltype(ranges)>::value_type range_type; typedef typename range_type::bound bound_type; bool found = false; auto i = ranges.begin(); while (i != ranges.end()) { bool contains = i->contains(lo, cmp); if (contains) { found = true; } bool remove = !found || (contains && !inclusive && (i->is_singular() || (reversed && i->start() && !cmp(i->start()->value(), lo)) || (!reversed && i->end() && !cmp(i->end()->value(), lo)))) ; if (remove) { qlogger.trace("Remove range {}", *i); i = ranges.erase(i); continue; } if (contains) { auto r = reversed && !i->is_singular() ? range_type(i->start(), bound_type{ lo, inclusive }) : range_type( bound_type{ lo, inclusive }, i->end(), i->is_singular()) ; qlogger.trace("Modify range {} -> {}", *i, r); *i = std::move(r); } ++i; } qlogger.trace("Result ranges {}", ranges); }; // Because of #1446 we don't have a comparator to use with // range<clustering_key_prefix> which would produce correct results. // This means we cannot reuse the same logic for dealing with // partition and clustering keys. auto modify_ck_ranges = [reversed] (const schema& s, auto& ranges, auto& lo) { typedef typename std::remove_reference_t<decltype(ranges)>::value_type range_type; typedef typename range_type::bound bound_type; auto cmp = [reversed, bv_cmp = bound_view::compare(s)] (const auto& a, const auto& b) { return reversed ? bv_cmp(b, a) : bv_cmp(a, b); }; auto start_bound = [reversed] (const auto& range) -> const bound_view& { return reversed ? range.second : range.first; }; auto end_bound = [reversed] (const auto& range) -> const bound_view& { return reversed ? range.first : range.second; }; clustering_key_prefix::equality eq(s); auto it = ranges.begin(); while (it != ranges.end()) { auto range = bound_view::from_range(*it); if (cmp(end_bound(range), lo) || eq(end_bound(range).prefix, lo)) { qlogger.trace("Remove ck range {}", *it); it = ranges.erase(it); continue; } else if (cmp(start_bound(range), lo)) { assert(cmp(lo, end_bound(range))); auto r = reversed ? range_type(it->start(), bound_type { lo, false }) : range_type(bound_type { lo, false }, it->end()); qlogger.trace("Modify ck range {} -> {}", *it, r); *it = std::move(r); } ++it; } }; // last ck can be empty depending on whether we // deserialized state or not. This case means "last page ended on // something-not-bound-by-clustering" (i.e. a static row, alone) const bool has_ck = _has_clustering_keys && _last_ckey; // If we have no clustering keys, it should mean we only have one row // per PK. Thus we can just bypass the last one. modify_ranges(_ranges, lo, has_ck, dht::ring_position_comparator(*_schema)); if (has_ck) { query::clustering_row_ranges row_ranges = _cmd->slice.default_row_ranges(); clustering_key_prefix ckp = clustering_key_prefix::from_exploded(*_schema, _last_ckey->explode(*_schema)); modify_ck_ranges(*_schema, row_ranges, ckp); _cmd->slice.set_range(*_schema, *_last_pkey, row_ranges); } } auto max_rows = std::min(_max, page_size); // We always need PK so we can determine where to start next. _cmd->slice.options.set<query::partition_slice::option::send_partition_key>(); // don't add empty bytes (cks) unless we have to if (_has_clustering_keys) { _cmd->slice.options.set< query::partition_slice::option::send_clustering_key>(); } _cmd->row_limit = max_rows; qlogger.debug("Fetching {}, page size={}, max_rows={}", _cmd->cf_id, page_size, max_rows ); auto ranges = _ranges; auto command = ::make_lw_shared<query::read_command>(*_cmd); return get_local_storage_proxy().query(_schema, std::move(command), std::move(ranges), _options.get_consistency(), _state.get_trace_state()).then( [this, &builder, page_size, now](foreign_ptr<lw_shared_ptr<query::result>> results, paging_state::replicas_per_token_range) { handle_result(builder, std::move(results), page_size, now); }); } future<std::unique_ptr<cql3::result_set>> fetch_page(uint32_t page_size, gc_clock::time_point now) override { return do_with( cql3::selection::result_set_builder(*_selection, now, _options.get_cql_serialization_format()), [this, page_size, now](auto& builder) { return this->fetch_page(builder, page_size, now).then([&builder] { return builder.build(); }); }); } void handle_result( cql3::selection::result_set_builder& builder, foreign_ptr<lw_shared_ptr<query::result>> results, uint32_t page_size, gc_clock::time_point now) { class myvisitor : public cql3::selection::result_set_builder::visitor { public: uint32_t total_rows = 0; std::experimental::optional<partition_key> last_pkey; std::experimental::optional<clustering_key> last_ckey; myvisitor(cql3::selection::result_set_builder& builder, const schema& s, const cql3::selection::selection& selection) : visitor(builder, s, selection) { } void accept_new_partition(uint32_t) { throw std::logic_error("Should not reach!"); } void accept_new_partition(const partition_key& key, uint32_t row_count) { qlogger.trace("Accepting partition: {} ({})", key, row_count); total_rows += std::max(row_count, 1u); last_pkey = key; last_ckey = { }; visitor::accept_new_partition(key, row_count); } void accept_new_row(const clustering_key& key, const query::result_row_view& static_row, const query::result_row_view& row) { last_ckey = key; visitor::accept_new_row(key, static_row, row); } void accept_new_row(const query::result_row_view& static_row, const query::result_row_view& row) { visitor::accept_new_row(static_row, row); } void accept_partition_end(const query::result_row_view& static_row) { visitor::accept_partition_end(static_row); } }; myvisitor v(builder, *_schema, *_selection); query::result_view::consume(*results, _cmd->slice, v); if (_last_pkey) { // refs #752, when doing aggregate queries we will re-use same // slice repeatedly. Since "specific ck ranges" only deal with // a single extra range, we must clear out the old one // Even if it was not so of course, leaving junk in the slice // is bad. _cmd->slice.clear_range(*_schema, *_last_pkey); } _max = _max - v.total_rows; _exhausted = (v.total_rows < page_size && !results->is_short_read()) || _max == 0; _last_pkey = v.last_pkey; _last_ckey = v.last_ckey; qlogger.debug("Fetched {} rows, max_remain={} {}", v.total_rows, _max, _exhausted ? "(exh)" : ""); if (_last_pkey) { qlogger.debug("Last partition key: {}", *_last_pkey); } if (_has_clustering_keys && _last_ckey) { qlogger.debug("Last clustering key: {}", *_last_ckey); } } bool is_exhausted() const override { return _exhausted; } int max_remaining() const override { return _max; } ::shared_ptr<const service::pager::paging_state> state() const override { return _exhausted ? nullptr : ::make_shared<const paging_state>(*_last_pkey, _last_ckey, _max, _cmd->query_uuid, paging_state::replicas_per_token_range{}); } private: // remember if we use clustering. if not, each partition == one row const bool _has_clustering_keys; bool _exhausted = false; uint32_t _max; std::experimental::optional<partition_key> _last_pkey; std::experimental::optional<clustering_key> _last_ckey; schema_ptr _schema; ::shared_ptr<cql3::selection::selection> _selection; service::query_state& _state; const cql3::query_options& _options; lw_shared_ptr<query::read_command> _cmd; dht::partition_range_vector _ranges; }; bool service::pager::query_pagers::may_need_paging(uint32_t page_size, const query::read_command& cmd, const dht::partition_range_vector& ranges) { auto est_max_rows = [&] { if (ranges.empty()) { return cmd.row_limit; } uint32_t n = 0; for (auto& r : ranges) { if (r.is_singular() && cmd.slice.options.contains<query::partition_slice::option::distinct>()) { ++n; continue; } return cmd.row_limit; } return n; }; auto est = est_max_rows(); auto need_paging = est > page_size; qlogger.debug("Query of {}, page_size={}, limit={} {}", cmd.cf_id, page_size, cmd.row_limit, need_paging ? "requires paging" : "does not require paging"); return need_paging; } ::shared_ptr<service::pager::query_pager> service::pager::query_pagers::pager( schema_ptr s, ::shared_ptr<cql3::selection::selection> selection, service::query_state& state, const cql3::query_options& options, lw_shared_ptr<query::read_command> cmd, dht::partition_range_vector ranges) { return ::make_shared<impl>(std::move(s), std::move(selection), state, options, std::move(cmd), std::move(ranges)); } <commit_msg>Use the last_replicas stored in the page_state<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2015 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "query_pagers.hh" #include "query_pager.hh" #include "cql3/selection/selection.hh" #include "log.hh" #include "service/storage_proxy.hh" #include "to_string.hh" static logging::logger qlogger("paging"); class service::pager::query_pagers::impl : public query_pager { public: impl(schema_ptr s, ::shared_ptr<cql3::selection::selection> selection, service::query_state& state, const cql3::query_options& options, lw_shared_ptr<query::read_command> cmd, dht::partition_range_vector ranges) : _has_clustering_keys(has_clustering_keys(*s, *cmd)) , _max(cmd->row_limit) , _schema(std::move(s)) , _selection(selection) , _state(state) , _options(options) , _cmd(std::move(cmd)) , _ranges(std::move(ranges)) {} private: static bool has_clustering_keys(const schema& s, const query::read_command& cmd) { return s.clustering_key_size() > 0 && !cmd.slice.options.contains<query::partition_slice::option::distinct>(); } future<> fetch_page(cql3::selection::result_set_builder& builder, uint32_t page_size, gc_clock::time_point now) override { auto state = _options.get_paging_state(); if (!_last_pkey && state) { _max = state->get_remaining(); _last_pkey = state->get_partition_key(); _last_ckey = state->get_clustering_key(); _cmd->query_uuid = state->get_query_uuid(); _cmd->is_first_page = false; _last_replicas = state->get_last_replicas(); } else { // Reusing readers is currently only supported for singular queries. if (_ranges.front().is_singular()) { _cmd->query_uuid = utils::make_random_uuid(); } _cmd->is_first_page = true; } qlogger.trace("fetch_page query id {}", _cmd->query_uuid); if (_last_pkey) { auto dpk = dht::global_partitioner().decorate_key(*_schema, *_last_pkey); dht::ring_position lo(dpk); auto reversed = _cmd->slice.options.contains<query::partition_slice::option::reversed>(); qlogger.trace("PKey={}, CKey={}, reversed={}", dpk, _last_ckey, reversed); // Note: we're assuming both that the ranges are checked // and "cql-compliant", and that storage_proxy will process // the ranges in order // // If the original query has singular restrictions like "col in (x, y, z)", // we will eventually generate an empty range. This is ok, because empty range == nothing, // which is what we thus mean. auto modify_ranges = [reversed](auto& ranges, auto& lo, bool inclusive, const auto& cmp) { typedef typename std::remove_reference_t<decltype(ranges)>::value_type range_type; typedef typename range_type::bound bound_type; bool found = false; auto i = ranges.begin(); while (i != ranges.end()) { bool contains = i->contains(lo, cmp); if (contains) { found = true; } bool remove = !found || (contains && !inclusive && (i->is_singular() || (reversed && i->start() && !cmp(i->start()->value(), lo)) || (!reversed && i->end() && !cmp(i->end()->value(), lo)))) ; if (remove) { qlogger.trace("Remove range {}", *i); i = ranges.erase(i); continue; } if (contains) { auto r = reversed && !i->is_singular() ? range_type(i->start(), bound_type{ lo, inclusive }) : range_type( bound_type{ lo, inclusive }, i->end(), i->is_singular()) ; qlogger.trace("Modify range {} -> {}", *i, r); *i = std::move(r); } ++i; } qlogger.trace("Result ranges {}", ranges); }; // Because of #1446 we don't have a comparator to use with // range<clustering_key_prefix> which would produce correct results. // This means we cannot reuse the same logic for dealing with // partition and clustering keys. auto modify_ck_ranges = [reversed] (const schema& s, auto& ranges, auto& lo) { typedef typename std::remove_reference_t<decltype(ranges)>::value_type range_type; typedef typename range_type::bound bound_type; auto cmp = [reversed, bv_cmp = bound_view::compare(s)] (const auto& a, const auto& b) { return reversed ? bv_cmp(b, a) : bv_cmp(a, b); }; auto start_bound = [reversed] (const auto& range) -> const bound_view& { return reversed ? range.second : range.first; }; auto end_bound = [reversed] (const auto& range) -> const bound_view& { return reversed ? range.first : range.second; }; clustering_key_prefix::equality eq(s); auto it = ranges.begin(); while (it != ranges.end()) { auto range = bound_view::from_range(*it); if (cmp(end_bound(range), lo) || eq(end_bound(range).prefix, lo)) { qlogger.trace("Remove ck range {}", *it); it = ranges.erase(it); continue; } else if (cmp(start_bound(range), lo)) { assert(cmp(lo, end_bound(range))); auto r = reversed ? range_type(it->start(), bound_type { lo, false }) : range_type(bound_type { lo, false }, it->end()); qlogger.trace("Modify ck range {} -> {}", *it, r); *it = std::move(r); } ++it; } }; // last ck can be empty depending on whether we // deserialized state or not. This case means "last page ended on // something-not-bound-by-clustering" (i.e. a static row, alone) const bool has_ck = _has_clustering_keys && _last_ckey; // If we have no clustering keys, it should mean we only have one row // per PK. Thus we can just bypass the last one. modify_ranges(_ranges, lo, has_ck, dht::ring_position_comparator(*_schema)); if (has_ck) { query::clustering_row_ranges row_ranges = _cmd->slice.default_row_ranges(); clustering_key_prefix ckp = clustering_key_prefix::from_exploded(*_schema, _last_ckey->explode(*_schema)); modify_ck_ranges(*_schema, row_ranges, ckp); _cmd->slice.set_range(*_schema, *_last_pkey, row_ranges); } } auto max_rows = std::min(_max, page_size); // We always need PK so we can determine where to start next. _cmd->slice.options.set<query::partition_slice::option::send_partition_key>(); // don't add empty bytes (cks) unless we have to if (_has_clustering_keys) { _cmd->slice.options.set< query::partition_slice::option::send_clustering_key>(); } _cmd->row_limit = max_rows; qlogger.debug("Fetching {}, page size={}, max_rows={}", _cmd->cf_id, page_size, max_rows ); auto ranges = _ranges; auto command = ::make_lw_shared<query::read_command>(*_cmd); auto& sp = get_local_storage_proxy(); return sp.query(_schema, std::move(command), std::move(ranges), _options.get_consistency(), _state.get_trace_state(), sp.default_query_timeout(), std::move(_last_replicas)).then( [this, &builder, page_size, now](foreign_ptr<lw_shared_ptr<query::result>> results, paging_state::replicas_per_token_range last_replicas) { _last_replicas = std::move(last_replicas); handle_result(builder, std::move(results), page_size, now); }); } future<std::unique_ptr<cql3::result_set>> fetch_page(uint32_t page_size, gc_clock::time_point now) override { return do_with( cql3::selection::result_set_builder(*_selection, now, _options.get_cql_serialization_format()), [this, page_size, now](auto& builder) { return this->fetch_page(builder, page_size, now).then([&builder] { return builder.build(); }); }); } void handle_result( cql3::selection::result_set_builder& builder, foreign_ptr<lw_shared_ptr<query::result>> results, uint32_t page_size, gc_clock::time_point now) { class myvisitor : public cql3::selection::result_set_builder::visitor { public: uint32_t total_rows = 0; std::experimental::optional<partition_key> last_pkey; std::experimental::optional<clustering_key> last_ckey; myvisitor(cql3::selection::result_set_builder& builder, const schema& s, const cql3::selection::selection& selection) : visitor(builder, s, selection) { } void accept_new_partition(uint32_t) { throw std::logic_error("Should not reach!"); } void accept_new_partition(const partition_key& key, uint32_t row_count) { qlogger.trace("Accepting partition: {} ({})", key, row_count); total_rows += std::max(row_count, 1u); last_pkey = key; last_ckey = { }; visitor::accept_new_partition(key, row_count); } void accept_new_row(const clustering_key& key, const query::result_row_view& static_row, const query::result_row_view& row) { last_ckey = key; visitor::accept_new_row(key, static_row, row); } void accept_new_row(const query::result_row_view& static_row, const query::result_row_view& row) { visitor::accept_new_row(static_row, row); } void accept_partition_end(const query::result_row_view& static_row) { visitor::accept_partition_end(static_row); } }; myvisitor v(builder, *_schema, *_selection); query::result_view::consume(*results, _cmd->slice, v); if (_last_pkey) { // refs #752, when doing aggregate queries we will re-use same // slice repeatedly. Since "specific ck ranges" only deal with // a single extra range, we must clear out the old one // Even if it was not so of course, leaving junk in the slice // is bad. _cmd->slice.clear_range(*_schema, *_last_pkey); } _max = _max - v.total_rows; _exhausted = (v.total_rows < page_size && !results->is_short_read()) || _max == 0; _last_pkey = v.last_pkey; _last_ckey = v.last_ckey; qlogger.debug("Fetched {} rows, max_remain={} {}", v.total_rows, _max, _exhausted ? "(exh)" : ""); if (_last_pkey) { qlogger.debug("Last partition key: {}", *_last_pkey); } if (_has_clustering_keys && _last_ckey) { qlogger.debug("Last clustering key: {}", *_last_ckey); } } bool is_exhausted() const override { return _exhausted; } int max_remaining() const override { return _max; } ::shared_ptr<const service::pager::paging_state> state() const override { return _exhausted ? nullptr : ::make_shared<const paging_state>(*_last_pkey, _last_ckey, _max, _cmd->query_uuid, _last_replicas); } private: // remember if we use clustering. if not, each partition == one row const bool _has_clustering_keys; bool _exhausted = false; uint32_t _max; std::experimental::optional<partition_key> _last_pkey; std::experimental::optional<clustering_key> _last_ckey; schema_ptr _schema; ::shared_ptr<cql3::selection::selection> _selection; service::query_state& _state; const cql3::query_options& _options; lw_shared_ptr<query::read_command> _cmd; dht::partition_range_vector _ranges; paging_state::replicas_per_token_range _last_replicas; }; bool service::pager::query_pagers::may_need_paging(uint32_t page_size, const query::read_command& cmd, const dht::partition_range_vector& ranges) { auto est_max_rows = [&] { if (ranges.empty()) { return cmd.row_limit; } uint32_t n = 0; for (auto& r : ranges) { if (r.is_singular() && cmd.slice.options.contains<query::partition_slice::option::distinct>()) { ++n; continue; } return cmd.row_limit; } return n; }; auto est = est_max_rows(); auto need_paging = est > page_size; qlogger.debug("Query of {}, page_size={}, limit={} {}", cmd.cf_id, page_size, cmd.row_limit, need_paging ? "requires paging" : "does not require paging"); return need_paging; } ::shared_ptr<service::pager::query_pager> service::pager::query_pagers::pager( schema_ptr s, ::shared_ptr<cql3::selection::selection> selection, service::query_state& state, const cql3::query_options& options, lw_shared_ptr<query::read_command> cmd, dht::partition_range_vector ranges) { return ::make_shared<impl>(std::move(s), std::move(selection), state, options, std::move(cmd), std::move(ranges)); } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "jubatus_serv.hpp" #include "../common/util.hpp" #include "../common/cht.hpp" #include "../common/exception.hpp" #include "server_util.hpp" #include <fstream> #include <sstream> #include <pficommon/system/time_util.h> using std::vector; using std::string; using pfi::network::mprpc::rpc_client; using pfi::lang::function; using pfi::system::time::clock_time; using pfi::system::time::get_clock_time; namespace jubatus { namespace framework { jubatus_serv::jubatus_serv(const server_argv& a, const std::string& base_path): a_(a), update_count_(0), #ifdef HAVE_ZOOKEEPER_H mixer_(new mixer(a_.name, a_.interval_count, a_.interval_sec, pfi::lang::bind(&jubatus_serv::do_mix, this, pfi::lang::_1))), use_cht_(false), #endif base_path_(a_.tmpdir) { }; int jubatus_serv::start(pfi::network::mprpc::rpc_server& serv){ #ifdef HAVE_ZOOKEEPER_H if(! a_.is_standalone()){ zk_ = pfi::lang::shared_ptr<jubatus::common::lock_service> (common::create_lock_service("zk", a_.z, a_.timeout, "logfile_jubatus_serv")); ls = zk_; jubatus::common::prepare_jubatus(*zk_); if( a_.join ){ // join to the existing cluster with -j option join_to_cluster(zk_); } if( use_cht_ ){ jubatus::common::cht::setup_cht_dir(*zk_, a_.name); jubatus::common::cht ht(zk_, a_.name); ht.register_node(a_.eth, a_.port); } mixer_->set_zk(zk_); register_actor(*zk_, a_.name, a_.eth, a_.port); mixer_->start(); } #endif { LOG(INFO) << "running in port=" << a_.port; } return serv.serv(a_.port, a_.threadnum); } void jubatus_serv::register_mixable(mixable0* m){ #ifdef HAVE_ZOOKEEPER_H mixables_.push_back(m); #endif }; void jubatus_serv::use_cht(){ #ifdef HAVE_ZOOKEEPER_H use_cht_ = true; #endif }; std::map<std::string, std::map<std::string,std::string> > jubatus_serv::get_status(int) const { std::map<std::string, std::string> data; util::get_machine_status(data); data["timeout"] = pfi::lang::lexical_cast<std::string>(a_.timeout); data["threadnum"] = pfi::lang::lexical_cast<std::string>(a_.threadnum); data["tmpdir"] = a_.tmpdir; data["interval_sec"] = pfi::lang::lexical_cast<std::string>(a_.interval_sec); data["interval_count"] = pfi::lang::lexical_cast<std::string>(a_.interval_count); data["is_standalone"] = pfi::lang::lexical_cast<std::string>(a_.is_standalone()); data["VERSION"] = JUBATUS_VERSION; data["PROGNAME"] = JUBATUS_APPNAME; data["update_count"] = pfi::lang::lexical_cast<std::string>(update_count_); #ifdef HAVE_ZOOKEEPER_H mixer_->get_status(data); data["zk"] = a_.z; data["use_cht"] = pfi::lang::lexical_cast<std::string>(use_cht_); #endif std::map<std::string, std::map<std::string,std::string> > ret; ret[get_server_identifier()] = data; return ret; }; std::string jubatus_serv::get_server_identifier()const{ std::stringstream ss; ss << a_.eth; ss << "_"; ss << a_.port; return ss.str(); }; //here #ifdef HAVE_ZOOKEEPER_H void jubatus_serv::join_to_cluster(pfi::lang::shared_ptr<jubatus::common::lock_service> z){ std::vector<std::string> list; std::string path = common::ACTOR_BASE_PATH + "/" + a_.name + "/nodes"; z->list(path, list); if(not list.empty()){ common::lock_service_mutex zlk(*z, common::ACTOR_BASE_PATH + "/" + a_.name + "/master_lock"); while(not zlk.try_lock()){ ; } size_t i = rand() % list.size(); std::string ip; int port; common::revert(list[i], ip, port); pfi::network::mprpc::rpc_client c(ip, port, a_.timeout); pfi::lang::function<std::string()> f = c.call<std::string()>("get_storage"); std::stringstream ss( f() ); for(size_t i = 0;i<mixables_.size(); ++i){ mixables_[i]->clear(); mixables_[i]->load(ss); } } }; std::string jubatus_serv::get_storage(int i){ std::stringstream ss; for(size_t i=0; i<mixables_.size(); ++i){ mixables_[i]->save(ss); } return ss.str(); } std::vector<std::string> jubatus_serv::get_diff_impl(int){ // if(mixables_.empty()){ // //throw config_not_set(); nothing to mix // } std::vector<std::string> o; { scoped_lock lk(rlock(m_)); for(size_t i=0; i<mixables_.size(); ++i){ o.push_back(mixables_[i]->get_diff()); } } return o; }; int jubatus_serv::put_diff_impl(std::vector<std::string> unpacked){ scoped_lock lk(wlock(m_)); if(unpacked.size() != mixables_.size()){ //deserialization error } for(size_t i=0; i<mixables_.size(); ++i){ mixables_[i]->put_diff(unpacked[i]); } return 0; }; void jubatus_serv::do_mix(const std::vector<std::pair<std::string,int> >& v){ vector<string> accs; vector<string> serialized_diffs; clock_time start = get_clock_time(); for(size_t s = 0; s < v.size(); ++s ){ try{ rpc_client c(v[s].first, v[s].second, a_.timeout); function<vector<string>(int)> get_diff_fun = c.call<vector<string>(int)>("get_diff"); serialized_diffs = get_diff_fun(0); }catch(std::exception& e){ LOG(ERROR) << e.what(); continue; } scoped_lock lk(rlock(m_)); // model_ should not be in mix (reduce)? if(accs.empty()){ accs = serialized_diffs; }else{ for(size_t i=0; i<mixables_.size(); ++i){ // FIXME: very inefficient but what sucks is type system of C++ mixables_[i]->reduce(serialized_diffs[i], accs[i]); } } } for(size_t s = 0; s < v.size(); ++s ){ try{ rpc_client c(v[s].first, v[s].second, a_.timeout); function<int(vector<string>)> put_diff_fun = c.call<int(vector<string>)>("put_diff"); put_diff_fun(accs); }catch(std::exception& e){ LOG(ERROR) << e.what(); continue; } } clock_time end = get_clock_time(); DLOG(INFO) << "mixed with " << v.size() << " servers in " << (double)(end - start) << " secs."; size_t s = 0; for(size_t i=0; i<accs.size(); ++i){ s+=accs[i].size(); } DLOG(INFO) << s << " bytes (serialized data) has been put."; } #endif int jubatus_serv::save(std::string id) { std::string ofile; build_local_path_(ofile, "jubatus", id); std::ofstream ofs(ofile.c_str(), std::ios::trunc|std::ios::binary); if(!ofs){ throw std::runtime_error(ofile + ": cannot open (" + pfi::lang::lexical_cast<std::string>(errno) + ")" ); } try{ for(size_t i=0; i<mixables_.size(); ++i){ mixables_[i]->save(ofs); } ofs.close(); LOG(INFO) << "saved to " << ofile; return 0; }catch(const std::exception& e){ return -1; } } int jubatus_serv::load(std::string id) { std::string ifile; build_local_path_(ifile, "jubatus", id); std::ifstream ifs(ifile.c_str(), std::ios::binary); if(!ifs)throw std::runtime_error(ifile + ": cannot open (" + pfi::lang::lexical_cast<std::string>(errno) + ")" ); try{ for(size_t i = 0;i<mixables_.size(); ++i){ mixables_[i]->clear(); mixables_[i]->load(ifs); } ifs.close(); this->after_load(); return 0; }catch(const std::exception& e){ ifs.close(); } return -1; //expected never reaching here. } }} <commit_msg>add safety check in case of bad pointer passed to mixable set. (fixes #22)<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "jubatus_serv.hpp" #include "../common/util.hpp" #include "../common/cht.hpp" #include "../common/exception.hpp" #include "server_util.hpp" #include <fstream> #include <sstream> #include <pficommon/system/time_util.h> using std::vector; using std::string; using pfi::network::mprpc::rpc_client; using pfi::lang::function; using pfi::system::time::clock_time; using pfi::system::time::get_clock_time; namespace jubatus { namespace framework { jubatus_serv::jubatus_serv(const server_argv& a, const std::string& base_path): a_(a), update_count_(0), #ifdef HAVE_ZOOKEEPER_H mixer_(new mixer(a_.name, a_.interval_count, a_.interval_sec, pfi::lang::bind(&jubatus_serv::do_mix, this, pfi::lang::_1))), use_cht_(false), #endif base_path_(a_.tmpdir) { }; int jubatus_serv::start(pfi::network::mprpc::rpc_server& serv){ #ifdef HAVE_ZOOKEEPER_H if(! a_.is_standalone()){ zk_ = pfi::lang::shared_ptr<jubatus::common::lock_service> (common::create_lock_service("zk", a_.z, a_.timeout, "logfile_jubatus_serv")); ls = zk_; jubatus::common::prepare_jubatus(*zk_); if( a_.join ){ // join to the existing cluster with -j option join_to_cluster(zk_); } if( use_cht_ ){ jubatus::common::cht::setup_cht_dir(*zk_, a_.name); jubatus::common::cht ht(zk_, a_.name); ht.register_node(a_.eth, a_.port); } mixer_->set_zk(zk_); register_actor(*zk_, a_.name, a_.eth, a_.port); mixer_->start(); } #endif { LOG(INFO) << "running in port=" << a_.port; } return serv.serv(a_.port, a_.threadnum); } void jubatus_serv::register_mixable(mixable0* m){ #ifdef HAVE_ZOOKEEPER_H m->get_diff(); // #22 ensure m is good pointer at process startup mixables_.push_back(m); #endif }; void jubatus_serv::use_cht(){ #ifdef HAVE_ZOOKEEPER_H use_cht_ = true; #endif }; std::map<std::string, std::map<std::string,std::string> > jubatus_serv::get_status(int) const { std::map<std::string, std::string> data; util::get_machine_status(data); data["timeout"] = pfi::lang::lexical_cast<std::string>(a_.timeout); data["threadnum"] = pfi::lang::lexical_cast<std::string>(a_.threadnum); data["tmpdir"] = a_.tmpdir; data["interval_sec"] = pfi::lang::lexical_cast<std::string>(a_.interval_sec); data["interval_count"] = pfi::lang::lexical_cast<std::string>(a_.interval_count); data["is_standalone"] = pfi::lang::lexical_cast<std::string>(a_.is_standalone()); data["VERSION"] = JUBATUS_VERSION; data["PROGNAME"] = JUBATUS_APPNAME; data["update_count"] = pfi::lang::lexical_cast<std::string>(update_count_); #ifdef HAVE_ZOOKEEPER_H mixer_->get_status(data); data["zk"] = a_.z; data["use_cht"] = pfi::lang::lexical_cast<std::string>(use_cht_); #endif std::map<std::string, std::map<std::string,std::string> > ret; ret[get_server_identifier()] = data; return ret; }; std::string jubatus_serv::get_server_identifier()const{ std::stringstream ss; ss << a_.eth; ss << "_"; ss << a_.port; return ss.str(); }; //here #ifdef HAVE_ZOOKEEPER_H void jubatus_serv::join_to_cluster(pfi::lang::shared_ptr<jubatus::common::lock_service> z){ std::vector<std::string> list; std::string path = common::ACTOR_BASE_PATH + "/" + a_.name + "/nodes"; z->list(path, list); if(not list.empty()){ common::lock_service_mutex zlk(*z, common::ACTOR_BASE_PATH + "/" + a_.name + "/master_lock"); while(not zlk.try_lock()){ ; } size_t i = rand() % list.size(); std::string ip; int port; common::revert(list[i], ip, port); pfi::network::mprpc::rpc_client c(ip, port, a_.timeout); pfi::lang::function<std::string()> f = c.call<std::string()>("get_storage"); std::stringstream ss( f() ); for(size_t i = 0;i<mixables_.size(); ++i){ mixables_[i]->clear(); mixables_[i]->load(ss); } } }; std::string jubatus_serv::get_storage(int i){ std::stringstream ss; for(size_t i=0; i<mixables_.size(); ++i){ mixables_[i]->save(ss); } return ss.str(); } std::vector<std::string> jubatus_serv::get_diff_impl(int){ // if(mixables_.empty()){ // //throw config_not_set(); nothing to mix // } std::vector<std::string> o; { scoped_lock lk(rlock(m_)); for(size_t i=0; i<mixables_.size(); ++i){ o.push_back(mixables_[i]->get_diff()); } } return o; }; int jubatus_serv::put_diff_impl(std::vector<std::string> unpacked){ scoped_lock lk(wlock(m_)); if(unpacked.size() != mixables_.size()){ //deserialization error } for(size_t i=0; i<mixables_.size(); ++i){ mixables_[i]->put_diff(unpacked[i]); } return 0; }; void jubatus_serv::do_mix(const std::vector<std::pair<std::string,int> >& v){ vector<string> accs; vector<string> serialized_diffs; clock_time start = get_clock_time(); for(size_t s = 0; s < v.size(); ++s ){ try{ rpc_client c(v[s].first, v[s].second, a_.timeout); function<vector<string>(int)> get_diff_fun = c.call<vector<string>(int)>("get_diff"); serialized_diffs = get_diff_fun(0); }catch(std::exception& e){ LOG(ERROR) << e.what(); continue; } scoped_lock lk(rlock(m_)); // model_ should not be in mix (reduce)? if(accs.empty()){ accs = serialized_diffs; }else{ for(size_t i=0; i<mixables_.size(); ++i){ // FIXME: very inefficient but what sucks is type system of C++ mixables_[i]->reduce(serialized_diffs[i], accs[i]); } } } for(size_t s = 0; s < v.size(); ++s ){ try{ rpc_client c(v[s].first, v[s].second, a_.timeout); function<int(vector<string>)> put_diff_fun = c.call<int(vector<string>)>("put_diff"); put_diff_fun(accs); }catch(std::exception& e){ LOG(ERROR) << e.what(); continue; } } clock_time end = get_clock_time(); DLOG(INFO) << "mixed with " << v.size() << " servers in " << (double)(end - start) << " secs."; size_t s = 0; for(size_t i=0; i<accs.size(); ++i){ s+=accs[i].size(); } DLOG(INFO) << s << " bytes (serialized data) has been put."; } #endif int jubatus_serv::save(std::string id) { std::string ofile; build_local_path_(ofile, "jubatus", id); std::ofstream ofs(ofile.c_str(), std::ios::trunc|std::ios::binary); if(!ofs){ throw std::runtime_error(ofile + ": cannot open (" + pfi::lang::lexical_cast<std::string>(errno) + ")" ); } try{ for(size_t i=0; i<mixables_.size(); ++i){ mixables_[i]->save(ofs); } ofs.close(); LOG(INFO) << "saved to " << ofile; return 0; }catch(const std::exception& e){ return -1; } } int jubatus_serv::load(std::string id) { std::string ifile; build_local_path_(ifile, "jubatus", id); std::ifstream ifs(ifile.c_str(), std::ios::binary); if(!ifs)throw std::runtime_error(ifile + ": cannot open (" + pfi::lang::lexical_cast<std::string>(errno) + ")" ); try{ for(size_t i = 0;i<mixables_.size(); ++i){ mixables_[i]->clear(); mixables_[i]->load(ifs); } ifs.close(); this->after_load(); return 0; }catch(const std::exception& e){ ifs.close(); } return -1; //expected never reaching here. } }} <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: appchild.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2007-06-27 22:55:19 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #ifndef GCC #endif #ifndef _SFX_WHITER_HXX //autogen #include <svtools/whiter.hxx> #endif #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #include <sfx2/app.hxx> #include "appdata.hxx" #include "workwin.hxx" #include <sfx2/childwin.hxx> #include "arrdecl.hxx" #include <sfx2/templdlg.hxx> #include <sfx2/request.hxx> #include <sfx2/bindings.hxx> #include <sfx2/dispatch.hxx> #include "sfxtypes.hxx" #include <sfx2/module.hxx> #include <sfx2/sfxsids.hrc> //========================================================================= void SfxApplication::RegisterChildWindow_Impl( SfxModule *pMod, SfxChildWinFactory *pFact ) { if ( pMod ) { pMod->RegisterChildWindow( pFact ); return; } if (!pAppData_Impl->pFactArr) pAppData_Impl->pFactArr = new SfxChildWinFactArr_Impl; //#ifdef DBG_UTIL for (USHORT nFactory=0; nFactory<pAppData_Impl->pFactArr->Count(); ++nFactory) { if (pFact->nId == (*pAppData_Impl->pFactArr)[nFactory]->nId) { pAppData_Impl->pFactArr->Remove( nFactory ); // DBG_ERROR("ChildWindow mehrfach registriert!"); // return; } } //#endif pAppData_Impl->pFactArr->C40_INSERT( SfxChildWinFactory, pFact, pAppData_Impl->pFactArr->Count() ); } void SfxApplication::RegisterChildWindowContext_Impl( SfxModule *pMod, USHORT nId, SfxChildWinContextFactory *pFact) { SfxChildWinFactArr_Impl *pFactories; SfxChildWinFactory *pF = NULL; if ( pMod ) { // Modul "ubergeben, ChildwindowFactory dort suchen pFactories = pMod->GetChildWinFactories_Impl(); if ( pFactories ) { USHORT nCount = pFactories->Count(); for (USHORT nFactory=0; nFactory<nCount; ++nFactory) { SfxChildWinFactory *pFac = (*pFactories)[nFactory]; if ( nId == pFac->nId ) { // Factory gefunden, Context dort registrieren pF = pFac; break; } } } } if ( !pF ) { // Factory an der Application suchen DBG_ASSERT( pAppData_Impl, "Keine AppDaten!" ); DBG_ASSERT( pAppData_Impl->pFactArr, "Keine Factories!" ); pFactories = pAppData_Impl->pFactArr; USHORT nCount = pFactories->Count(); for (USHORT nFactory=0; nFactory<nCount; ++nFactory) { SfxChildWinFactory *pFac = (*pFactories)[nFactory]; if ( nId == pFac->nId ) { if ( pMod ) { // Wenn der Context von einem Modul registriert wurde, // mu\s die ChildwindowFactory auch dort zur Verf"ugung // stehen, sonst m"u\ste sich die Contextfactory im DLL-Exit // wieder abmelden ! pF = new SfxChildWinFactory( pFac->pCtor, pFac->nId, pFac->nPos ); pMod->RegisterChildWindow( pF ); } else pF = pFac; break; } } } if ( pF ) { if ( !pF->pArr ) pF->pArr = new SfxChildWinContextArr_Impl; pF->pArr->C40_INSERT( SfxChildWinContextFactory, pFact, pF->pArr->Count() ); return; } DBG_ERROR( "Kein ChildWindow fuer diesen Context!" ); } //-------------------------------------------------------------------- SfxChildWinFactArr_Impl& SfxApplication::GetChildWinFactories_Impl() const { return ( *(pAppData_Impl->pFactArr)); } //-------------------------------------------------------------------- SfxTemplateDialog* SfxApplication::GetTemplateDialog() { if ( pAppData_Impl->pViewFrame ) { SfxChildWindow *pChild = pAppData_Impl->pViewFrame->GetChildWindow(SfxTemplateDialogWrapper::GetChildWindowId()); return pChild ? (SfxTemplateDialog*) pChild->GetWindow() : 0; } return NULL; } //-------------------------------------------------------------------- SfxWorkWindow* SfxApplication::GetWorkWindow_Impl(const SfxViewFrame *pFrame) const { if ( pFrame ) return pFrame->GetFrame()->GetWorkWindow_Impl(); else if ( pAppData_Impl->pViewFrame ) return pAppData_Impl->pViewFrame->GetFrame()->GetWorkWindow_Impl(); else return NULL; } <commit_msg>INTEGRATION: CWS changefileheader (1.9.216); FILE MERGED 2008/04/01 15:38:39 thb 1.9.216.2: #i85898# Stripping all external header guards 2008/03/31 13:38:00 rt 1.9.216.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: appchild.cxx,v $ * $Revision: 1.10 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #ifndef GCC #endif #include <svtools/whiter.hxx> #include <svtools/eitem.hxx> #include <sfx2/app.hxx> #include "appdata.hxx" #include "workwin.hxx" #include <sfx2/childwin.hxx> #include "arrdecl.hxx" #include <sfx2/templdlg.hxx> #include <sfx2/request.hxx> #include <sfx2/bindings.hxx> #include <sfx2/dispatch.hxx> #include "sfxtypes.hxx" #include <sfx2/module.hxx> #include <sfx2/sfxsids.hrc> //========================================================================= void SfxApplication::RegisterChildWindow_Impl( SfxModule *pMod, SfxChildWinFactory *pFact ) { if ( pMod ) { pMod->RegisterChildWindow( pFact ); return; } if (!pAppData_Impl->pFactArr) pAppData_Impl->pFactArr = new SfxChildWinFactArr_Impl; //#ifdef DBG_UTIL for (USHORT nFactory=0; nFactory<pAppData_Impl->pFactArr->Count(); ++nFactory) { if (pFact->nId == (*pAppData_Impl->pFactArr)[nFactory]->nId) { pAppData_Impl->pFactArr->Remove( nFactory ); // DBG_ERROR("ChildWindow mehrfach registriert!"); // return; } } //#endif pAppData_Impl->pFactArr->C40_INSERT( SfxChildWinFactory, pFact, pAppData_Impl->pFactArr->Count() ); } void SfxApplication::RegisterChildWindowContext_Impl( SfxModule *pMod, USHORT nId, SfxChildWinContextFactory *pFact) { SfxChildWinFactArr_Impl *pFactories; SfxChildWinFactory *pF = NULL; if ( pMod ) { // Modul "ubergeben, ChildwindowFactory dort suchen pFactories = pMod->GetChildWinFactories_Impl(); if ( pFactories ) { USHORT nCount = pFactories->Count(); for (USHORT nFactory=0; nFactory<nCount; ++nFactory) { SfxChildWinFactory *pFac = (*pFactories)[nFactory]; if ( nId == pFac->nId ) { // Factory gefunden, Context dort registrieren pF = pFac; break; } } } } if ( !pF ) { // Factory an der Application suchen DBG_ASSERT( pAppData_Impl, "Keine AppDaten!" ); DBG_ASSERT( pAppData_Impl->pFactArr, "Keine Factories!" ); pFactories = pAppData_Impl->pFactArr; USHORT nCount = pFactories->Count(); for (USHORT nFactory=0; nFactory<nCount; ++nFactory) { SfxChildWinFactory *pFac = (*pFactories)[nFactory]; if ( nId == pFac->nId ) { if ( pMod ) { // Wenn der Context von einem Modul registriert wurde, // mu\s die ChildwindowFactory auch dort zur Verf"ugung // stehen, sonst m"u\ste sich die Contextfactory im DLL-Exit // wieder abmelden ! pF = new SfxChildWinFactory( pFac->pCtor, pFac->nId, pFac->nPos ); pMod->RegisterChildWindow( pF ); } else pF = pFac; break; } } } if ( pF ) { if ( !pF->pArr ) pF->pArr = new SfxChildWinContextArr_Impl; pF->pArr->C40_INSERT( SfxChildWinContextFactory, pFact, pF->pArr->Count() ); return; } DBG_ERROR( "Kein ChildWindow fuer diesen Context!" ); } //-------------------------------------------------------------------- SfxChildWinFactArr_Impl& SfxApplication::GetChildWinFactories_Impl() const { return ( *(pAppData_Impl->pFactArr)); } //-------------------------------------------------------------------- SfxTemplateDialog* SfxApplication::GetTemplateDialog() { if ( pAppData_Impl->pViewFrame ) { SfxChildWindow *pChild = pAppData_Impl->pViewFrame->GetChildWindow(SfxTemplateDialogWrapper::GetChildWindowId()); return pChild ? (SfxTemplateDialog*) pChild->GetWindow() : 0; } return NULL; } //-------------------------------------------------------------------- SfxWorkWindow* SfxApplication::GetWorkWindow_Impl(const SfxViewFrame *pFrame) const { if ( pFrame ) return pFrame->GetFrame()->GetWorkWindow_Impl(); else if ( pAppData_Impl->pViewFrame ) return pAppData_Impl->pViewFrame->GetFrame()->GetWorkWindow_Impl(); else return NULL; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: imagemgr.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: pb $ $Date: 2001-05-14 10:10:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // includes -------------------------------------------------------------- #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #include <tools/urlobj.hxx> #include <svtools/imagemgr.hxx> #include <comphelper/processfactory.hxx> #include "imgmgr.hxx" #include "app.hxx" #include "unoctitm.hxx" #include "dispatch.hxx" #include "msg.hxx" #include "msgpool.hxx" #include "viewfrm.hxx" #include "module.hxx" #include "objsh.hxx" using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; Image SAL_CALL GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig ) { INetURLObject aObj( aURL ); INetProtocol nProtocol = aObj.GetProtocol(); switch ( nProtocol ) { case INET_PROT_UNO : case INET_PROT_SLOT : { URL aTargetURL; SfxViewFrame* pViewFrame = NULL; Reference < XController > xController; if ( rFrame.is() ) xController = rFrame->getController(); Reference < XDispatchProvider > xProvider( xController, UNO_QUERY ); if ( xProvider.is() ) { aTargetURL.Complete = aURL; Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY ); xTrans->parseStrict( aTargetURL ); Reference < XDispatch > xDisp = xProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); if ( xDisp.is() ) { Reference< XUnoTunnel > xTunnel( xDisp, UNO_QUERY ); SfxOfficeDispatch* pDisp = NULL; if ( xTunnel.is() ) { sal_Int64 nImplementation = xTunnel->getSomething(SfxOfficeDispatch::impl_getStaticIdentifier()); pDisp = (SfxOfficeDispatch*)(nImplementation); } if ( pDisp ) pViewFrame = pDisp->GetDispatcher_Impl()->GetFrame(); } } USHORT nId; if ( nProtocol == INET_PROT_UNO ) { SfxSlotPool& rPool = SFX_APP()->GetSlotPool( pViewFrame ); const SfxSlot* pSlot = rPool.GetUnoSlot( aTargetURL.Path ); if ( pSlot ) nId = pSlot->GetSlotId(); } else nId = ( USHORT ) aTargetURL.Path.toInt32(); SfxModule* pModule = pViewFrame ? pViewFrame->GetObjectShell()->GetModule() : NULL; if ( nId ) return SFX_IMAGEMANAGER()->SeekImage( nId, pModule ); break; } case INET_PROT_NOT_VALID : { return Image(); break; } } return SvFileInformationManager::GetImage( aObj, bBig ); } <commit_msg>#87722#: no global access for ImageManager<commit_after>/************************************************************************* * * $RCSfile: imagemgr.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: mba $ $Date: 2001-06-11 09:53:01 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // includes -------------------------------------------------------------- #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #include <tools/urlobj.hxx> #include <svtools/imagemgr.hxx> #include <comphelper/processfactory.hxx> #include "imgmgr.hxx" #include "app.hxx" #include "unoctitm.hxx" #include "dispatch.hxx" #include "msg.hxx" #include "msgpool.hxx" #include "viewfrm.hxx" #include "module.hxx" #include "objsh.hxx" using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; Image SAL_CALL GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig ) { INetURLObject aObj( aURL ); INetProtocol nProtocol = aObj.GetProtocol(); switch ( nProtocol ) { case INET_PROT_UNO : case INET_PROT_SLOT : { URL aTargetURL; SfxViewFrame* pViewFrame = NULL; Reference < XController > xController; if ( rFrame.is() ) xController = rFrame->getController(); Reference < XDispatchProvider > xProvider( xController, UNO_QUERY ); if ( xProvider.is() ) { aTargetURL.Complete = aURL; Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY ); xTrans->parseStrict( aTargetURL ); Reference < XDispatch > xDisp = xProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); if ( xDisp.is() ) { Reference< XUnoTunnel > xTunnel( xDisp, UNO_QUERY ); SfxOfficeDispatch* pDisp = NULL; if ( xTunnel.is() ) { sal_Int64 nImplementation = xTunnel->getSomething(SfxOfficeDispatch::impl_getStaticIdentifier()); pDisp = (SfxOfficeDispatch*)(nImplementation); } if ( pDisp ) pViewFrame = pDisp->GetDispatcher_Impl()->GetFrame(); } } USHORT nId; if ( nProtocol == INET_PROT_UNO ) { SfxSlotPool& rPool = SFX_APP()->GetSlotPool( pViewFrame ); const SfxSlot* pSlot = rPool.GetUnoSlot( aTargetURL.Path ); if ( pSlot ) nId = pSlot->GetSlotId(); } else nId = ( USHORT ) aTargetURL.Path.toInt32(); SfxModule* pModule = pViewFrame ? pViewFrame->GetObjectShell()->GetModule() : NULL; if ( nId ) { if ( pViewFrame ) return pViewFrame->GetImageManager()->GetImage( nId, pModule, bBig ); else { return SFX_APP()->GetImageManager_Impl()->GetImage( nId, NULL, bBig ); } } break; } case INET_PROT_NOT_VALID : { return Image(); break; } } return SvFileInformationManager::GetImage( aObj, bBig ); } <|endoftext|>
<commit_before>/* * Part of HTTPP. * * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the * project root). * * Copyright (c) 2013 Thomas Sanchez. All rights reserved. * */ #include "httpp/utils/ThreadPool.hpp" #include <atomic> #include <boost/log/trivial.hpp> namespace HTTPP { namespace UTILS { static void empty_deleter(boost::asio::io_service*) {} ThreadPool::ThreadPool(size_t nb_thread, const std::string& name) : service_(std::make_shared<boost::asio::io_service>(nb_thread)) , nb_thread_(nb_thread) , name_(name) { } ThreadPool::ThreadPool(size_t nb_thread, boost::asio::io_service& service, const std::string& name) : service_(std::addressof(service), &empty_deleter) , nb_thread_(nb_thread) , name_(name) { } ThreadPool::~ThreadPool() { if (running_) { stop(); } } ThreadPool::ThreadPool(ThreadPool&& pool) : service_(pool.service_) , running_(pool.running_) , nb_thread_(pool.nb_thread_) , work_(std::move(pool.work_)) , threads_(std::move(pool.threads_)) , name_(std::move(name_)) { running_threads_.store(pool.running_threads_.load()); pool.running_ = false; } void ThreadPool::start(ThreadInit fct) { if (running_) { return; } work_.reset(new boost::asio::io_service::work(*service_)); for (size_t i = 0; i < nb_thread_; ++i) { threads_.emplace_back(std::bind(&ThreadPool::run, this, [this, fct, i] { if (name_.empty()) { setCurrentThreadName("Pool thread #" + std::to_string(i)); } else { setCurrentThreadName(name_ + " #" + std::to_string(i)); } if (fct) { BOOST_LOG_TRIVIAL(debug) << "call init fct " << name_; fct(); } } )); } while (running_threads_ != nb_thread_) { std::this_thread::yield(); } running_ = true; } void ThreadPool::run(ThreadInit fct) { BOOST_LOG_TRIVIAL(debug) << "start thread"; if (fct) { fct(); } BOOST_LOG_TRIVIAL(debug) << "call run()"; ++running_threads_; this->service_->reset(); this->service_->run(); BOOST_LOG_TRIVIAL(debug) << "is stopping"; --running_threads_; } void ThreadPool::stop() { if (!running_) { return; } running_ = false; work_.reset(); service_->stop(); for (auto& th : threads_) { if (th.joinable()) { th.join(); } } threads_.clear(); } bool ThreadPool::runningInPool() const noexcept { auto current_id = std::this_thread::get_id(); for (const auto& thread : threads_) { if (thread.get_id() == current_id) { return true; } } return false; } } // namespace UTILS } // namespace HTTPP <commit_msg>Fix bug in ThreadPool's move constructor.<commit_after>/* * Part of HTTPP. * * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the * project root). * * Copyright (c) 2013 Thomas Sanchez. All rights reserved. * */ #include "httpp/utils/ThreadPool.hpp" #include <atomic> #include <boost/log/trivial.hpp> namespace HTTPP { namespace UTILS { static void empty_deleter(boost::asio::io_service*) {} ThreadPool::ThreadPool(size_t nb_thread, const std::string& name) : service_(std::make_shared<boost::asio::io_service>(nb_thread)) , nb_thread_(nb_thread) , name_(name) { } ThreadPool::ThreadPool(size_t nb_thread, boost::asio::io_service& service, const std::string& name) : service_(std::addressof(service), &empty_deleter) , nb_thread_(nb_thread) , name_(name) { } ThreadPool::~ThreadPool() { if (running_) { stop(); } } ThreadPool::ThreadPool(ThreadPool&& pool) : service_(pool.service_) , running_(pool.running_) , nb_thread_(pool.nb_thread_) , work_(std::move(pool.work_)) , threads_(std::move(pool.threads_)) , name_(std::move(pool.name_)) { running_threads_.store(pool.running_threads_.load()); pool.running_ = false; } void ThreadPool::start(ThreadInit fct) { if (running_) { return; } work_.reset(new boost::asio::io_service::work(*service_)); for (size_t i = 0; i < nb_thread_; ++i) { threads_.emplace_back(std::bind(&ThreadPool::run, this, [this, fct, i] { if (name_.empty()) { setCurrentThreadName("Pool thread #" + std::to_string(i)); } else { setCurrentThreadName(name_ + " #" + std::to_string(i)); } if (fct) { BOOST_LOG_TRIVIAL(debug) << "call init fct " << name_; fct(); } } )); } while (running_threads_ != nb_thread_) { std::this_thread::yield(); } running_ = true; } void ThreadPool::run(ThreadInit fct) { BOOST_LOG_TRIVIAL(debug) << "start thread"; if (fct) { fct(); } BOOST_LOG_TRIVIAL(debug) << "call run()"; ++running_threads_; this->service_->reset(); this->service_->run(); BOOST_LOG_TRIVIAL(debug) << "is stopping"; --running_threads_; } void ThreadPool::stop() { if (!running_) { return; } running_ = false; work_.reset(); service_->stop(); for (auto& th : threads_) { if (th.joinable()) { th.join(); } } threads_.clear(); } bool ThreadPool::runningInPool() const noexcept { auto current_id = std::this_thread::get_id(); for (const auto& thread : threads_) { if (thread.get_id() == current_id) { return true; } } return false; } } // namespace UTILS } // namespace HTTPP <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2003 by Unai Garro * * ugarro@users.sourceforge.net * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "ingredientpropertylist.h" #include <iostream> IngredientPropertyList::IngredientPropertyList() { } IngredientPropertyList::~IngredientPropertyList() { } void IngredientPropertyList::add(IngredientProperty &property) { list.append (new IngredientProperty(property)); } IngredientProperty* IngredientPropertyList::getFirst(void){ return(list.first()); } IngredientProperty* IngredientPropertyList::getNext(void){ return(list.next()); } IngredientProperty* IngredientPropertyList::getElement(int index){ return(list.at(index)); } void IngredientPropertyList::clear(void) { list.clear(); } bool IngredientPropertyList::isEmpty(void) { return(list.isEmpty()); } int IngredientPropertyList::find(IngredientProperty* it) { return(list.find(it)); } int IngredientPropertyList::find(int id) { IngredientProperty ip; ip.id=id; return(list.find(&ip)); } IngredientProperty* IngredientPropertyList::at(int pos) { return(list.at(pos)); } void IngredientPropertyList::append(IngredientProperty *property) { list.append (property); } void IngredientPropertyList::divide(int persons) { for (IngredientProperty* ip=getFirst();ip;ip=getNext()) ip->amount/=persons; } void IngredientPropertyList::filter(int ingredientID,IngredientPropertyList *filteredList) { filteredList->clear(); for (IngredientProperty* ip=getFirst();ip;ip=getNext()) if (ip->ingredientID==ingredientID) filteredList->add(*ip); } int IngredientPropertyList::count(void) { return (list.count()); } void IngredientPropertyList::remove(IngredientProperty* ip) { list->remove(ip); }<commit_msg>oops, small mistake<commit_after>/*************************************************************************** * Copyright (C) 2003 by Unai Garro * * ugarro@users.sourceforge.net * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "ingredientpropertylist.h" #include <iostream> IngredientPropertyList::IngredientPropertyList() { } IngredientPropertyList::~IngredientPropertyList() { } void IngredientPropertyList::add(IngredientProperty &property) { list.append (new IngredientProperty(property)); } IngredientProperty* IngredientPropertyList::getFirst(void){ return(list.first()); } IngredientProperty* IngredientPropertyList::getNext(void){ return(list.next()); } IngredientProperty* IngredientPropertyList::getElement(int index){ return(list.at(index)); } void IngredientPropertyList::clear(void) { list.clear(); } bool IngredientPropertyList::isEmpty(void) { return(list.isEmpty()); } int IngredientPropertyList::find(IngredientProperty* it) { return(list.find(it)); } int IngredientPropertyList::find(int id) { IngredientProperty ip; ip.id=id; return(list.find(&ip)); } IngredientProperty* IngredientPropertyList::at(int pos) { return(list.at(pos)); } void IngredientPropertyList::append(IngredientProperty *property) { list.append (property); } void IngredientPropertyList::divide(int persons) { for (IngredientProperty* ip=getFirst();ip;ip=getNext()) ip->amount/=persons; } void IngredientPropertyList::filter(int ingredientID,IngredientPropertyList *filteredList) { filteredList->clear(); for (IngredientProperty* ip=getFirst();ip;ip=getNext()) if (ip->ingredientID==ingredientID) filteredList->add(*ip); } int IngredientPropertyList::count(void) { return (list.count()); } void IngredientPropertyList::remove(IngredientProperty* ip) { list.remove(ip); }<|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <libtorrent/kademlia/closest_nodes.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include "libtorrent/assert.hpp" namespace libtorrent { namespace dht { using asio::ip::udp; closest_nodes_observer::~closest_nodes_observer() { if (m_algorithm) m_algorithm->failed(m_self, true); } void closest_nodes_observer::reply(msg const& in) { if (!m_algorithm) { TORRENT_ASSERT(false); return; } if (!in.nodes.empty()) { for (msg::nodes_t::const_iterator i = in.nodes.begin() , end(in.nodes.end()); i != end; ++i) { m_algorithm->traverse(i->id, i->addr); } } m_algorithm->finished(m_self); m_algorithm = 0; } void closest_nodes_observer::timeout() { if (!m_algorithm) return; m_algorithm->failed(m_self); m_algorithm = 0; } closest_nodes::closest_nodes( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) : traversal_algorithm( target , branch_factor , max_results , table , rpc , table.begin() , table.end() ) , m_done_callback(callback) { boost::intrusive_ptr<closest_nodes> self(this); add_requests(); } void closest_nodes::invoke(node_id const& id, udp::endpoint addr) { TORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer)); observer_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target)); #ifndef NDEBUG o->m_in_constructor = false; #endif m_rpc.invoke(messages::find_node, addr, o); } void closest_nodes::done() { std::vector<node_entry> results; int num_results = m_table.bucket_size(); for (std::vector<result>::iterator i = m_max_results , end(m_results.end()); i != end && num_results >= 0; ++i) { if (i->flags & result::no_id) continue; if ((i->flags & result::queried) == 0) continue; results.push_back(node_entry(i->id, i->addr)); --num_results; } m_done_callback(results); } void closest_nodes::initiate( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) { new closest_nodes(target, branch_factor, max_results, table, rpc, callback); } } } // namespace libtorrent::dht <commit_msg>fixed typo in previous dht checkin<commit_after>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <libtorrent/kademlia/closest_nodes.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include "libtorrent/assert.hpp" namespace libtorrent { namespace dht { using asio::ip::udp; closest_nodes_observer::~closest_nodes_observer() { if (m_algorithm) m_algorithm->failed(m_self, true); } void closest_nodes_observer::reply(msg const& in) { if (!m_algorithm) { TORRENT_ASSERT(false); return; } if (!in.nodes.empty()) { for (msg::nodes_t::const_iterator i = in.nodes.begin() , end(in.nodes.end()); i != end; ++i) { m_algorithm->traverse(i->id, i->addr); } } m_algorithm->finished(m_self); m_algorithm = 0; } void closest_nodes_observer::timeout() { if (!m_algorithm) return; m_algorithm->failed(m_self); m_algorithm = 0; } closest_nodes::closest_nodes( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) : traversal_algorithm( target , branch_factor , max_results , table , rpc , table.begin() , table.end() ) , m_done_callback(callback) { boost::intrusive_ptr<closest_nodes> self(this); add_requests(); } void closest_nodes::invoke(node_id const& id, udp::endpoint addr) { TORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer)); observer_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target)); #ifndef NDEBUG o->m_in_constructor = false; #endif m_rpc.invoke(messages::find_node, addr, o); } void closest_nodes::done() { std::vector<node_entry> results; int num_results = m_max_results; for (std::vector<result>::iterator i = m_results.begin() , end(m_results.end()); i != end && num_results >= 0; ++i) { if (i->flags & result::no_id) continue; if ((i->flags & result::queried) == 0) continue; results.push_back(node_entry(i->id, i->addr)); --num_results; } m_done_callback(results); } void closest_nodes::initiate( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) { new closest_nodes(target, branch_factor, max_results, table, rpc, callback); } } } // namespace libtorrent::dht <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <libtorrent/kademlia/closest_nodes.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include "libtorrent/assert.hpp" namespace libtorrent { namespace dht { using asio::ip::udp; closest_nodes_observer::~closest_nodes_observer() { if (m_algorithm) m_algorithm->failed(m_self, true); } void closest_nodes_observer::reply(msg const& in) { if (!m_algorithm) { TORRENT_ASSERT(false); return; } if (!in.nodes.empty()) { for (msg::nodes_t::const_iterator i = in.nodes.begin() , end(in.nodes.end()); i != end; ++i) { m_algorithm->traverse(i->id, i->addr); } } m_algorithm->finished(m_self); m_algorithm = 0; } void closest_nodes_observer::timeout() { if (!m_algorithm) return; m_algorithm->failed(m_self); m_algorithm = 0; } closest_nodes::closest_nodes( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) : traversal_algorithm( target , branch_factor , max_results , table , rpc , table.begin() , table.end() ) , m_done_callback(callback) { boost::intrusive_ptr<closest_nodes> self(this); add_requests(); } void closest_nodes::invoke(node_id const& id, udp::endpoint addr) { TORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer)); observer_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target)); #ifndef NDEBUG o->m_in_constructor = false; #endif m_rpc.invoke(messages::find_node, addr, o); } void closest_nodes::done() { std::vector<node_entry> results; int num_results = m_table.bucket_size(); for (std::vector<result>::iterator i = m_results.begin() , end(m_results.end()); i != end && num_results >= 0; ++i) { if (i->flags & result::no_id) continue; results.push_back(node_entry(i->id, i->addr)); --num_results; } m_done_callback(results); } void closest_nodes::initiate( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) { new closest_nodes(target, branch_factor, max_results, table, rpc, callback); } } } // namespace libtorrent::dht <commit_msg>dht fix<commit_after>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <libtorrent/kademlia/closest_nodes.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include "libtorrent/assert.hpp" namespace libtorrent { namespace dht { using asio::ip::udp; closest_nodes_observer::~closest_nodes_observer() { if (m_algorithm) m_algorithm->failed(m_self, true); } void closest_nodes_observer::reply(msg const& in) { if (!m_algorithm) { TORRENT_ASSERT(false); return; } if (!in.nodes.empty()) { for (msg::nodes_t::const_iterator i = in.nodes.begin() , end(in.nodes.end()); i != end; ++i) { m_algorithm->traverse(i->id, i->addr); } } m_algorithm->finished(m_self); m_algorithm = 0; } void closest_nodes_observer::timeout() { if (!m_algorithm) return; m_algorithm->failed(m_self); m_algorithm = 0; } closest_nodes::closest_nodes( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) : traversal_algorithm( target , branch_factor , max_results , table , rpc , table.begin() , table.end() ) , m_done_callback(callback) { boost::intrusive_ptr<closest_nodes> self(this); add_requests(); } void closest_nodes::invoke(node_id const& id, udp::endpoint addr) { TORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer)); observer_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target)); #ifndef NDEBUG o->m_in_constructor = false; #endif m_rpc.invoke(messages::find_node, addr, o); } void closest_nodes::done() { std::vector<node_entry> results; int num_results = m_table.bucket_size(); for (std::vector<result>::iterator i = m_max_results , end(m_results.end()); i != end && num_results >= 0; ++i) { if (i->flags & result::no_id) continue; if ((i->flags & result::queried) == 0) continue; results.push_back(node_entry(i->id, i->addr)); --num_results; } m_done_callback(results); } void closest_nodes::initiate( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) { new closest_nodes(target, branch_factor, max_results, table, rpc, callback); } } } // namespace libtorrent::dht <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Bastian Holst <bastianholst@gmx.de> // // Self #include "AbstractDataPlugin.h" // Marble #include "AbstractDataPluginModel.h" #include "AbstractDataPluginItem.h" #include "GeoPainter.h" #include "GeoSceneLayer.h" #include "MarbleModel.h" #include "ViewportParams.h" #include "MarbleDebug.h" // Qt #include <QtCore/QEvent> #include <QtGui/QMouseEvent> #include <QtGui/QRegion> #include <QtDeclarative/QDeclarativeComponent> #include <QtDeclarative/QDeclarativeItem> #include <QtDeclarative/QDeclarativeContext> namespace Marble { class AbstractDataPluginPrivate { public: AbstractDataPluginPrivate() : m_model( 0 ), m_numberOfItems( 10 ), m_delegate( 0 ), m_delegateParent( 0 ) { } ~AbstractDataPluginPrivate() { delete m_model; } AbstractDataPluginModel *m_model; quint32 m_numberOfItems; QDeclarativeComponent* m_delegate; QGraphicsItem* m_delegateParent; QMap<AbstractDataPluginItem*,QDeclarativeItem*> m_delegateInstances; }; AbstractDataPlugin::AbstractDataPlugin( const MarbleModel *marbleModel ) : RenderPlugin( marbleModel ), d( new AbstractDataPluginPrivate ) { } AbstractDataPlugin::~AbstractDataPlugin() { delete d; } bool AbstractDataPlugin::isInitialized() const { return model() != 0; } QStringList AbstractDataPlugin::backendTypes() const { return QStringList( name() ); } QString AbstractDataPlugin::renderPolicy() const { return QString( "ALWAYS" ); } QStringList AbstractDataPlugin::renderPosition() const { return QStringList( "ALWAYS_ON_TOP" ); } bool AbstractDataPlugin::render( GeoPainter *painter, ViewportParams *viewport, const QString& renderPos, GeoSceneLayer * layer) { Q_UNUSED( renderPos ); Q_UNUSED( layer ); if ( !d->m_model || !isInitialized() ) { return true; } if ( d->m_delegate ) { handleViewportChange( viewport ); } else { QList<AbstractDataPluginItem*> items = d->m_model->items( viewport, marbleModel(), numberOfItems() ); painter->save(); // Paint the most important item at last for( int i = items.size() - 1; i >= 0; --i ) { items.at( i )->paintEvent( painter, viewport ); } painter->restore(); } return true; } AbstractDataPluginModel *AbstractDataPlugin::model() const { return d->m_model; } void AbstractDataPlugin::setModel( AbstractDataPluginModel* model ) { if ( d->m_model ) { disconnect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) ); delete d->m_model; } d->m_model = model; connect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) ); connect( d->m_model, SIGNAL( favoriteItemsChanged( const QStringList& ) ), this, SLOT( favoriteItemsChanged( const QStringList& ) ) ); connect( d->m_model, SIGNAL( favoriteItemsOnlyChanged() ), this, SIGNAL( favoriteItemsOnlyChanged() ) ); emit favoritesModelChanged(); } const PluginManager* AbstractDataPlugin::pluginManager() const { return marbleModel()->pluginManager(); } quint32 AbstractDataPlugin::numberOfItems() const { return d->m_numberOfItems; } void AbstractDataPlugin::setNumberOfItems( quint32 number ) { bool changed = ( number != d->m_numberOfItems ); d->m_numberOfItems = number; if ( changed ) emit changedNumberOfItems( number ); } QList<AbstractDataPluginItem *> AbstractDataPlugin::whichItemAt( const QPoint& curpos ) { if ( d->m_model && enabled() && visible()) { return d->m_model->whichItemAt( curpos ); } else { return QList<AbstractDataPluginItem *>(); } } RenderPlugin::RenderType AbstractDataPlugin::renderType() const { return Online; } void AbstractDataPlugin::setDelegate( QDeclarativeComponent *delegate, QGraphicsItem* parent ) { qDeleteAll( d->m_delegateInstances.values() ); d->m_delegateInstances.clear(); d->m_delegate = delegate; d->m_delegateParent = parent; } void AbstractDataPlugin::setFavoriteItemsOnly( bool favoriteOnly ) { if ( d->m_model && d->m_model->isFavoriteItemsOnly() != favoriteOnly ) { d->m_model->setFavoriteItemsOnly( favoriteOnly ); } } bool AbstractDataPlugin::isFavoriteItemsOnly() const { return d->m_model && d->m_model->isFavoriteItemsOnly(); } QObject *AbstractDataPlugin::favoritesModel() { return d->m_model ? d->m_model->favoritesModel() : 0; } void AbstractDataPlugin::handleViewportChange( ViewportParams* viewport ) { QList<AbstractDataPluginItem*> orphane = d->m_delegateInstances.keys(); QList<AbstractDataPluginItem*> const items = d->m_model->items( viewport, marbleModel(), numberOfItems() ); foreach( AbstractDataPluginItem* item, items ) { qreal x, y; Marble::GeoDataCoordinates const coordinates = item->coordinate(); bool const visible = viewport->screenCoordinates( coordinates.longitude(), coordinates.latitude(), x, y ); if ( !d->m_delegateInstances.contains( item ) ) { if ( !visible ) { // We don't have, but don't need it either. Shouldn't happen though as the model checks for it already. continue; } // Create a new QML object instance using the delegate as the factory. The original // data plugin item is set as the context object, i.e. all its properties are available // to QML directly with their names QDeclarativeContext *context = new QDeclarativeContext( qmlContext( d->m_delegate ) ); context->setContextObject( item ); QObject* component = d->m_delegate->create( context ); QDeclarativeItem* newItem = qobject_cast<QDeclarativeItem*>( component ); QGraphicsItem* graphicsItem = qobject_cast<QGraphicsItem*>( component ); if ( graphicsItem && newItem ) { graphicsItem->setParentItem( d->m_delegateParent ); } if ( newItem ) { d->m_delegateInstances[item] = newItem; } else { mDebug() << "Failed to create delegate"; continue; } } else if ( !visible ) { // Previously visible but not anymore => needs to be deleted. Orphane list takes care of it later. // Shouldn't happen though as the model checks for it already. continue; } Q_ASSERT( visible ); QDeclarativeItem* declarativeItem = d->m_delegateInstances[item]; Q_ASSERT( declarativeItem ); // Make sure we have a valid bounding rect for collision detection item->setProjection( viewport ); item->setSize( QSizeF( declarativeItem->boundingRect().size() ) ); int shiftX( 0 ), shiftY( 0 ); switch( declarativeItem->transformOrigin() ) { case QDeclarativeItem::TopLeft: case QDeclarativeItem::Top: case QDeclarativeItem::TopRight: break; case QDeclarativeItem::Left: case QDeclarativeItem::Center: case QDeclarativeItem::Right: shiftY = declarativeItem->height() / 2; break; case QDeclarativeItem::BottomLeft: case QDeclarativeItem::Bottom: case QDeclarativeItem::BottomRight: shiftY = declarativeItem->height(); break; } switch( declarativeItem->transformOrigin() ) { case QDeclarativeItem::TopLeft: case QDeclarativeItem::Left: case QDeclarativeItem::BottomLeft: break; case QDeclarativeItem::Top: case QDeclarativeItem::Center: case QDeclarativeItem::Bottom: shiftX = declarativeItem->width() / 2; break; case QDeclarativeItem::TopRight: case QDeclarativeItem::Right: case QDeclarativeItem::BottomRight: shiftX = declarativeItem->width(); break; } declarativeItem->setPos( x - shiftX, y - shiftY ); orphane.removeOne( item ); } // Cleanup foreach( AbstractDataPluginItem* item, orphane ) { Q_ASSERT( d->m_delegateInstances.contains( item ) ); delete d->m_delegateInstances[item]; d->m_delegateInstances.remove( item ); } } void AbstractDataPlugin::favoriteItemsChanged( const QStringList& favoriteItems ) { Q_UNUSED( favoriteItems ) } } // namespace Marble #include "AbstractDataPlugin.moc" <commit_msg>Make dynamic object properties available to QML.<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Bastian Holst <bastianholst@gmx.de> // // Self #include "AbstractDataPlugin.h" // Marble #include "AbstractDataPluginModel.h" #include "AbstractDataPluginItem.h" #include "GeoPainter.h" #include "GeoSceneLayer.h" #include "MarbleModel.h" #include "ViewportParams.h" #include "MarbleDebug.h" // Qt #include <QtCore/QEvent> #include <QtGui/QMouseEvent> #include <QtGui/QRegion> #include <QtDeclarative/QDeclarativeComponent> #include <QtDeclarative/QDeclarativeItem> #include <QtDeclarative/QDeclarativeContext> namespace Marble { class AbstractDataPluginPrivate { public: AbstractDataPluginPrivate() : m_model( 0 ), m_numberOfItems( 10 ), m_delegate( 0 ), m_delegateParent( 0 ) { } ~AbstractDataPluginPrivate() { delete m_model; } AbstractDataPluginModel *m_model; quint32 m_numberOfItems; QDeclarativeComponent* m_delegate; QGraphicsItem* m_delegateParent; QMap<AbstractDataPluginItem*,QDeclarativeItem*> m_delegateInstances; }; AbstractDataPlugin::AbstractDataPlugin( const MarbleModel *marbleModel ) : RenderPlugin( marbleModel ), d( new AbstractDataPluginPrivate ) { } AbstractDataPlugin::~AbstractDataPlugin() { delete d; } bool AbstractDataPlugin::isInitialized() const { return model() != 0; } QStringList AbstractDataPlugin::backendTypes() const { return QStringList( name() ); } QString AbstractDataPlugin::renderPolicy() const { return QString( "ALWAYS" ); } QStringList AbstractDataPlugin::renderPosition() const { return QStringList( "ALWAYS_ON_TOP" ); } bool AbstractDataPlugin::render( GeoPainter *painter, ViewportParams *viewport, const QString& renderPos, GeoSceneLayer * layer) { Q_UNUSED( renderPos ); Q_UNUSED( layer ); if ( !d->m_model || !isInitialized() ) { return true; } if ( d->m_delegate ) { handleViewportChange( viewport ); } else { QList<AbstractDataPluginItem*> items = d->m_model->items( viewport, marbleModel(), numberOfItems() ); painter->save(); // Paint the most important item at last for( int i = items.size() - 1; i >= 0; --i ) { items.at( i )->paintEvent( painter, viewport ); } painter->restore(); } return true; } AbstractDataPluginModel *AbstractDataPlugin::model() const { return d->m_model; } void AbstractDataPlugin::setModel( AbstractDataPluginModel* model ) { if ( d->m_model ) { disconnect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) ); delete d->m_model; } d->m_model = model; connect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) ); connect( d->m_model, SIGNAL( favoriteItemsChanged( const QStringList& ) ), this, SLOT( favoriteItemsChanged( const QStringList& ) ) ); connect( d->m_model, SIGNAL( favoriteItemsOnlyChanged() ), this, SIGNAL( favoriteItemsOnlyChanged() ) ); emit favoritesModelChanged(); } const PluginManager* AbstractDataPlugin::pluginManager() const { return marbleModel()->pluginManager(); } quint32 AbstractDataPlugin::numberOfItems() const { return d->m_numberOfItems; } void AbstractDataPlugin::setNumberOfItems( quint32 number ) { bool changed = ( number != d->m_numberOfItems ); d->m_numberOfItems = number; if ( changed ) emit changedNumberOfItems( number ); } QList<AbstractDataPluginItem *> AbstractDataPlugin::whichItemAt( const QPoint& curpos ) { if ( d->m_model && enabled() && visible()) { return d->m_model->whichItemAt( curpos ); } else { return QList<AbstractDataPluginItem *>(); } } RenderPlugin::RenderType AbstractDataPlugin::renderType() const { return Online; } void AbstractDataPlugin::setDelegate( QDeclarativeComponent *delegate, QGraphicsItem* parent ) { qDeleteAll( d->m_delegateInstances.values() ); d->m_delegateInstances.clear(); d->m_delegate = delegate; d->m_delegateParent = parent; } void AbstractDataPlugin::setFavoriteItemsOnly( bool favoriteOnly ) { if ( d->m_model && d->m_model->isFavoriteItemsOnly() != favoriteOnly ) { d->m_model->setFavoriteItemsOnly( favoriteOnly ); } } bool AbstractDataPlugin::isFavoriteItemsOnly() const { return d->m_model && d->m_model->isFavoriteItemsOnly(); } QObject *AbstractDataPlugin::favoritesModel() { return d->m_model ? d->m_model->favoritesModel() : 0; } void AbstractDataPlugin::handleViewportChange( ViewportParams* viewport ) { QList<AbstractDataPluginItem*> orphane = d->m_delegateInstances.keys(); QList<AbstractDataPluginItem*> const items = d->m_model->items( viewport, marbleModel(), numberOfItems() ); foreach( AbstractDataPluginItem* item, items ) { qreal x, y; Marble::GeoDataCoordinates const coordinates = item->coordinate(); bool const visible = viewport->screenCoordinates( coordinates.longitude(), coordinates.latitude(), x, y ); if ( !d->m_delegateInstances.contains( item ) ) { if ( !visible ) { // We don't have, but don't need it either. Shouldn't happen though as the model checks for it already. continue; } // Create a new QML object instance using the delegate as the factory. The original // data plugin item is set as the context object, i.e. all its properties are available // to QML directly with their names QDeclarativeContext *context = new QDeclarativeContext( qmlContext( d->m_delegate ) ); context->setContextObject( item ); QList<QByteArray> const dynamicProperties = item->dynamicPropertyNames(); foreach( const QByteArray &property, dynamicProperties ) { context->setContextProperty( property, item->property( property ) ); } QObject* component = d->m_delegate->create( context ); QDeclarativeItem* newItem = qobject_cast<QDeclarativeItem*>( component ); QGraphicsItem* graphicsItem = qobject_cast<QGraphicsItem*>( component ); if ( graphicsItem && newItem ) { graphicsItem->setParentItem( d->m_delegateParent ); } if ( newItem ) { d->m_delegateInstances[item] = newItem; } else { mDebug() << "Failed to create delegate"; continue; } } else if ( !visible ) { // Previously visible but not anymore => needs to be deleted. Orphane list takes care of it later. // Shouldn't happen though as the model checks for it already. continue; } Q_ASSERT( visible ); QDeclarativeItem* declarativeItem = d->m_delegateInstances[item]; Q_ASSERT( declarativeItem ); // Make sure we have a valid bounding rect for collision detection item->setProjection( viewport ); item->setSize( QSizeF( declarativeItem->boundingRect().size() ) ); int shiftX( 0 ), shiftY( 0 ); switch( declarativeItem->transformOrigin() ) { case QDeclarativeItem::TopLeft: case QDeclarativeItem::Top: case QDeclarativeItem::TopRight: break; case QDeclarativeItem::Left: case QDeclarativeItem::Center: case QDeclarativeItem::Right: shiftY = declarativeItem->height() / 2; break; case QDeclarativeItem::BottomLeft: case QDeclarativeItem::Bottom: case QDeclarativeItem::BottomRight: shiftY = declarativeItem->height(); break; } switch( declarativeItem->transformOrigin() ) { case QDeclarativeItem::TopLeft: case QDeclarativeItem::Left: case QDeclarativeItem::BottomLeft: break; case QDeclarativeItem::Top: case QDeclarativeItem::Center: case QDeclarativeItem::Bottom: shiftX = declarativeItem->width() / 2; break; case QDeclarativeItem::TopRight: case QDeclarativeItem::Right: case QDeclarativeItem::BottomRight: shiftX = declarativeItem->width(); break; } declarativeItem->setPos( x - shiftX, y - shiftY ); orphane.removeOne( item ); } // Cleanup foreach( AbstractDataPluginItem* item, orphane ) { Q_ASSERT( d->m_delegateInstances.contains( item ) ); delete d->m_delegateInstances[item]; d->m_delegateInstances.remove( item ); } } void AbstractDataPlugin::favoriteItemsChanged( const QStringList& favoriteItems ) { Q_UNUSED( favoriteItems ) } } // namespace Marble #include "AbstractDataPlugin.moc" <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "Dumpers.h" #include <Overview.h> #include <Literals.h> #include <Scope.h> #include <LookupContext.h> #include <QDebug> #include <typeinfo> static QString indent(QString s, int level = 2) { QString indentString(level, QLatin1Char(' ')); QString result; int last = 0; for (int i = 0; i < s.length(); ++i) { if (s.at(i) == QLatin1Char('\n') || i == s.length() - 1) { result.append(indentString); result.append(s.midRef(last, i + 1)); last = i + 1; } } return result; } QString CPlusPlus::toString(const Name *name, QString id) { Overview oo; return QString("%0: %1").arg(id, name ? oo(name) : QLatin1String("(null)")); } QString CPlusPlus::toString(FullySpecifiedType ty, QString id) { Overview oo; return QString("%0: %1 (a %2)").arg(id, oo(ty), ty.type() ? typeid(*ty.type()).name() : "(null)"); } QString CPlusPlus::toString(const Symbol *s, QString id) { if (!s) return QString("%0: (null)").arg(id); return QString("%0: %1 (%2) at %3:%4:%5\n%6").arg( id, QString::fromLatin1(typeid(*s).name()), QString::fromUtf8(s->identifier()->chars()), QString::fromLatin1(s->fileName()), QString::number(s->line()), QString::number(s->column()), indent(toString(s->type()))); } QString CPlusPlus::toString(LookupItem it, QString id) { QString result = QString("%1:").arg(id); if (it.declaration()) { result.append(QString("\n%1").arg(indent(toString(it.declaration(), QLatin1String("Decl"))))); } if (it.type().isValid()) { result.append(QString("\n%1").arg(indent(toString(it.type())))); } if (it.scope()) { result.append(QString("\n%1").arg(indent(toString(it.scope(), QLatin1String("Scope"))))); } if (it.binding()) { result.append(QString("\n%1").arg(indent(toString(it.binding(), QLatin1String("Binding"))))); } return result; } QString CPlusPlus::toString(const ClassOrNamespace *binding, QString id) { if (!binding) return QString("%0: (null)").arg(id); QString result = QString("%0: %1 symbols").arg( id, QString::number(binding->symbols().length())); if (binding->templateId()) { result.append(QString("\n%1").arg(indent(toString(binding->templateId(), QLatin1String("Template"))))); } return result; } void CPlusPlus::dump(const Name *name) { qDebug() << qPrintable(toString(name)); } void CPlusPlus::dump(FullySpecifiedType ty) { qDebug() << qPrintable(toString(ty)); } void CPlusPlus::dump(const Symbol *s) { qDebug() << qPrintable(toString(s)); } void CPlusPlus::dump(LookupItem it) { qDebug() << qPrintable(toString(it)); } void CPlusPlus::dump(const ClassOrNamespace *binding) { qDebug() << qPrintable(toString(binding)); } <commit_msg>C++: Fix dumpers when symbol has no identifier.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "Dumpers.h" #include <Overview.h> #include <Literals.h> #include <Scope.h> #include <LookupContext.h> #include <QDebug> #include <typeinfo> static QString indent(QString s, int level = 2) { QString indentString(level, QLatin1Char(' ')); QString result; int last = 0; for (int i = 0; i < s.length(); ++i) { if (s.at(i) == QLatin1Char('\n') || i == s.length() - 1) { result.append(indentString); result.append(s.midRef(last, i + 1)); last = i + 1; } } return result; } QString CPlusPlus::toString(const Name *name, QString id) { Overview oo; return QString("%0: %1").arg(id, name ? oo(name) : QLatin1String("(null)")); } QString CPlusPlus::toString(FullySpecifiedType ty, QString id) { Overview oo; return QString("%0: %1 (a %2)").arg(id, oo(ty), ty.type() ? typeid(*ty.type()).name() : "(null)"); } QString CPlusPlus::toString(const Symbol *s, QString id) { if (!s) return QString("%0: (null)").arg(id); return QString("%0: %1 (%2) at %3:%4:%5\n%6").arg( id, QString::fromLatin1(typeid(*s).name()), s->identifier() ? QString::fromUtf8(s->identifier()->chars()) : "no id", QString::fromLatin1(s->fileName()), QString::number(s->line()), QString::number(s->column()), indent(toString(s->type()))); } QString CPlusPlus::toString(LookupItem it, QString id) { QString result = QString("%1:").arg(id); if (it.declaration()) { result.append(QString("\n%1").arg(indent(toString(it.declaration(), QLatin1String("Decl"))))); } if (it.type().isValid()) { result.append(QString("\n%1").arg(indent(toString(it.type())))); } if (it.scope()) { result.append(QString("\n%1").arg(indent(toString(it.scope(), QLatin1String("Scope"))))); } if (it.binding()) { result.append(QString("\n%1").arg(indent(toString(it.binding(), QLatin1String("Binding"))))); } return result; } QString CPlusPlus::toString(const ClassOrNamespace *binding, QString id) { if (!binding) return QString("%0: (null)").arg(id); QString result = QString("%0: %1 symbols").arg( id, QString::number(binding->symbols().length())); if (binding->templateId()) { result.append(QString("\n%1").arg(indent(toString(binding->templateId(), QLatin1String("Template"))))); } return result; } void CPlusPlus::dump(const Name *name) { qDebug() << qPrintable(toString(name)); } void CPlusPlus::dump(FullySpecifiedType ty) { qDebug() << qPrintable(toString(ty)); } void CPlusPlus::dump(const Symbol *s) { qDebug() << qPrintable(toString(s)); } void CPlusPlus::dump(LookupItem it) { qDebug() << qPrintable(toString(it)); } void CPlusPlus::dump(const ClassOrNamespace *binding) { qDebug() << qPrintable(toString(binding)); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "crumblepath.h" #include "stylehelper.h" #include <QtCore/QList> #include <QtGui/QHBoxLayout> #include <QtGui/QPushButton> #include <QtGui/QMenu> #include <QtGui/QStyle> #include <QtGui/QResizeEvent> #include <QtGui/QPainter> #include <QtGui/QImage> #include <qtcassert.h> namespace Utils { static const int ArrowBorderSize = 12; class CrumblePathButton : public QPushButton { public: enum SegmentType { LastSegment = 1, MiddleSegment = 2, FirstSegment = 4 }; explicit CrumblePathButton(const QString &title, QWidget *parent = 0); void setSegmentType(int type); void select(bool s); void setData(const QVariant &data); QVariant data() const; protected: void paintEvent(QPaintEvent *); void mouseMoveEvent(QMouseEvent *e); void leaveEvent(QEvent *); void mousePressEvent(QMouseEvent *e); void mouseReleaseEvent(QMouseEvent *e); private: void tintImages(); private: bool m_isHovering; bool m_isPressed; bool m_isSelected; bool m_isEnd; QColor m_baseColor; QImage m_segment; QImage m_segmentEnd; QImage m_segmentSelected; QImage m_segmentSelectedEnd; QImage m_segmentHover; QImage m_segmentHoverEnd; QImage m_triangleIcon; QPoint m_textPos; QVariant m_data; }; CrumblePathButton::CrumblePathButton(const QString &title, QWidget *parent) : QPushButton(title, parent), m_isHovering(false), m_isPressed(false), m_isSelected(false), m_isEnd(true) { setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); setToolTip(title); setMinimumHeight(25); setMaximumHeight(25); setMouseTracking(true); m_textPos.setX(18); m_textPos.setY(height()); m_baseColor = StyleHelper::baseColor(); m_segment = QImage(":/utils/images/crumblepath-segment.png"); m_segmentSelected = QImage(":/utils/images/crumblepath-segment-selected.png"); m_segmentHover = QImage(":/utils/images/crumblepath-segment-hover.png"); m_segmentEnd = QImage(":/utils/images/crumblepath-segment-end.png"); m_segmentSelectedEnd = QImage(":/utils/images/crumblepath-segment-selected-end.png"); m_segmentHoverEnd = QImage(":/utils/images/crumblepath-segment-hover-end.png"); m_triangleIcon = QImage(":/utils/images/triangle_vert.png"); tintImages(); } void CrumblePathButton::paintEvent(QPaintEvent *) { QPainter p(this); QRect geom(0, 0, geometry().width(), geometry().height()); if (StyleHelper::baseColor() != m_baseColor) { m_baseColor = StyleHelper::baseColor(); tintImages(); } if (m_isEnd) { if (m_isPressed || m_isSelected) { Utils::StyleHelper::drawCornerImage(m_segmentSelectedEnd, &p, geom, 2, 0, 2, 0); } else if (m_isHovering) { Utils::StyleHelper::drawCornerImage(m_segmentHoverEnd, &p, geom, 2, 0, 2, 0); } else { Utils::StyleHelper::drawCornerImage(m_segmentEnd, &p, geom, 2, 0, 2, 0); } } else { if (m_isPressed || m_isSelected) { Utils::StyleHelper::drawCornerImage(m_segmentSelected, &p, geom, 2, 0, 12, 0); } else if (m_isHovering) { Utils::StyleHelper::drawCornerImage(m_segmentHover, &p, geom, 2, 0, 12, 0); } else { Utils::StyleHelper::drawCornerImage(m_segment, &p, geom, 2, 0, 12, 0); } } p.setPen(StyleHelper::panelTextColor()); QFontMetrics fm(p.font()); QString textToDraw = fm.elidedText(text(), Qt::ElideRight, geom.width() - m_textPos.x()); p.drawText(QRectF(m_textPos.x(), 4, geom.width(), geom.height()), textToDraw); if (menu()) { p.drawImage(geom.width() - m_triangleIcon.width() - 6, geom.center().y() - m_triangleIcon.height() / 2, m_triangleIcon); } } void CrumblePathButton::tintImages() { StyleHelper::tintImage(m_segmentEnd, m_baseColor); StyleHelper::tintImage(m_segmentSelectedEnd, m_baseColor); StyleHelper::tintImage(m_segmentHoverEnd, m_baseColor); StyleHelper::tintImage(m_segmentSelected, m_baseColor); StyleHelper::tintImage(m_segmentHover, m_baseColor); StyleHelper::tintImage(m_segment, m_baseColor); } void CrumblePathButton::leaveEvent(QEvent *e) { QPushButton::leaveEvent(e); m_isHovering = false; update(); } void CrumblePathButton::mouseMoveEvent(QMouseEvent *e) { QPushButton::mouseMoveEvent(e); m_isHovering = true; update(); } void CrumblePathButton::mousePressEvent(QMouseEvent *e) { QPushButton::mousePressEvent(e); m_isPressed = true; update(); } void CrumblePathButton::mouseReleaseEvent(QMouseEvent *e) { QPushButton::mouseReleaseEvent(e); m_isPressed = false; update(); } void CrumblePathButton::select(bool s) { m_isSelected = s; update(); } void CrumblePathButton::setSegmentType(int type) { bool useLeftPadding = !(type & FirstSegment); m_isEnd = (type & LastSegment); m_textPos.setX(useLeftPadding ? 18 : 4); } void CrumblePathButton::setData(const QVariant &data) { m_data = data; } QVariant CrumblePathButton::data() const { return m_data; } /////////////////////////////////////////////////////////////////////////////// struct CrumblePathPrivate { explicit CrumblePathPrivate(CrumblePath *q); QList<CrumblePathButton*> m_buttons; }; CrumblePathPrivate::CrumblePathPrivate(CrumblePath *q) { Q_UNUSED(q) } // // CrumblePath // CrumblePath::CrumblePath(QWidget *parent) : QWidget(parent), d(new CrumblePathPrivate(this)) { setMinimumHeight(25); setMaximumHeight(25); setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); } CrumblePath::~CrumblePath() { qDeleteAll(d->m_buttons); d->m_buttons.clear(); } void CrumblePath::selectIndex(int index) { if (index > -1 && index < d->m_buttons.length()) d->m_buttons[index]->select(true); } QVariant CrumblePath::dataForIndex(int index) const { if (index > -1 && index < d->m_buttons.length()) return d->m_buttons[index]->data(); return QVariant(); } void CrumblePath::pushElement(const QString &title, const QVariant &data) { CrumblePathButton *newButton = new CrumblePathButton(title, this); newButton->hide(); connect(newButton, SIGNAL(clicked()), SLOT(mapClickToIndex())); int segType = CrumblePathButton::MiddleSegment; if (!d->m_buttons.isEmpty()) { if (d->m_buttons.length() == 1) segType = segType | CrumblePathButton::FirstSegment; d->m_buttons.last()->setSegmentType(segType); } else { segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment; newButton->setSegmentType(segType); } newButton->setData(data); d->m_buttons.append(newButton); resizeButtons(); } void CrumblePath::addChild(const QString &title, const QVariant &data) { QTC_ASSERT(d->m_buttons.count() > 0,return); QPushButton *lastButton = d->m_buttons.last(); QMenu *childList = lastButton->menu(); if (childList == 0) childList = new QMenu(lastButton); QAction *childAction = new QAction(title, lastButton); childAction->setData(data); connect(childAction, SIGNAL(triggered()), this, SLOT(mapClickToIndex())); childList->addAction(childAction); lastButton->setMenu(childList); } void CrumblePath::popElement() { QWidget *last = d->m_buttons.last(); d->m_buttons.removeLast(); last->setParent(0); last->deleteLater(); int segType = CrumblePathButton::MiddleSegment | CrumblePathButton::LastSegment; if (!d->m_buttons.isEmpty()) { if (d->m_buttons.length() == 1) segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment; d->m_buttons.last()->setSegmentType(segType); } resizeButtons(); } void CrumblePath::clear() { while (!d->m_buttons.isEmpty()) popElement(); } void CrumblePath::resizeEvent(QResizeEvent *) { resizeButtons(); } void CrumblePath::resizeButtons() { int totalWidthLeft = width(); if (d->m_buttons.length() >= 1) { QPoint nextElementPosition(0, 0); d->m_buttons.first()->raise(); // rearrange all items so that the first item is on top (added last). // compute relative sizes QList<int> sizes; int totalSize = 0; for (int i = 0; i < d->m_buttons.length() ; ++i) { CrumblePathButton *button = d->m_buttons.at(i); QFontMetrics fm(button->font()); int originalSize = ArrowBorderSize + fm.width(button->text()) + ArrowBorderSize + 12; sizes << originalSize; totalSize += originalSize - ArrowBorderSize; } for (int i = 0; i < d->m_buttons.length() ; ++i) { CrumblePathButton *button = d->m_buttons.at(i); int candidateSize = (sizes.at(i) * totalWidthLeft) / totalSize; if (candidateSize < ArrowBorderSize) candidateSize = ArrowBorderSize; if (candidateSize > sizes.at(i) * 1.3) candidateSize = sizes.at(i) * 1.3; button->setMinimumWidth(candidateSize); button->setMaximumWidth(candidateSize); button->move(nextElementPosition); nextElementPosition.rx() += button->width() - ArrowBorderSize; button->show(); if (i > 0) button->stackUnder(d->m_buttons[i - 1]); } } } void CrumblePath::mapClickToIndex() { QObject *element = sender(); if (QString("QAction") == element->metaObject()->className()) emit elementClicked(static_cast<QAction *>(element)->data().toInt()); else if (QString("QPushButton") == element->metaObject()->className()) emit elementClicked(static_cast<CrumblePathButton *>(element)->data().toInt()); } } // namespace Utils <commit_msg>QmlDebug: Fix crash on Mac OS X<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "crumblepath.h" #include "stylehelper.h" #include <QtCore/QList> #include <QtGui/QHBoxLayout> #include <QtGui/QPushButton> #include <QtGui/QMenu> #include <QtGui/QStyle> #include <QtGui/QResizeEvent> #include <QtGui/QPainter> #include <QtGui/QImage> #include <qtcassert.h> namespace Utils { static const int ArrowBorderSize = 12; class CrumblePathButton : public QPushButton { public: enum SegmentType { LastSegment = 1, MiddleSegment = 2, FirstSegment = 4 }; explicit CrumblePathButton(const QString &title, QWidget *parent = 0); void setSegmentType(int type); void select(bool s); void setData(const QVariant &data); QVariant data() const; protected: void paintEvent(QPaintEvent *); void mouseMoveEvent(QMouseEvent *e); void leaveEvent(QEvent *); void mousePressEvent(QMouseEvent *e); void mouseReleaseEvent(QMouseEvent *e); private: void tintImages(); private: bool m_isHovering; bool m_isPressed; bool m_isSelected; bool m_isEnd; QColor m_baseColor; QImage m_segment; QImage m_segmentEnd; QImage m_segmentSelected; QImage m_segmentSelectedEnd; QImage m_segmentHover; QImage m_segmentHoverEnd; QImage m_triangleIcon; QPoint m_textPos; QVariant m_data; }; CrumblePathButton::CrumblePathButton(const QString &title, QWidget *parent) : QPushButton(title, parent), m_isHovering(false), m_isPressed(false), m_isSelected(false), m_isEnd(true) { setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); setToolTip(title); setMinimumHeight(25); setMaximumHeight(25); setMouseTracking(true); m_textPos.setX(18); m_textPos.setY(height()); m_baseColor = StyleHelper::baseColor(); m_segment = QImage(":/utils/images/crumblepath-segment.png"); m_segmentSelected = QImage(":/utils/images/crumblepath-segment-selected.png"); m_segmentHover = QImage(":/utils/images/crumblepath-segment-hover.png"); m_segmentEnd = QImage(":/utils/images/crumblepath-segment-end.png"); m_segmentSelectedEnd = QImage(":/utils/images/crumblepath-segment-selected-end.png"); m_segmentHoverEnd = QImage(":/utils/images/crumblepath-segment-hover-end.png"); m_triangleIcon = QImage(":/utils/images/triangle_vert.png"); tintImages(); } void CrumblePathButton::paintEvent(QPaintEvent *) { QPainter p(this); QRect geom(0, 0, geometry().width(), geometry().height()); if (StyleHelper::baseColor() != m_baseColor) { m_baseColor = StyleHelper::baseColor(); tintImages(); } if (m_isEnd) { if (m_isPressed || m_isSelected) { Utils::StyleHelper::drawCornerImage(m_segmentSelectedEnd, &p, geom, 2, 0, 2, 0); } else if (m_isHovering) { Utils::StyleHelper::drawCornerImage(m_segmentHoverEnd, &p, geom, 2, 0, 2, 0); } else { Utils::StyleHelper::drawCornerImage(m_segmentEnd, &p, geom, 2, 0, 2, 0); } } else { if (m_isPressed || m_isSelected) { Utils::StyleHelper::drawCornerImage(m_segmentSelected, &p, geom, 2, 0, 12, 0); } else if (m_isHovering) { Utils::StyleHelper::drawCornerImage(m_segmentHover, &p, geom, 2, 0, 12, 0); } else { Utils::StyleHelper::drawCornerImage(m_segment, &p, geom, 2, 0, 12, 0); } } p.setPen(StyleHelper::panelTextColor()); QFontMetrics fm(p.font()); QString textToDraw = fm.elidedText(text(), Qt::ElideRight, geom.width() - m_textPos.x()); p.drawText(QRectF(m_textPos.x(), 4, geom.width(), geom.height()), textToDraw); if (menu()) { p.drawImage(geom.width() - m_triangleIcon.width() - 6, geom.center().y() - m_triangleIcon.height() / 2, m_triangleIcon); } } void CrumblePathButton::tintImages() { StyleHelper::tintImage(m_segmentEnd, m_baseColor); StyleHelper::tintImage(m_segmentSelectedEnd, m_baseColor); StyleHelper::tintImage(m_segmentHoverEnd, m_baseColor); StyleHelper::tintImage(m_segmentSelected, m_baseColor); StyleHelper::tintImage(m_segmentHover, m_baseColor); StyleHelper::tintImage(m_segment, m_baseColor); } void CrumblePathButton::leaveEvent(QEvent *e) { QPushButton::leaveEvent(e); m_isHovering = false; update(); } void CrumblePathButton::mouseMoveEvent(QMouseEvent *e) { QPushButton::mouseMoveEvent(e); m_isHovering = true; update(); } void CrumblePathButton::mousePressEvent(QMouseEvent *e) { QPushButton::mousePressEvent(e); m_isPressed = true; update(); } void CrumblePathButton::mouseReleaseEvent(QMouseEvent *e) { QPushButton::mouseReleaseEvent(e); m_isPressed = false; update(); } void CrumblePathButton::select(bool s) { m_isSelected = s; update(); } void CrumblePathButton::setSegmentType(int type) { bool useLeftPadding = !(type & FirstSegment); m_isEnd = (type & LastSegment); m_textPos.setX(useLeftPadding ? 18 : 4); } void CrumblePathButton::setData(const QVariant &data) { m_data = data; } QVariant CrumblePathButton::data() const { return m_data; } /////////////////////////////////////////////////////////////////////////////// struct CrumblePathPrivate { explicit CrumblePathPrivate(CrumblePath *q); QList<CrumblePathButton*> m_buttons; }; CrumblePathPrivate::CrumblePathPrivate(CrumblePath *q) { Q_UNUSED(q) } // // CrumblePath // CrumblePath::CrumblePath(QWidget *parent) : QWidget(parent), d(new CrumblePathPrivate(this)) { setMinimumHeight(25); setMaximumHeight(25); setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); } CrumblePath::~CrumblePath() { qDeleteAll(d->m_buttons); d->m_buttons.clear(); } void CrumblePath::selectIndex(int index) { if (index > -1 && index < d->m_buttons.length()) d->m_buttons[index]->select(true); } QVariant CrumblePath::dataForIndex(int index) const { if (index > -1 && index < d->m_buttons.length()) return d->m_buttons[index]->data(); return QVariant(); } void CrumblePath::pushElement(const QString &title, const QVariant &data) { CrumblePathButton *newButton = new CrumblePathButton(title, this); newButton->hide(); connect(newButton, SIGNAL(clicked()), SLOT(mapClickToIndex())); int segType = CrumblePathButton::MiddleSegment; if (!d->m_buttons.isEmpty()) { if (d->m_buttons.length() == 1) segType = segType | CrumblePathButton::FirstSegment; d->m_buttons.last()->setSegmentType(segType); } else { segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment; newButton->setSegmentType(segType); } newButton->setData(data); d->m_buttons.append(newButton); resizeButtons(); } void CrumblePath::addChild(const QString &title, const QVariant &data) { QTC_ASSERT(d->m_buttons.count() > 0,return); QPushButton *lastButton = d->m_buttons.last(); QMenu *childList = lastButton->menu(); if (childList == 0) childList = new QMenu(lastButton); QAction *childAction = new QAction(title, lastButton); childAction->setData(data); connect(childAction, SIGNAL(triggered()), this, SLOT(mapClickToIndex())); childList->addAction(childAction); lastButton->setMenu(childList); } void CrumblePath::popElement() { QWidget *last = d->m_buttons.last(); d->m_buttons.removeLast(); last->setParent(0); last->deleteLater(); int segType = CrumblePathButton::MiddleSegment | CrumblePathButton::LastSegment; if (!d->m_buttons.isEmpty()) { if (d->m_buttons.length() == 1) segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment; d->m_buttons.last()->setSegmentType(segType); } resizeButtons(); } void CrumblePath::clear() { while (!d->m_buttons.isEmpty()) popElement(); } void CrumblePath::resizeEvent(QResizeEvent *) { resizeButtons(); } void CrumblePath::resizeButtons() { int totalWidthLeft = width(); if (d->m_buttons.length() >= 1) { QPoint nextElementPosition(0, 0); d->m_buttons.first()->raise(); // rearrange all items so that the first item is on top (added last). // compute relative sizes QList<int> sizes; int totalSize = 0; for (int i = 0; i < d->m_buttons.length() ; ++i) { CrumblePathButton *button = d->m_buttons.at(i); QFontMetrics fm(button->font()); int originalSize = ArrowBorderSize + fm.width(button->text()) + ArrowBorderSize + 12; sizes << originalSize; totalSize += originalSize - ArrowBorderSize; } for (int i = 0; i < d->m_buttons.length() ; ++i) { CrumblePathButton *button = d->m_buttons.at(i); int candidateSize = (sizes.at(i) * totalWidthLeft) / totalSize; if (candidateSize < ArrowBorderSize) candidateSize = ArrowBorderSize; if (candidateSize > sizes.at(i) * 1.3) candidateSize = sizes.at(i) * 1.3; button->setMinimumWidth(candidateSize); button->setMaximumWidth(candidateSize); button->move(nextElementPosition); nextElementPosition.rx() += button->width() - ArrowBorderSize; button->show(); if (i > 0) { // work-around for a compiler / optimization bug in i686-apple-darwin9-g // without volatile, the optimizer (-O2) seems to do the wrong thing (tm // the d->m_buttons array with an invalid argument. volatile int prevIndex = i - 1; button->stackUnder(d->m_buttons[prevIndex]); } } } } void CrumblePath::mapClickToIndex() { QObject *element = sender(); if (QString("QAction") == element->metaObject()->className()) emit elementClicked(static_cast<QAction *>(element)->data().toInt()); else if (QString("QPushButton") == element->metaObject()->className()) emit elementClicked(static_cast<CrumblePathButton *>(element)->data().toInt()); } } // namespace Utils <|endoftext|>
<commit_before>#ifndef slic3r_TriangleMesh_hpp_ #define slic3r_TriangleMesh_hpp_ #include "libslic3r.h" #include <admesh/stl.h> #include <functional> #include <vector> #include <boost/thread.hpp> #include "BoundingBox.hpp" #include "Line.hpp" #include "Point.hpp" #include "Polygon.hpp" #include "ExPolygon.hpp" namespace Slic3r { class TriangleMesh; class TriangleMeshSlicer; typedef std::vector<TriangleMesh*> TriangleMeshPtrs; class TriangleMesh { public: TriangleMesh() : repaired(false) {} TriangleMesh(const Pointf3s &points, const std::vector<Vec3crd> &facets); void clear() { this->stl.clear(); this->its.clear(); this->repaired = false; } bool ReadSTLFile(const char* input_file) { return stl_open(&stl, input_file); } bool write_ascii(const char* output_file) { return stl_write_ascii(&this->stl, output_file, ""); } bool write_binary(const char* output_file) { return stl_write_binary(&this->stl, output_file, ""); } void repair(bool update_shared_vertices = true); float volume(); void check_topology(); bool is_manifold() const { return this->stl.stats.connected_facets_3_edge == (int)this->stl.stats.number_of_facets; } void WriteOBJFile(const char* output_file) const; void scale(float factor); void scale(const Vec3d &versor); void translate(float x, float y, float z); void translate(const Vec3f &displacement); void rotate(float angle, const Axis &axis); void rotate(float angle, const Vec3d& axis); void rotate_x(float angle) { this->rotate(angle, X); } void rotate_y(float angle) { this->rotate(angle, Y); } void rotate_z(float angle) { this->rotate(angle, Z); } void mirror(const Axis &axis); void mirror_x() { this->mirror(X); } void mirror_y() { this->mirror(Y); } void mirror_z() { this->mirror(Z); } void transform(const Transform3d& t, bool fix_left_handed = false); void transform(const Matrix3d& t, bool fix_left_handed = false); void align_to_origin(); void rotate(double angle, Point* center); TriangleMeshPtrs split() const; void merge(const TriangleMesh &mesh); ExPolygons horizontal_projection() const; const float* first_vertex() const { return this->stl.facet_start.empty() ? nullptr : &this->stl.facet_start.front().vertex[0](0); } // 2D convex hull of a 3D mesh projected into the Z=0 plane. Polygon convex_hull(); BoundingBoxf3 bounding_box() const; // Returns the bbox of this TriangleMesh transformed by the given transformation BoundingBoxf3 transformed_bounding_box(const Transform3d &trafo) const; // Return the size of the mesh in coordinates. Vec3d size() const { return stl.stats.size.cast<double>(); } /// Return the center of the related bounding box. Vec3d center() const { return this->bounding_box().center(); } // Returns the convex hull of this TriangleMesh TriangleMesh convex_hull_3d() const; // Slice this mesh at the provided Z levels and return the vector std::vector<ExPolygons> slice(const std::vector<double>& z); void reset_repair_stats(); bool needed_repair() const; void require_shared_vertices(); bool has_shared_vertices() const { return ! this->its.vertices.empty(); } size_t facets_count() const { return this->stl.stats.number_of_facets; } bool empty() const { return this->facets_count() == 0; } bool is_splittable() const; // Estimate of the memory occupied by this structure, important for keeping an eye on the Undo / Redo stack allocation. size_t memsize() const; // Release optional data from the mesh if the object is on the Undo / Redo stack only. Returns the amount of memory released. size_t release_optional(); // Restore optional data possibly released by release_optional(). void restore_optional(); stl_file stl; indexed_triangle_set its; bool repaired; private: std::deque<uint32_t> find_unvisited_neighbors(std::vector<unsigned char> &facet_visited) const; }; enum FacetEdgeType { // A general case, the cutting plane intersect a face at two different edges. feGeneral, // Two vertices are aligned with the cutting plane, the third vertex is below the cutting plane. feTop, // Two vertices are aligned with the cutting plane, the third vertex is above the cutting plane. feBottom, // All three vertices of a face are aligned with the cutting plane. feHorizontal }; class IntersectionReference { public: IntersectionReference() : point_id(-1), edge_id(-1) {}; IntersectionReference(int point_id, int edge_id) : point_id(point_id), edge_id(edge_id) {} // Where is this intersection point located? On mesh vertex or mesh edge? // Only one of the following will be set, the other will remain set to -1. // Index of the mesh vertex. int point_id; // Index of the mesh edge. int edge_id; }; class IntersectionPoint : public Point, public IntersectionReference { public: IntersectionPoint() {}; IntersectionPoint(int point_id, int edge_id, const Point &pt) : IntersectionReference(point_id, edge_id), Point(pt) {} IntersectionPoint(const IntersectionReference &ir, const Point &pt) : IntersectionReference(ir), Point(pt) {} // Inherits coord_t x, y }; class IntersectionLine : public Line { public: IntersectionLine() : a_id(-1), b_id(-1), edge_a_id(-1), edge_b_id(-1), edge_type(feGeneral), flags(0) {} bool skip() const { return (this->flags & SKIP) != 0; } void set_skip() { this->flags |= SKIP; } bool is_seed_candidate() const { return (this->flags & NO_SEED) == 0 && ! this->skip(); } void set_no_seed(bool set) { if (set) this->flags |= NO_SEED; else this->flags &= ~NO_SEED; } // Inherits Point a, b // For each line end point, either {a,b}_id or {a,b}edge_a_id is set, the other is left to -1. // Vertex indices of the line end points. int a_id; int b_id; // Source mesh edges of the line end points. int edge_a_id; int edge_b_id; // feGeneral, feTop, feBottom, feHorizontal FacetEdgeType edge_type; // Used by TriangleMeshSlicer::slice() to skip duplicate edges. enum { // Triangle edge added, because it has no neighbor. EDGE0_NO_NEIGHBOR = 0x001, EDGE1_NO_NEIGHBOR = 0x002, EDGE2_NO_NEIGHBOR = 0x004, // Triangle edge added, because it makes a fold with another horizontal edge. EDGE0_FOLD = 0x010, EDGE1_FOLD = 0x020, EDGE2_FOLD = 0x040, // The edge cannot be a seed of a greedy loop extraction (folds are not safe to become seeds). NO_SEED = 0x100, SKIP = 0x200, }; uint32_t flags; }; typedef std::vector<IntersectionLine> IntersectionLines; typedef std::vector<IntersectionLine*> IntersectionLinePtrs; class TriangleMeshSlicer { public: typedef std::function<void()> throw_on_cancel_callback_type; TriangleMeshSlicer() : mesh(nullptr) {} TriangleMeshSlicer(const TriangleMesh* mesh) { this->init(mesh, [](){}); } void init(const TriangleMesh *mesh, throw_on_cancel_callback_type throw_on_cancel); void slice(const std::vector<float> &z, std::vector<Polygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const; void slice(const std::vector<float> &z, const float closing_radius, std::vector<ExPolygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const; enum FacetSliceType { NoSlice = 0, Slicing = 1, Cutting = 2 }; FacetSliceType slice_facet(float slice_z, const stl_facet &facet, const int facet_idx, const float min_z, const float max_z, IntersectionLine *line_out) const; void cut(float z, TriangleMesh* upper, TriangleMesh* lower) const; void set_up_direction(const Vec3f& up); private: const TriangleMesh *mesh; // Map from a facet to an edge index. std::vector<int> facets_edges; // Scaled copy of this->mesh->stl.v_shared std::vector<stl_vertex> v_scaled_shared; // Quaternion that will be used to rotate every facet before the slicing Eigen::Quaternion<float, Eigen::DontAlign> m_quaternion; // Whether or not the above quaterion should be used bool m_use_quaternion = false; void _slice_do(size_t facet_idx, std::vector<IntersectionLines>* lines, boost::mutex* lines_mutex, const std::vector<float> &z) const; void make_loops(std::vector<IntersectionLine> &lines, Polygons* loops) const; void make_expolygons(const Polygons &loops, const float closing_radius, ExPolygons* slices) const; void make_expolygons_simple(std::vector<IntersectionLine> &lines, ExPolygons* slices) const; void make_expolygons(std::vector<IntersectionLine> &lines, const float closing_radius, ExPolygons* slices) const; }; TriangleMesh make_cube(double x, double y, double z); // Generate a TriangleMesh of a cylinder TriangleMesh make_cylinder(double r, double h, double fa=(2*PI/360)); TriangleMesh make_sphere(double rho, double fa=(2*PI/360)); } // Serialization through the Cereal library #include <cereal/access.hpp> namespace cereal { template <class Archive> struct specialize<Archive, Slic3r::TriangleMesh, cereal::specialization::non_member_load_save> {}; template<class Archive> void load(Archive &archive, Slic3r::TriangleMesh &mesh) { stl_file &stl = mesh.stl; stl.stats.type = inmemory; archive(stl.stats.number_of_facets, stl.stats.original_num_facets); stl_allocate(&stl); archive.loadBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50); stl_get_size(&stl); mesh.repair(); } template<class Archive> void save(Archive &archive, const Slic3r::TriangleMesh &mesh) { const stl_file& stl = mesh.stl; archive(stl.stats.number_of_facets, stl.stats.original_num_facets); archive.saveBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50); } } #endif <commit_msg>Add free functions to slice a TriangleMesh<commit_after>#ifndef slic3r_TriangleMesh_hpp_ #define slic3r_TriangleMesh_hpp_ #include "libslic3r.h" #include <admesh/stl.h> #include <functional> #include <vector> #include <boost/thread.hpp> #include "BoundingBox.hpp" #include "Line.hpp" #include "Point.hpp" #include "Polygon.hpp" #include "ExPolygon.hpp" namespace Slic3r { class TriangleMesh; class TriangleMeshSlicer; typedef std::vector<TriangleMesh*> TriangleMeshPtrs; class TriangleMesh { public: TriangleMesh() : repaired(false) {} TriangleMesh(const Pointf3s &points, const std::vector<Vec3crd> &facets); void clear() { this->stl.clear(); this->its.clear(); this->repaired = false; } bool ReadSTLFile(const char* input_file) { return stl_open(&stl, input_file); } bool write_ascii(const char* output_file) { return stl_write_ascii(&this->stl, output_file, ""); } bool write_binary(const char* output_file) { return stl_write_binary(&this->stl, output_file, ""); } void repair(bool update_shared_vertices = true); float volume(); void check_topology(); bool is_manifold() const { return this->stl.stats.connected_facets_3_edge == (int)this->stl.stats.number_of_facets; } void WriteOBJFile(const char* output_file) const; void scale(float factor); void scale(const Vec3d &versor); void translate(float x, float y, float z); void translate(const Vec3f &displacement); void rotate(float angle, const Axis &axis); void rotate(float angle, const Vec3d& axis); void rotate_x(float angle) { this->rotate(angle, X); } void rotate_y(float angle) { this->rotate(angle, Y); } void rotate_z(float angle) { this->rotate(angle, Z); } void mirror(const Axis &axis); void mirror_x() { this->mirror(X); } void mirror_y() { this->mirror(Y); } void mirror_z() { this->mirror(Z); } void transform(const Transform3d& t, bool fix_left_handed = false); void transform(const Matrix3d& t, bool fix_left_handed = false); void align_to_origin(); void rotate(double angle, Point* center); TriangleMeshPtrs split() const; void merge(const TriangleMesh &mesh); ExPolygons horizontal_projection() const; const float* first_vertex() const { return this->stl.facet_start.empty() ? nullptr : &this->stl.facet_start.front().vertex[0](0); } // 2D convex hull of a 3D mesh projected into the Z=0 plane. Polygon convex_hull(); BoundingBoxf3 bounding_box() const; // Returns the bbox of this TriangleMesh transformed by the given transformation BoundingBoxf3 transformed_bounding_box(const Transform3d &trafo) const; // Return the size of the mesh in coordinates. Vec3d size() const { return stl.stats.size.cast<double>(); } /// Return the center of the related bounding box. Vec3d center() const { return this->bounding_box().center(); } // Returns the convex hull of this TriangleMesh TriangleMesh convex_hull_3d() const; // Slice this mesh at the provided Z levels and return the vector std::vector<ExPolygons> slice(const std::vector<double>& z); void reset_repair_stats(); bool needed_repair() const; void require_shared_vertices(); bool has_shared_vertices() const { return ! this->its.vertices.empty(); } size_t facets_count() const { return this->stl.stats.number_of_facets; } bool empty() const { return this->facets_count() == 0; } bool is_splittable() const; // Estimate of the memory occupied by this structure, important for keeping an eye on the Undo / Redo stack allocation. size_t memsize() const; // Release optional data from the mesh if the object is on the Undo / Redo stack only. Returns the amount of memory released. size_t release_optional(); // Restore optional data possibly released by release_optional(). void restore_optional(); stl_file stl; indexed_triangle_set its; bool repaired; private: std::deque<uint32_t> find_unvisited_neighbors(std::vector<unsigned char> &facet_visited) const; }; enum FacetEdgeType { // A general case, the cutting plane intersect a face at two different edges. feGeneral, // Two vertices are aligned with the cutting plane, the third vertex is below the cutting plane. feTop, // Two vertices are aligned with the cutting plane, the third vertex is above the cutting plane. feBottom, // All three vertices of a face are aligned with the cutting plane. feHorizontal }; class IntersectionReference { public: IntersectionReference() : point_id(-1), edge_id(-1) {}; IntersectionReference(int point_id, int edge_id) : point_id(point_id), edge_id(edge_id) {} // Where is this intersection point located? On mesh vertex or mesh edge? // Only one of the following will be set, the other will remain set to -1. // Index of the mesh vertex. int point_id; // Index of the mesh edge. int edge_id; }; class IntersectionPoint : public Point, public IntersectionReference { public: IntersectionPoint() {}; IntersectionPoint(int point_id, int edge_id, const Point &pt) : IntersectionReference(point_id, edge_id), Point(pt) {} IntersectionPoint(const IntersectionReference &ir, const Point &pt) : IntersectionReference(ir), Point(pt) {} // Inherits coord_t x, y }; class IntersectionLine : public Line { public: IntersectionLine() : a_id(-1), b_id(-1), edge_a_id(-1), edge_b_id(-1), edge_type(feGeneral), flags(0) {} bool skip() const { return (this->flags & SKIP) != 0; } void set_skip() { this->flags |= SKIP; } bool is_seed_candidate() const { return (this->flags & NO_SEED) == 0 && ! this->skip(); } void set_no_seed(bool set) { if (set) this->flags |= NO_SEED; else this->flags &= ~NO_SEED; } // Inherits Point a, b // For each line end point, either {a,b}_id or {a,b}edge_a_id is set, the other is left to -1. // Vertex indices of the line end points. int a_id; int b_id; // Source mesh edges of the line end points. int edge_a_id; int edge_b_id; // feGeneral, feTop, feBottom, feHorizontal FacetEdgeType edge_type; // Used by TriangleMeshSlicer::slice() to skip duplicate edges. enum { // Triangle edge added, because it has no neighbor. EDGE0_NO_NEIGHBOR = 0x001, EDGE1_NO_NEIGHBOR = 0x002, EDGE2_NO_NEIGHBOR = 0x004, // Triangle edge added, because it makes a fold with another horizontal edge. EDGE0_FOLD = 0x010, EDGE1_FOLD = 0x020, EDGE2_FOLD = 0x040, // The edge cannot be a seed of a greedy loop extraction (folds are not safe to become seeds). NO_SEED = 0x100, SKIP = 0x200, }; uint32_t flags; }; typedef std::vector<IntersectionLine> IntersectionLines; typedef std::vector<IntersectionLine*> IntersectionLinePtrs; class TriangleMeshSlicer { public: typedef std::function<void()> throw_on_cancel_callback_type; TriangleMeshSlicer() : mesh(nullptr) {} TriangleMeshSlicer(const TriangleMesh* mesh) { this->init(mesh, [](){}); } void init(const TriangleMesh *mesh, throw_on_cancel_callback_type throw_on_cancel); void slice(const std::vector<float> &z, std::vector<Polygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const; void slice(const std::vector<float> &z, const float closing_radius, std::vector<ExPolygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const; enum FacetSliceType { NoSlice = 0, Slicing = 1, Cutting = 2 }; FacetSliceType slice_facet(float slice_z, const stl_facet &facet, const int facet_idx, const float min_z, const float max_z, IntersectionLine *line_out) const; void cut(float z, TriangleMesh* upper, TriangleMesh* lower) const; void set_up_direction(const Vec3f& up); private: const TriangleMesh *mesh; // Map from a facet to an edge index. std::vector<int> facets_edges; // Scaled copy of this->mesh->stl.v_shared std::vector<stl_vertex> v_scaled_shared; // Quaternion that will be used to rotate every facet before the slicing Eigen::Quaternion<float, Eigen::DontAlign> m_quaternion; // Whether or not the above quaterion should be used bool m_use_quaternion = false; void _slice_do(size_t facet_idx, std::vector<IntersectionLines>* lines, boost::mutex* lines_mutex, const std::vector<float> &z) const; void make_loops(std::vector<IntersectionLine> &lines, Polygons* loops) const; void make_expolygons(const Polygons &loops, const float closing_radius, ExPolygons* slices) const; void make_expolygons_simple(std::vector<IntersectionLine> &lines, ExPolygons* slices) const; void make_expolygons(std::vector<IntersectionLine> &lines, const float closing_radius, ExPolygons* slices) const; }; inline void slice_mesh( const TriangleMesh & mesh, const std::vector<float> & z, std::vector<Polygons> & layers, TriangleMeshSlicer::throw_on_cancel_callback_type thr = nullptr) { if (mesh.empty()) return; TriangleMeshSlicer slicer(&mesh); slicer.slice(z, &layers, thr); } inline void slice_mesh( const TriangleMesh & mesh, const std::vector<float> & z, std::vector<ExPolygons> & layers, float closing_radius, TriangleMeshSlicer::throw_on_cancel_callback_type thr = nullptr) { if (mesh.empty()) return; TriangleMeshSlicer slicer(&mesh); slicer.slice(z, closing_radius, &layers, thr); } TriangleMesh make_cube(double x, double y, double z); // Generate a TriangleMesh of a cylinder TriangleMesh make_cylinder(double r, double h, double fa=(2*PI/360)); TriangleMesh make_sphere(double rho, double fa=(2*PI/360)); } // Serialization through the Cereal library #include <cereal/access.hpp> namespace cereal { template <class Archive> struct specialize<Archive, Slic3r::TriangleMesh, cereal::specialization::non_member_load_save> {}; template<class Archive> void load(Archive &archive, Slic3r::TriangleMesh &mesh) { stl_file &stl = mesh.stl; stl.stats.type = inmemory; archive(stl.stats.number_of_facets, stl.stats.original_num_facets); stl_allocate(&stl); archive.loadBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50); stl_get_size(&stl); mesh.repair(); } template<class Archive> void save(Archive &archive, const Slic3r::TriangleMesh &mesh) { const stl_file& stl = mesh.stl; archive(stl.stats.number_of_facets, stl.stats.original_num_facets); archive.saveBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50); } } #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "projwrapper_p.h" #include <proj_api.h> #include <QSharedData> #include <QString> #include <QPolygonF> #include <QPointF> QTM_BEGIN_NAMESPACE class ProjCoordinateSystemPrivate : public QSharedData { public: ProjCoordinateSystemPrivate(const QString &projection, bool latLon); ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other); ~ProjCoordinateSystemPrivate(); projPJ projection; bool latLon; }; ProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const QString &projStr, bool isLatLon) { projection = pj_init_plus(projStr.toLatin1().constData()); Q_ASSERT_X(projection, "pj_init_plus", "invalid projection string"); latLon = isLatLon; } ProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other) : QSharedData(other), projection(other.projection) {} ProjCoordinateSystemPrivate::~ProjCoordinateSystemPrivate() {} ProjCoordinateSystem::ProjCoordinateSystem(const QString &projection, bool latLon) : d(new ProjCoordinateSystemPrivate(projection, latLon)) {} ProjCoordinateSystem::ProjCoordinateSystem(const ProjCoordinateSystem &other) : d(other.d) {} ProjCoordinateSystem::~ProjCoordinateSystem() {} bool ProjCoordinateSystem::isLatLon() const { return d->latLon; } class ProjCoordinatePrivate { public: ProjCoordinateSystem currentSystem; double x; double y; double z; }; ProjCoordinate::ProjCoordinate(double x, double y, double z, const ProjCoordinateSystem &system) : d(new ProjCoordinatePrivate) { d->x = x; d->y = y; d->z = z; d->currentSystem = system; } ProjCoordinate::ProjCoordinate(const ProjCoordinate &other) : d(new ProjCoordinatePrivate) { d->x = other.d->x; d->y = other.d->y; d->z = other.d->z; d->currentSystem = other.d->currentSystem; } ProjCoordinate::~ProjCoordinate() {} double ProjCoordinate::x() const { return d->x; } double ProjCoordinate::y() const { return d->y; } double ProjCoordinate::z() const { return d->z; } bool ProjCoordinate::convert(const ProjCoordinateSystem &system) { int result; double x = d->x, y = d->y, z = d->z; if (d->currentSystem.isLatLon()) { x *= DEG_TO_RAD; y *= DEG_TO_RAD; } result = pj_transform(d->currentSystem.d->projection, system.d->projection, 1, 1, &x, &y, &z); if (result) { return false; } else { if (system.isLatLon()) { x *= RAD_TO_DEG; y *= RAD_TO_DEG; } d->x = x; d->y = y; d->z = z; d->currentSystem = system; return true; } } class ProjPolygonPrivate { public: ProjCoordinateSystem currentSystem; }; ProjPolygon::ProjPolygon(const ProjCoordinateSystem &system) : QList<ProjCoordinate>(), d(new ProjPolygonPrivate) { d->currentSystem = system; } ProjPolygon::ProjPolygon(const QPolygonF &poly, const ProjCoordinateSystem &system, double scale) : QList<ProjCoordinate>(), d(new ProjPolygonPrivate) { d->currentSystem = system; foreach (QPointF point, poly) { double x = point.x(); x /= scale; double y = point.y(); y /= scale; append(ProjCoordinate(x, y, 0.0, system)); } } bool ProjPolygon::convert(const ProjCoordinateSystem &system) { for (int i=0; i<size(); ++i) { ProjCoordinate coord = at(i); if (!coord.convert(system)) return false; replace(i, coord); } d->currentSystem = system; return true; } QPolygonF ProjPolygon::toPolygonF(double scale) const { QPolygonF poly; for (int i=0; i<size(); ++i) { const ProjCoordinate &coord = at(i); double x = coord.x() * scale; double y = coord.y() * scale; poly << QPointF(x, y); } return poly; } QTM_END_NAMESPACE <commit_msg>Adding destructor implementation for ProjPolygon<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "projwrapper_p.h" #include <proj_api.h> #include <QSharedData> #include <QString> #include <QPolygonF> #include <QPointF> QTM_BEGIN_NAMESPACE class ProjCoordinateSystemPrivate : public QSharedData { public: ProjCoordinateSystemPrivate(const QString &projection, bool latLon); ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other); ~ProjCoordinateSystemPrivate(); projPJ projection; bool latLon; }; ProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const QString &projStr, bool isLatLon) { projection = pj_init_plus(projStr.toLatin1().constData()); Q_ASSERT_X(projection, "pj_init_plus", "invalid projection string"); latLon = isLatLon; } ProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other) : QSharedData(other), projection(other.projection) {} ProjCoordinateSystemPrivate::~ProjCoordinateSystemPrivate() {} ProjCoordinateSystem::ProjCoordinateSystem(const QString &projection, bool latLon) : d(new ProjCoordinateSystemPrivate(projection, latLon)) {} ProjCoordinateSystem::ProjCoordinateSystem(const ProjCoordinateSystem &other) : d(other.d) {} ProjCoordinateSystem::~ProjCoordinateSystem() {} bool ProjCoordinateSystem::isLatLon() const { return d->latLon; } class ProjCoordinatePrivate { public: ProjCoordinateSystem currentSystem; double x; double y; double z; }; ProjCoordinate::ProjCoordinate(double x, double y, double z, const ProjCoordinateSystem &system) : d(new ProjCoordinatePrivate) { d->x = x; d->y = y; d->z = z; d->currentSystem = system; } ProjCoordinate::ProjCoordinate(const ProjCoordinate &other) : d(new ProjCoordinatePrivate) { d->x = other.d->x; d->y = other.d->y; d->z = other.d->z; d->currentSystem = other.d->currentSystem; } ProjCoordinate::~ProjCoordinate() {} double ProjCoordinate::x() const { return d->x; } double ProjCoordinate::y() const { return d->y; } double ProjCoordinate::z() const { return d->z; } bool ProjCoordinate::convert(const ProjCoordinateSystem &system) { int result; double x = d->x, y = d->y, z = d->z; if (d->currentSystem.isLatLon()) { x *= DEG_TO_RAD; y *= DEG_TO_RAD; } result = pj_transform(d->currentSystem.d->projection, system.d->projection, 1, 1, &x, &y, &z); if (result) { return false; } else { if (system.isLatLon()) { x *= RAD_TO_DEG; y *= RAD_TO_DEG; } d->x = x; d->y = y; d->z = z; d->currentSystem = system; return true; } } class ProjPolygonPrivate { public: ProjCoordinateSystem currentSystem; }; ProjPolygon::ProjPolygon(const ProjCoordinateSystem &system) : QList<ProjCoordinate>(), d(new ProjPolygonPrivate) { d->currentSystem = system; } ProjPolygon::ProjPolygon(const QPolygonF &poly, const ProjCoordinateSystem &system, double scale) : QList<ProjCoordinate>(), d(new ProjPolygonPrivate) { d->currentSystem = system; foreach (QPointF point, poly) { double x = point.x(); x /= scale; double y = point.y(); y /= scale; append(ProjCoordinate(x, y, 0.0, system)); } } ProjPolygon::~ProjPolygon() {} bool ProjPolygon::convert(const ProjCoordinateSystem &system) { for (int i=0; i<size(); ++i) { ProjCoordinate coord = at(i); if (!coord.convert(system)) return false; replace(i, coord); } d->currentSystem = system; return true; } QPolygonF ProjPolygon::toPolygonF(double scale) const { QPolygonF poly; for (int i=0; i<size(); ++i) { const ProjCoordinate &coord = at(i); double x = coord.x() * scale; double y = coord.y() * scale; poly << QPointF(x, y); } return poly; } QTM_END_NAMESPACE <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Steve Reinhardt */ #include <cstring> #include <fstream> #include <list> #include <string> #include <vector> #include "base/misc.hh" #include "params/Root.hh" #include "sim/sim_object.hh" // Dummy Object struct Root : public SimObject { Root(RootParams *params) : SimObject(params) {} }; Root * RootParams::create() { static bool created = false; if (created) panic("only one root object allowed!"); created = true; return new Root(this); } <commit_msg>Root: Get rid of unnecessary includes in root.cc.<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Steve Reinhardt */ #include "base/misc.hh" #include "params/Root.hh" #include "sim/sim_object.hh" // Dummy Object struct Root : public SimObject { Root(RootParams *params) : SimObject(params) {} }; Root * RootParams::create() { static bool created = false; if (created) panic("only one root object allowed!"); created = true; return new Root(this); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qvariant.h> #include <QtCore/qdebug.h> #if defined(HAVE_WIDGETS) #include <QtWidgets/qwidget.h> #endif #include "qgstreamerplayerservice.h" #include "qgstreamerplayercontrol.h" #include "qgstreamerplayersession.h" #include "qgstreamermetadataprovider.h" #include "qgstreameravailabilitycontrol.h" #if defined(HAVE_WIDGETS) #include <private/qgstreamervideooverlay_p.h> #include <private/qgstreamervideowindow_p.h> #include <private/qgstreamervideowidget_p.h> #endif #include <private/qgstreamervideorenderer_p.h> #if defined(Q_WS_MAEMO_6) && defined(__arm__) #include "private/qgstreamergltexturerenderer.h" #endif #if defined(HAVE_MIR) && defined (__arm__) #include "private/qgstreamermirtexturerenderer_p.h" #endif #include "qgstreamerstreamscontrol.h" #include <private/qgstreameraudioprobecontrol_p.h> #include <private/qgstreamervideoprobecontrol_p.h> #include <private/qmediaplaylistnavigator_p.h> #include <qmediaplaylist.h> #include <private/qmediaresourceset_p.h> QT_BEGIN_NAMESPACE QGstreamerPlayerService::QGstreamerPlayerService(QObject *parent): QMediaService(parent) , m_videoOutput(0) , m_videoRenderer(0) #if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS) , m_videoWindow(0) , m_videoWidget(0) #endif , m_videoReferenceCount(0) { m_session = new QGstreamerPlayerSession(this); m_control = new QGstreamerPlayerControl(m_session, this); m_metaData = new QGstreamerMetaDataProvider(m_session, this); m_streamsControl = new QGstreamerStreamsControl(m_session,this); m_availabilityControl = new QGStreamerAvailabilityControl(m_control->resources(), this); #if defined(Q_WS_MAEMO_6) && defined(__arm__) m_videoRenderer = new QGstreamerGLTextureRenderer(this); // TODO: Implement HAVE_UBUNTU_TOUCH configure check and remove QGstreamerMirTextureRenderer from the else case #elif defined(HAVE_MIR) && defined (__arm__) m_videoRenderer = new QGstreamerMirTextureRenderer(this, m_session); #else //m_videoRenderer = new QGstreamerMirTextureRenderer(this, m_session); m_videoRenderer = new QGstreamerVideoRenderer(this); #endif #if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS) #ifdef Q_WS_MAEMO_6 m_videoWindow = new QGstreamerVideoWindow(this, "omapxvsink"); // TODO: Implement Q_WS_UBUNTU_TOUCH configure check and remove mirsink from the else case //#elif defined(HAVE_MIR) // m_videoWindow = new QGstreamerVideoWindow(this, "mirsink"); #else qDebug() << "Creating new QGstreamerVideoWindow, passing 'this'" << endl; //m_videoWindow = new QGstreamerVideoWindow(this, "mirsink"); m_videoWindow = new QGstreamerVideoOverlay(this); #endif m_videoWidget = new QGstreamerVideoWidgetControl(this); #endif } QGstreamerPlayerService::~QGstreamerPlayerService() { } QMediaControl *QGstreamerPlayerService::requestControl(const char *name) { if (qstrcmp(name,QMediaPlayerControl_iid) == 0) return m_control; if (qstrcmp(name,QMetaDataReaderControl_iid) == 0) return m_metaData; if (qstrcmp(name,QMediaStreamsControl_iid) == 0) return m_streamsControl; if (qstrcmp(name, QMediaAvailabilityControl_iid) == 0) return m_availabilityControl; if (qstrcmp(name,QMediaVideoProbeControl_iid) == 0) { if (m_session) { QGstreamerVideoProbeControl *probe = new QGstreamerVideoProbeControl(this); increaseVideoRef(); m_session->addProbe(probe); return probe; } return 0; } if (qstrcmp(name,QMediaAudioProbeControl_iid) == 0) { if (m_session) { QGstreamerAudioProbeControl *probe = new QGstreamerAudioProbeControl(this); m_session->addProbe(probe); return probe; } return 0; } if (!m_videoOutput) { if (qstrcmp(name, QVideoRendererControl_iid) == 0) m_videoOutput = m_videoRenderer; #if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS) else if (qstrcmp(name, QVideoWidgetControl_iid) == 0) m_videoOutput = m_videoWidget; else if (qstrcmp(name, QVideoWindowControl_iid) == 0) m_videoOutput = m_videoWindow; #endif if (m_videoOutput) { increaseVideoRef(); m_control->setVideoOutput(m_videoOutput); return m_videoOutput; } } return 0; } void QGstreamerPlayerService::releaseControl(QMediaControl *control) { if (control == m_videoOutput) { m_videoOutput = 0; m_control->setVideoOutput(0); decreaseVideoRef(); } QGstreamerVideoProbeControl* videoProbe = qobject_cast<QGstreamerVideoProbeControl*>(control); if (videoProbe) { if (m_session) { m_session->removeProbe(videoProbe); decreaseVideoRef(); } delete videoProbe; return; } QGstreamerAudioProbeControl* audioProbe = qobject_cast<QGstreamerAudioProbeControl*>(control); if (audioProbe) { if (m_session) m_session->removeProbe(audioProbe); delete audioProbe; return; } } void QGstreamerPlayerService::increaseVideoRef() { m_videoReferenceCount++; if (m_videoReferenceCount == 1) { m_control->resources()->setVideoEnabled(true); } } void QGstreamerPlayerService::decreaseVideoRef() { m_videoReferenceCount--; if (m_videoReferenceCount == 0) { m_control->resources()->setVideoEnabled(false); } } QT_END_NAMESPACE <commit_msg>Clean up the renderer choosing code after adding support for creating a QGstreamerMirTextureRenderer instance.<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qvariant.h> #include <QtCore/qdebug.h> #if defined(HAVE_WIDGETS) #include <QtWidgets/qwidget.h> #endif #include "qgstreamerplayerservice.h" #include "qgstreamerplayercontrol.h" #include "qgstreamerplayersession.h" #include "qgstreamermetadataprovider.h" #include "qgstreameravailabilitycontrol.h" #if defined(HAVE_WIDGETS) #include <private/qgstreamervideooverlay_p.h> #include <private/qgstreamervideowindow_p.h> #include <private/qgstreamervideowidget_p.h> #endif #include <private/qgstreamervideorenderer_p.h> #if defined(Q_WS_MAEMO_6) && defined(__arm__) #include "private/qgstreamergltexturerenderer.h" #endif #if defined(HAVE_MIR) && defined (__arm__) #include "private/qgstreamermirtexturerenderer_p.h" #endif #include "qgstreamerstreamscontrol.h" #include <private/qgstreameraudioprobecontrol_p.h> #include <private/qgstreamervideoprobecontrol_p.h> #include <private/qmediaplaylistnavigator_p.h> #include <qmediaplaylist.h> #include <private/qmediaresourceset_p.h> QT_BEGIN_NAMESPACE QGstreamerPlayerService::QGstreamerPlayerService(QObject *parent): QMediaService(parent) , m_videoOutput(0) , m_videoRenderer(0) #if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS) , m_videoWindow(0) , m_videoWidget(0) #endif , m_videoReferenceCount(0) { m_session = new QGstreamerPlayerSession(this); m_control = new QGstreamerPlayerControl(m_session, this); m_metaData = new QGstreamerMetaDataProvider(m_session, this); m_streamsControl = new QGstreamerStreamsControl(m_session,this); m_availabilityControl = new QGStreamerAvailabilityControl(m_control->resources(), this); #if defined(Q_WS_MAEMO_6) && defined(__arm__) m_videoRenderer = new QGstreamerGLTextureRenderer(this); #elif defined(HAVE_MIR) && defined (__arm__) m_videoRenderer = new QGstreamerMirTextureRenderer(this, m_session); #else m_videoRenderer = new QGstreamerVideoRenderer(this); #endif #if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS) #ifdef Q_WS_MAEMO_6 m_videoWindow = new QGstreamerVideoWindow(this, "omapxvsink"); #else m_videoWindow = new QGstreamerVideoOverlay(this); #endif m_videoWidget = new QGstreamerVideoWidgetControl(this); #endif } QGstreamerPlayerService::~QGstreamerPlayerService() { } QMediaControl *QGstreamerPlayerService::requestControl(const char *name) { if (qstrcmp(name,QMediaPlayerControl_iid) == 0) return m_control; if (qstrcmp(name,QMetaDataReaderControl_iid) == 0) return m_metaData; if (qstrcmp(name,QMediaStreamsControl_iid) == 0) return m_streamsControl; if (qstrcmp(name, QMediaAvailabilityControl_iid) == 0) return m_availabilityControl; if (qstrcmp(name,QMediaVideoProbeControl_iid) == 0) { if (m_session) { QGstreamerVideoProbeControl *probe = new QGstreamerVideoProbeControl(this); increaseVideoRef(); m_session->addProbe(probe); return probe; } return 0; } if (qstrcmp(name,QMediaAudioProbeControl_iid) == 0) { if (m_session) { QGstreamerAudioProbeControl *probe = new QGstreamerAudioProbeControl(this); m_session->addProbe(probe); return probe; } return 0; } if (!m_videoOutput) { if (qstrcmp(name, QVideoRendererControl_iid) == 0) m_videoOutput = m_videoRenderer; #if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS) else if (qstrcmp(name, QVideoWidgetControl_iid) == 0) m_videoOutput = m_videoWidget; else if (qstrcmp(name, QVideoWindowControl_iid) == 0) m_videoOutput = m_videoWindow; #endif if (m_videoOutput) { increaseVideoRef(); m_control->setVideoOutput(m_videoOutput); return m_videoOutput; } } return 0; } void QGstreamerPlayerService::releaseControl(QMediaControl *control) { if (control == m_videoOutput) { m_videoOutput = 0; m_control->setVideoOutput(0); decreaseVideoRef(); } QGstreamerVideoProbeControl* videoProbe = qobject_cast<QGstreamerVideoProbeControl*>(control); if (videoProbe) { if (m_session) { m_session->removeProbe(videoProbe); decreaseVideoRef(); } delete videoProbe; return; } QGstreamerAudioProbeControl* audioProbe = qobject_cast<QGstreamerAudioProbeControl*>(control); if (audioProbe) { if (m_session) m_session->removeProbe(audioProbe); delete audioProbe; return; } } void QGstreamerPlayerService::increaseVideoRef() { m_videoReferenceCount++; if (m_videoReferenceCount == 1) { m_control->resources()->setVideoEnabled(true); } } void QGstreamerPlayerService::decreaseVideoRef() { m_videoReferenceCount--; if (m_videoReferenceCount == 0) { m_control->resources()->setVideoEnabled(false); } } QT_END_NAMESPACE <|endoftext|>
<commit_before>#include <alvar_logger/alvar_logger_node.h> #include <sensor_msgs/image_encodings.h> #include <cv_bridge/cv_bridge.h> AlvarLoggerNode::AlvarLoggerNode(ros::NodeHandle &nh) : nh_(nh), it_(nh), frame_number_(0) { std::string camera_info_topic; if (!nh_.getParam("camera_info_topic", camera_info_topic)) { ROS_ERROR("Camera info topic needs to be specified"); exit(0); } cam_ = new alvar::Camera(nh_, camera_info_topic); std::string log_file_name; if (!nh_.getParam("log_file", log_file_name)) { ROS_ERROR("Log file needs to be specified"); exit(0); } if (!nh_.hasParam("video_file")) { ROS_ERROR("Video file needs to be specified"); exit(0); } file_out_.open(log_file_name.c_str()); image_publisher_ = it_.advertise("detected_markers", 1); image_subscriber_ = it_.subscribe("input_image", 0, &AlvarLoggerNode::imageCallback, this); } AlvarLoggerNode::~AlvarLoggerNode() { file_out_.close(); delete cam_; } void AlvarLoggerNode::imageCallback(const sensor_msgs::ImageConstPtr &image) { if (cam_->getCamInfo_) { if (!video_writer_.isOpened()) { cv::Size image_size(image->width, image->height); double frame_rate = 30.0; std::string video_file_name; nh_.getParam("video_file", video_file_name); video_writer_.open(video_file_name, CV_FOURCC('D','I','V','X'), frame_rate, image_size, true); } cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image, sensor_msgs::image_encodings::BGR8); IplImage ipl_image = cv_image->image; marker_detector_.Detect(&ipl_image, cam_); video_writer_.write(cv_image->image); cv::Mat debug_image; cv_image->image.copyTo(debug_image); for (size_t i = 0; i < marker_detector_.markers->size(); i++) { int id = (*(marker_detector_.markers))[i].GetId(); std::vector<alvar::PointDouble> marker_corners = (*(marker_detector_.markers))[i].marker_corners_img; for (int i = 0; i < marker_corners.size() - 1; i++) { cv::Point start_point(marker_corners.at(i).x, marker_corners.at(i).y); cv::Point end_point(marker_corners.at(i + 1).x, marker_corners.at(i + 1).y); cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0); if (i == 0) { file_out_ << id << ", " << frame_number_ << ", " << start_point.x << ", " << start_point.y; } else { file_out_ << ", " << start_point.x << ", " << start_point.y; } } cv::Point start_point(marker_corners.at(marker_corners.size() - 1).x, marker_corners.at(marker_corners.size() - 1).y); cv::Point end_point(marker_corners.at(0).x, marker_corners.at(0).y); cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0); file_out_ << ", " << start_point.x << ", " << start_point.y << std::endl; } cv_bridge::CvImage debug_image_msg; debug_image_msg.encoding = sensor_msgs::image_encodings::BGR8; debug_image_msg.image = debug_image; image_publisher_.publish(debug_image_msg.toImageMsg()); } frame_number_++; } int main(int argc, char **argv) { ros::init(argc, argv, "alvar_logger"); ros::NodeHandle n("~"); ROS_INFO("[alvar_logger] node started"); AlvarLoggerNode alvar_logger_node(n); ros::spin(); return 0; } <commit_msg>log frame id first then marker id<commit_after>#include <alvar_logger/alvar_logger_node.h> #include <sensor_msgs/image_encodings.h> #include <cv_bridge/cv_bridge.h> AlvarLoggerNode::AlvarLoggerNode(ros::NodeHandle &nh) : nh_(nh), it_(nh), frame_number_(0) { std::string camera_info_topic; if (!nh_.getParam("camera_info_topic", camera_info_topic)) { ROS_ERROR("Camera info topic needs to be specified"); exit(0); } cam_ = new alvar::Camera(nh_, camera_info_topic); std::string log_file_name; if (!nh_.getParam("log_file", log_file_name)) { ROS_ERROR("Log file needs to be specified"); exit(0); } if (!nh_.hasParam("video_file")) { ROS_ERROR("Video file needs to be specified"); exit(0); } file_out_.open(log_file_name.c_str()); image_publisher_ = it_.advertise("detected_markers", 1); image_subscriber_ = it_.subscribe("input_image", 0, &AlvarLoggerNode::imageCallback, this); } AlvarLoggerNode::~AlvarLoggerNode() { file_out_.close(); delete cam_; } void AlvarLoggerNode::imageCallback(const sensor_msgs::ImageConstPtr &image) { if (cam_->getCamInfo_) { if (!video_writer_.isOpened()) { cv::Size image_size(image->width, image->height); double frame_rate = 30.0; std::string video_file_name; nh_.getParam("video_file", video_file_name); video_writer_.open(video_file_name, CV_FOURCC('D','I','V','X'), frame_rate, image_size, true); } cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image, sensor_msgs::image_encodings::BGR8); IplImage ipl_image = cv_image->image; marker_detector_.Detect(&ipl_image, cam_); video_writer_.write(cv_image->image); cv::Mat debug_image; cv_image->image.copyTo(debug_image); for (size_t i = 0; i < marker_detector_.markers->size(); i++) { int id = (*(marker_detector_.markers))[i].GetId(); std::vector<alvar::PointDouble> marker_corners = (*(marker_detector_.markers))[i].marker_corners_img; for (int i = 0; i < marker_corners.size() - 1; i++) { cv::Point start_point(marker_corners.at(i).x, marker_corners.at(i).y); cv::Point end_point(marker_corners.at(i + 1).x, marker_corners.at(i + 1).y); cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0); if (i == 0) { file_out_ << frame_number_ << ", " << id << ", " << start_point.x << ", " << start_point.y; } else { file_out_ << ", " << start_point.x << ", " << start_point.y; } } cv::Point start_point(marker_corners.at(marker_corners.size() - 1).x, marker_corners.at(marker_corners.size() - 1).y); cv::Point end_point(marker_corners.at(0).x, marker_corners.at(0).y); cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0); file_out_ << ", " << start_point.x << ", " << start_point.y << std::endl; } cv_bridge::CvImage debug_image_msg; debug_image_msg.encoding = sensor_msgs::image_encodings::BGR8; debug_image_msg.image = debug_image; image_publisher_.publish(debug_image_msg.toImageMsg()); } frame_number_++; } int main(int argc, char **argv) { ros::init(argc, argv, "alvar_logger"); ros::NodeHandle n("~"); ROS_INFO("[alvar_logger] node started"); AlvarLoggerNode alvar_logger_node(n); ros::spin(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkInstantiator.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkInstantiator.h" #include "vtkObjectFactory.h" #include "vtkDebugLeaks.h" vtkCxxRevisionMacro(vtkInstantiator, "1.4"); vtkStandardNewMacro(vtkInstantiator); // Node in hash table. class vtkInstantiatorHashNode { public: typedef vtkInstantiator::CreateFunction CreateFunction; vtkInstantiatorHashNode() { this->ClassName = 0; this->Function = 0; } void SetClassName(const char* className) { this->ClassName = className; } const char* GetClassName() { return this->ClassName; } void SetFunction(CreateFunction function) { this->Function = function; } CreateFunction GetFunction() { return this->Function; } private: const char* ClassName; CreateFunction Function; }; // Hash table used by vtkInstantiator. class vtkInstantiatorHashTable : public vtkObject { public: vtkTypeRevisionMacro(vtkInstantiatorHashTable,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); static vtkInstantiatorHashTable* New(); typedef vtkInstantiator::CreateFunction CreateFunction; void Insert(const char* className, CreateFunction function); void Erase(const char* className, CreateFunction function); CreateFunction Find(const char* className); protected: vtkInstantiatorHashTable(); ~vtkInstantiatorHashTable(); unsigned long Hash(const char* s); void ExtendBucket(unsigned long bucket); const char* AddClassName(const char* className); vtkInstantiatorHashNode** Buckets; unsigned int* BucketCounts; unsigned int* BucketSizes; unsigned long NumberOfBuckets; char** ClassNames; unsigned long NumberOfClassNames; unsigned long ClassNamesSize; private: vtkInstantiatorHashTable(const vtkInstantiatorHashTable&); // Not implemented. void operator=(const vtkInstantiatorHashTable&); // Not implemented. }; vtkCxxRevisionMacro(vtkInstantiatorHashTable, "1.4"); //---------------------------------------------------------------------------- vtkInstantiatorHashTable* vtkInstantiatorHashTable::New() { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::ConstructClass("vtkInstantiatorHashTable"); #endif // Don't use the object factory because it may not have been // initialized when this table is allocated. return new vtkInstantiatorHashTable; } //---------------------------------------------------------------------------- vtkInstantiatorHashTable::vtkInstantiatorHashTable() { this->NumberOfBuckets = 101; this->Buckets = new vtkInstantiatorHashNode*[this->NumberOfBuckets]; this->BucketCounts = new unsigned int[this->NumberOfBuckets]; this->BucketSizes = new unsigned int[this->NumberOfBuckets]; unsigned int i; for(i=0;i < this->NumberOfBuckets;++i) { this->BucketCounts[i] = 0; this->BucketSizes[i] = 16; this->Buckets[i] = new vtkInstantiatorHashNode[this->BucketSizes[i]]; } this->NumberOfClassNames = 0; this->ClassNamesSize = 256; this->ClassNames = new char*[this->ClassNamesSize]; } //---------------------------------------------------------------------------- vtkInstantiatorHashTable::~vtkInstantiatorHashTable() { unsigned long i; for(i=0; i < this->NumberOfBuckets;++i) { delete [] this->Buckets[i]; } delete [] this->BucketSizes; delete [] this->BucketCounts; delete [] this->Buckets; for(i=0;i < this->NumberOfClassNames;++i) { delete [] this->ClassNames[i]; } delete [] this->ClassNames; } //---------------------------------------------------------------------------- void vtkInstantiatorHashTable::PrintSelf(ostream& os, vtkIndent indent) { this->vtkObject::PrintSelf(os, indent); os << indent << "NumberOfBuckets: " << this->NumberOfBuckets << "\n"; unsigned int i; float avgBucketSize = 0; unsigned int maxBucketSize = 0; unsigned int minBucketSize = this->NumberOfClassNames; for(i=0;i < this->NumberOfBuckets;++i) { avgBucketSize += this->BucketCounts[i]; if(this->BucketCounts[i] > maxBucketSize) { maxBucketSize = this->BucketCounts[i]; } if(this->BucketCounts[i] < minBucketSize) { minBucketSize = this->BucketCounts[i]; } } avgBucketSize /= float(this->NumberOfBuckets); os << indent << "Average Bucket Size: " << avgBucketSize << "\n"; os << indent << "Minimum Bucket Size: " << minBucketSize << "\n"; os << indent << "Maximum Bucket Size: " << maxBucketSize << "\n"; } //---------------------------------------------------------------------------- void vtkInstantiatorHashTable::Insert(const char* className, CreateFunction function) { unsigned long bucket = this->Hash(className); if(this->BucketCounts[bucket] == this->BucketSizes[bucket]) { this->ExtendBucket(bucket); } // Do not check if the class is already registered. It is possible // that more than one create function will be registered for the // same class, and even that the same function is registered more // than once. Each register should have a corresponding unregister. // As long as any register has not had its corresponding unregister, // we want to allow the class to be created. unsigned int pos = this->BucketCounts[bucket]++; this->Buckets[bucket][pos].SetClassName(this->AddClassName(className)); this->Buckets[bucket][pos].SetFunction(function); } //---------------------------------------------------------------------------- void vtkInstantiatorHashTable::Erase(const char* className, CreateFunction function) { unsigned long bucket = this->Hash(className); // Find the exact registration function we have been given, and // remove it only once. If more than one funcion has been // registered for this class, or the same function more than once, // each register should have its corresponding unregister. unsigned int i; for(i=0; i < this->BucketCounts[bucket];++i) { if(((this->Buckets[bucket][i].GetFunction() == function) && (strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0))) { unsigned int j; --this->BucketCounts[bucket]; for(j=i;j < this->BucketCounts[bucket];++j) { this->Buckets[bucket][j] = this->Buckets[bucket][j+1]; } return; } } } //---------------------------------------------------------------------------- vtkInstantiatorHashTable::CreateFunction vtkInstantiatorHashTable::Find(const char* className) { unsigned long bucket = this->Hash(className); unsigned int i; for(i=0; i < this->BucketCounts[bucket];++i) { if(strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0) { return this->Buckets[bucket][i].GetFunction(); } } return 0; } //---------------------------------------------------------------------------- unsigned long vtkInstantiatorHashTable::Hash(const char* s) { unsigned long h = 0; for(;*s;++s) { h = 5*h + *s; } return h % this->NumberOfBuckets; } //---------------------------------------------------------------------------- void vtkInstantiatorHashTable::ExtendBucket(unsigned long bucket) { unsigned int newSize = this->BucketSizes[bucket] * 2; vtkInstantiatorHashNode* newBucket = new vtkInstantiatorHashNode[newSize]; unsigned int i; for(i=0; i < this->BucketCounts[bucket];++i) { newBucket[i] = this->Buckets[bucket][i]; } delete [] this->Buckets[bucket]; this->Buckets[bucket] = newBucket; this->BucketSizes[bucket] = newSize; } //---------------------------------------------------------------------------- const char* vtkInstantiatorHashTable::AddClassName(const char* className) { if(this->NumberOfClassNames == this->ClassNamesSize) { unsigned long newSize = this->ClassNamesSize * 2; char** newNames = new char*[newSize]; unsigned long i; for(i=0;i < this->NumberOfClassNames;++i) { newNames[i] = this->ClassNames[i]; } delete [] this->ClassNames; this->ClassNames = newNames; this->ClassNamesSize = newSize; } char* newName = new char[strlen(className)+1]; strcpy(newName, className); this->ClassNames[this->NumberOfClassNames++] = newName; return newName; } //---------------------------------------------------------------------------- // Implementation of actual vtkInstantiator class. //---------------------------------------------------------------------------- vtkInstantiator::vtkInstantiator() { } //---------------------------------------------------------------------------- vtkInstantiator::~vtkInstantiator() { } //---------------------------------------------------------------------------- void vtkInstantiator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); vtkInstantiator::CreatorTable->PrintSelf(os, indent); } //---------------------------------------------------------------------------- vtkObject* vtkInstantiator::CreateInstance(const char* className) { CreateFunction function = vtkInstantiator::CreatorTable->Find(className); if(function) { return function(); } return 0; } //---------------------------------------------------------------------------- void vtkInstantiator::RegisterInstantiator(const char* className, CreateFunction createFunction) { vtkInstantiator::CreatorTable->Insert(className, createFunction); } //---------------------------------------------------------------------------- void vtkInstantiator::UnRegisterInstantiator(const char* className, CreateFunction createFunction) { vtkInstantiator::CreatorTable->Erase(className, createFunction); } //---------------------------------------------------------------------------- void vtkInstantiator::ClassInitialize() { vtkInstantiator::CreatorTable = vtkInstantiatorHashTable::New(); } //---------------------------------------------------------------------------- void vtkInstantiator::ClassFinalize() { vtkInstantiator::CreatorTable->Delete(); } //---------------------------------------------------------------------------- vtkInstantiatorInitialize::vtkInstantiatorInitialize() { if(++vtkInstantiatorInitialize::Count == 1) { vtkInstantiator::ClassInitialize(); } } //---------------------------------------------------------------------------- vtkInstantiatorInitialize::~vtkInstantiatorInitialize() { if(--vtkInstantiatorInitialize::Count == 0) { vtkInstantiator::ClassFinalize(); } } //---------------------------------------------------------------------------- unsigned int vtkInstantiatorInitialize::Count; vtkInstantiatorHashTable* vtkInstantiator::CreatorTable; <commit_msg>BUG: vtkInstantiatorHashTable must not be a subclass of vtkObject because vtkObject's constructor touches vtkTimeStamp's global, which may not yet be initialized by the time vtkInstantiatorHashTable is constructed (on certain platforms).<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkInstantiator.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkInstantiator.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkInstantiator, "1.5"); vtkStandardNewMacro(vtkInstantiator); // Node in hash table. class vtkInstantiatorHashNode { public: typedef vtkInstantiator::CreateFunction CreateFunction; vtkInstantiatorHashNode() { this->ClassName = 0; this->Function = 0; } void SetClassName(const char* className) { this->ClassName = className; } const char* GetClassName() { return this->ClassName; } void SetFunction(CreateFunction function) { this->Function = function; } CreateFunction GetFunction() { return this->Function; } private: const char* ClassName; CreateFunction Function; }; // Hash table used by vtkInstantiator. Must not be a vtkObject. class vtkInstantiatorHashTable { public: vtkInstantiatorHashTable(); ~vtkInstantiatorHashTable(); void PrintSelf(ostream& os, vtkIndent indent); typedef vtkInstantiator::CreateFunction CreateFunction; void Insert(const char* className, CreateFunction function); void Erase(const char* className, CreateFunction function); CreateFunction Find(const char* className); protected: unsigned long Hash(const char* s); void ExtendBucket(unsigned long bucket); const char* AddClassName(const char* className); vtkInstantiatorHashNode** Buckets; unsigned int* BucketCounts; unsigned int* BucketSizes; unsigned long NumberOfBuckets; char** ClassNames; unsigned long NumberOfClassNames; unsigned long ClassNamesSize; private: vtkInstantiatorHashTable(const vtkInstantiatorHashTable&); // Not implemented. void operator=(const vtkInstantiatorHashTable&); // Not implemented. }; //---------------------------------------------------------------------------- vtkInstantiatorHashTable::vtkInstantiatorHashTable() { this->NumberOfBuckets = 101; this->Buckets = new vtkInstantiatorHashNode*[this->NumberOfBuckets]; this->BucketCounts = new unsigned int[this->NumberOfBuckets]; this->BucketSizes = new unsigned int[this->NumberOfBuckets]; unsigned int i; for(i=0;i < this->NumberOfBuckets;++i) { this->BucketCounts[i] = 0; this->BucketSizes[i] = 16; this->Buckets[i] = new vtkInstantiatorHashNode[this->BucketSizes[i]]; } this->NumberOfClassNames = 0; this->ClassNamesSize = 256; this->ClassNames = new char*[this->ClassNamesSize]; } //---------------------------------------------------------------------------- vtkInstantiatorHashTable::~vtkInstantiatorHashTable() { unsigned long i; for(i=0; i < this->NumberOfBuckets;++i) { delete [] this->Buckets[i]; } delete [] this->BucketSizes; delete [] this->BucketCounts; delete [] this->Buckets; for(i=0;i < this->NumberOfClassNames;++i) { delete [] this->ClassNames[i]; } delete [] this->ClassNames; } //---------------------------------------------------------------------------- void vtkInstantiatorHashTable::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "NumberOfBuckets: " << this->NumberOfBuckets << "\n"; unsigned int i; float avgBucketSize = 0; unsigned int maxBucketSize = 0; unsigned int minBucketSize = this->NumberOfClassNames; for(i=0;i < this->NumberOfBuckets;++i) { avgBucketSize += this->BucketCounts[i]; if(this->BucketCounts[i] > maxBucketSize) { maxBucketSize = this->BucketCounts[i]; } if(this->BucketCounts[i] < minBucketSize) { minBucketSize = this->BucketCounts[i]; } } avgBucketSize /= float(this->NumberOfBuckets); os << indent << "Average Bucket Size: " << avgBucketSize << "\n"; os << indent << "Minimum Bucket Size: " << minBucketSize << "\n"; os << indent << "Maximum Bucket Size: " << maxBucketSize << "\n"; } //---------------------------------------------------------------------------- void vtkInstantiatorHashTable::Insert(const char* className, CreateFunction function) { unsigned long bucket = this->Hash(className); if(this->BucketCounts[bucket] == this->BucketSizes[bucket]) { this->ExtendBucket(bucket); } // Do not check if the class is already registered. It is possible // that more than one create function will be registered for the // same class, and even that the same function is registered more // than once. Each register should have a corresponding unregister. // As long as any register has not had its corresponding unregister, // we want to allow the class to be created. unsigned int pos = this->BucketCounts[bucket]++; this->Buckets[bucket][pos].SetClassName(this->AddClassName(className)); this->Buckets[bucket][pos].SetFunction(function); } //---------------------------------------------------------------------------- void vtkInstantiatorHashTable::Erase(const char* className, CreateFunction function) { unsigned long bucket = this->Hash(className); // Find the exact registration function we have been given, and // remove it only once. If more than one funcion has been // registered for this class, or the same function more than once, // each register should have its corresponding unregister. unsigned int i; for(i=0; i < this->BucketCounts[bucket];++i) { if(((this->Buckets[bucket][i].GetFunction() == function) && (strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0))) { unsigned int j; --this->BucketCounts[bucket]; for(j=i;j < this->BucketCounts[bucket];++j) { this->Buckets[bucket][j] = this->Buckets[bucket][j+1]; } return; } } } //---------------------------------------------------------------------------- vtkInstantiatorHashTable::CreateFunction vtkInstantiatorHashTable::Find(const char* className) { unsigned long bucket = this->Hash(className); unsigned int i; for(i=0; i < this->BucketCounts[bucket];++i) { if(strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0) { return this->Buckets[bucket][i].GetFunction(); } } return 0; } //---------------------------------------------------------------------------- unsigned long vtkInstantiatorHashTable::Hash(const char* s) { unsigned long h = 0; for(;*s;++s) { h = 5*h + *s; } return h % this->NumberOfBuckets; } //---------------------------------------------------------------------------- void vtkInstantiatorHashTable::ExtendBucket(unsigned long bucket) { unsigned int newSize = this->BucketSizes[bucket] * 2; vtkInstantiatorHashNode* newBucket = new vtkInstantiatorHashNode[newSize]; unsigned int i; for(i=0; i < this->BucketCounts[bucket];++i) { newBucket[i] = this->Buckets[bucket][i]; } delete [] this->Buckets[bucket]; this->Buckets[bucket] = newBucket; this->BucketSizes[bucket] = newSize; } //---------------------------------------------------------------------------- const char* vtkInstantiatorHashTable::AddClassName(const char* className) { if(this->NumberOfClassNames == this->ClassNamesSize) { unsigned long newSize = this->ClassNamesSize * 2; char** newNames = new char*[newSize]; unsigned long i; for(i=0;i < this->NumberOfClassNames;++i) { newNames[i] = this->ClassNames[i]; } delete [] this->ClassNames; this->ClassNames = newNames; this->ClassNamesSize = newSize; } char* newName = new char[strlen(className)+1]; strcpy(newName, className); this->ClassNames[this->NumberOfClassNames++] = newName; return newName; } //---------------------------------------------------------------------------- // Implementation of actual vtkInstantiator class. //---------------------------------------------------------------------------- vtkInstantiator::vtkInstantiator() { } //---------------------------------------------------------------------------- vtkInstantiator::~vtkInstantiator() { } //---------------------------------------------------------------------------- void vtkInstantiator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); vtkInstantiator::CreatorTable->PrintSelf(os, indent); } //---------------------------------------------------------------------------- vtkObject* vtkInstantiator::CreateInstance(const char* className) { CreateFunction function = vtkInstantiator::CreatorTable->Find(className); if(function) { return function(); } return 0; } //---------------------------------------------------------------------------- void vtkInstantiator::RegisterInstantiator(const char* className, CreateFunction createFunction) { vtkInstantiator::CreatorTable->Insert(className, createFunction); } //---------------------------------------------------------------------------- void vtkInstantiator::UnRegisterInstantiator(const char* className, CreateFunction createFunction) { vtkInstantiator::CreatorTable->Erase(className, createFunction); } //---------------------------------------------------------------------------- void vtkInstantiator::ClassInitialize() { vtkInstantiator::CreatorTable = new vtkInstantiatorHashTable; } //---------------------------------------------------------------------------- void vtkInstantiator::ClassFinalize() { delete vtkInstantiator::CreatorTable; } //---------------------------------------------------------------------------- vtkInstantiatorInitialize::vtkInstantiatorInitialize() { if(++vtkInstantiatorInitialize::Count == 1) { vtkInstantiator::ClassInitialize(); } } //---------------------------------------------------------------------------- vtkInstantiatorInitialize::~vtkInstantiatorInitialize() { if(--vtkInstantiatorInitialize::Count == 0) { vtkInstantiator::ClassFinalize(); } } //---------------------------------------------------------------------------- unsigned int vtkInstantiatorInitialize::Count; vtkInstantiatorHashTable* vtkInstantiator::CreatorTable; <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: global.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-11-02 13:09:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef GLOBAL_HXX_INCLUDED #define GLOBAL_HXX_INCLUDED #if defined _MSC_VER #pragma warning(push, 1) #endif #ifndef OS2 #include <windows.h> #endif #if defined _MSC_VER #pragma warning(pop) #endif #ifndef DBGMACROS_HXX_INCLUDED #include "internal/dbgmacros.hxx" #endif extern long g_DllRefCnt; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.40); FILE MERGED 2008/04/01 12:41:07 thb 1.5.40.2: #i85898# Stripping all external header guards 2008/03/31 13:17:04 rt 1.5.40.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: global.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef GLOBAL_HXX_INCLUDED #define GLOBAL_HXX_INCLUDED #if defined _MSC_VER #pragma warning(push, 1) #endif #ifndef OS2 #include <windows.h> #endif #if defined _MSC_VER #pragma warning(pop) #endif #include "internal/dbgmacros.hxx" extern long g_DllRefCnt; #endif <|endoftext|>
<commit_before>/** * @file dt_main.cpp * @ Parikshit Ram (pram@cc.gatech.edu) * * This file provides an example use of the DET */ #include <mlpack/core.hpp> #include "dt_utils.hpp" using namespace mlpack; using namespace mlpack::det; using namespace std; PROGRAM_INFO("Density estimation with DET", "This program " "provides an example use of the Density Estimation " "Tree for density estimation. For more details, " "please look at the paper titled " "'Density Estimation Trees'."); // input data files PARAM_STRING_REQ("input/training_set", "The data set on which to " "perform density estimation.", "S"); PARAM_STRING("input/test_set", "An extra set of test points on " "which to estimate the density given the estimator.", "T", ""); PARAM_STRING("input/labels", "The labels for the given training data to " "generate the class membership of each leaf (as an " "extra statistic)", "L", ""); // output data files PARAM_STRING("output/unpruned_tree_estimates", "The file " "in which to output the estimates on the " "training set from the large unpruned tree.", "u", ""); PARAM_STRING("output/training_set_estimates", "The file " "in which to output the estimates on the " "training set from the final optimally pruned" " tree.", "s", ""); PARAM_STRING("output/test_set_estimates", "The file " "in which to output the estimates on the " "test set from the final optimally pruned" " tree.", "t", ""); PARAM_STRING("output/leaf_class_table", "The file " "in which to output the leaf class membership " "table.", "l", "leaf_class_membership.txt"); PARAM_STRING("output/tree", "The file in which to print " "the final optimally pruned tree.", "p", ""); PARAM_STRING("output/vi", "The file to output the " "variable importance values for each feature.", "i", ""); // parameters for the algorithm PARAM_INT("param/number_of_classes", "The number of classes present " "in the 'labels' set provided", "C", 0); PARAM_INT("param/folds", "The number of folds of cross-validation" " to performed for the estimation (enter 0 for LOOCV)", "F", 10); PARAM_INT("DET/min_leaf_size", "The minimum size of a leaf" " in the unpruned fully grown DET.", "N", 5); PARAM_INT("DET/max_leaf_size", "The maximum size of a leaf" " in the unpruned fully grown DET.", "M", 10); PARAM_FLAG("DET/use_volume_reg", "This flag gives the used the " "option to use a form of regularization similar to " "the usual alpha-pruning in decision tree. But " "instead of regularizing on the number of leaves, " "you regularize on the sum of the inverse of the volume " "of the leaves (meaning you penalize " "low volume leaves.", "R"); // some flags for output of some information about the tree PARAM_FLAG("flag/print_tree", "If you just wish to print the tree " "out on the command line.", "P"); PARAM_FLAG("flag/print_vi", "If you just wish to print the " "variable importance of each feature " "out on the command line.", "I"); int main(int argc, char *argv[]) { CLI::ParseCommandLine(argc, argv); string train_set_file = CLI::GetParam<string>("S"); arma::Mat<float> training_data; Log::Info << "Loading training set..." << endl; if (!data::Load(train_set_file, training_data)) Log::Fatal << "Training set file "<< train_set_file << " can't be loaded." << endl; Log::Info << "Training set (" << training_data.n_rows << ", " << training_data.n_cols << ")" << endl; // cross-validation here size_t folds = CLI::GetParam<int>("F"); if (folds == 0) { folds = training_data.n_cols; Log::Info << "Starting Leave-One-Out Cross validation" << endl; } else Log::Info << "Starting " << folds << "-fold Cross validation" << endl; // obtaining the optimal tree string unpruned_tree_estimate_file = CLI::GetParam<string>("u"); Timer::Start("DET/Training"); DTree<float> *dtree_opt = Trainer<float> (&training_data, folds, CLI::HasParam("R"), CLI::GetParam<int>("M"), CLI::GetParam<int>("N"), unpruned_tree_estimate_file); Timer::Stop("DET/Training"); // computing densities for the train points in the // optimal tree FILE *fp = NULL; if (CLI::GetParam<string>("s") != "") { string optimal_estimates_file = CLI::GetParam<string>("s"); fp = fopen(optimal_estimates_file.c_str(), "w"); } // Computation timing is more accurate when you do not // perform the printing. Timer::Start("DET/EstimationTime"); for (size_t i = 0; i < training_data.n_cols; i++) { arma::Col<float> test_p = training_data.unsafe_col(i); long double f = dtree_opt->ComputeValue(&test_p); if (fp != NULL) fprintf(fp, "%Lg\n", f); } // end for Timer::Stop("DET/EstimationTime"); if (fp != NULL) fclose(fp); // computing the density at the provided test points // and outputting the density in the given file. if (CLI::GetParam<string>("T") != "") { string test_file = CLI::GetParam<string>("T"); arma::Mat<float> test_data; Log::Info << "Loading test set..." << endl; if (!data::Load(test_file, test_data)) Log::Fatal << "Test set file "<< test_file << " can't be loaded." << endl; Log::Info << "Test set (" << test_data.n_rows << ", " << test_data.n_cols << ")" << endl; fp = NULL; if (CLI::GetParam<string>("t") != "") { string test_density_file = CLI::GetParam<string>("t"); fp = fopen(test_density_file.c_str(), "w"); } Timer::Start("DET/TestSetEstimation"); for (size_t i = 0; i < test_data.n_cols; i++) { arma::Col<float> test_p = test_data.unsafe_col(i); long double f = dtree_opt->ComputeValue(&test_p); if (fp != NULL) fprintf(fp, "%Lg\n", f); } // end for Timer::Stop("DET/TestSetEstimation"); if (fp != NULL) fclose(fp); } // Test set estimation // printing the final tree if (CLI::HasParam("P")) { fp = NULL; if (CLI::GetParam<string>("p") != "") { string print_tree_file = CLI::GetParam<string>("p"); fp = fopen(print_tree_file.c_str(), "w"); if (fp != NULL) { dtree_opt->WriteTree(0, fp); fclose(fp); } } else { dtree_opt->WriteTree(0, stdout); printf("\n"); } } // Printing the tree // print the leaf memberships for the optimal tree if (CLI::GetParam<string>("L") != "") { std::string labels_file = CLI::GetParam<string>("L"); arma::Mat<int> labels; Log::Info << "Loading label file..." << endl; if (!data::Load(labels_file, labels)) Log::Fatal << "Label file "<< labels_file << " can't be loaded." << endl; Log::Info << "Labels (" << labels.n_rows << ", " << labels.n_cols << ")" << endl; size_t num_classes = CLI::GetParam<int>("C"); if (num_classes == 0) Log::Fatal << "Please provide the number of classes" << " present in the label file" << endl; assert(training_data.n_cols == labels.n_cols); assert(labels.n_rows == 1); PrintLeafMembership<float> (dtree_opt, training_data, labels, num_classes, (string) CLI::GetParam<string>("l")); } // leaf class membership if(CLI::HasParam("I")) { PrintVariableImportance<float> (dtree_opt, training_data.n_rows, (string) CLI::GetParam<string>("i")); } // print variable importance delete dtree_opt; return 0; } // end main <commit_msg>Switch to doubles not floats in main executable so it compiles.<commit_after>/** * @file dt_main.cpp * @ Parikshit Ram (pram@cc.gatech.edu) * * This file provides an example use of the DET */ #include <mlpack/core.hpp> #include "dt_utils.hpp" using namespace mlpack; using namespace mlpack::det; using namespace std; PROGRAM_INFO("Density estimation with DET", "This program provides an example " "use of the Density Estimation " "Tree for density estimation. For more details, " "please look at the paper titled " "'Density Estimation Trees'."); // input data files PARAM_STRING_REQ("input/training_set", "The data set on which to " "perform density estimation.", "S"); PARAM_STRING("input/test_set", "An extra set of test points on " "which to estimate the density given the estimator.", "T", ""); PARAM_STRING("input/labels", "The labels for the given training data to " "generate the class membership of each leaf (as an " "extra statistic)", "L", ""); // output data files PARAM_STRING("output/unpruned_tree_estimates", "The file " "in which to output the estimates on the " "training set from the large unpruned tree.", "u", ""); PARAM_STRING("output/training_set_estimates", "The file " "in which to output the estimates on the " "training set from the final optimally pruned" " tree.", "s", ""); PARAM_STRING("output/test_set_estimates", "The file " "in which to output the estimates on the " "test set from the final optimally pruned" " tree.", "t", ""); PARAM_STRING("output/leaf_class_table", "The file " "in which to output the leaf class membership " "table.", "l", "leaf_class_membership.txt"); PARAM_STRING("output/tree", "The file in which to print " "the final optimally pruned tree.", "p", ""); PARAM_STRING("output/vi", "The file to output the " "variable importance values for each feature.", "i", ""); // parameters for the algorithm PARAM_INT("param/number_of_classes", "The number of classes present " "in the 'labels' set provided", "C", 0); PARAM_INT("param/folds", "The number of folds of cross-validation" " to performed for the estimation (enter 0 for LOOCV)", "F", 10); PARAM_INT("DET/min_leaf_size", "The minimum size of a leaf" " in the unpruned fully grown DET.", "N", 5); PARAM_INT("DET/max_leaf_size", "The maximum size of a leaf" " in the unpruned fully grown DET.", "M", 10); PARAM_FLAG("DET/use_volume_reg", "This flag gives the used the " "option to use a form of regularization similar to " "the usual alpha-pruning in decision tree. But " "instead of regularizing on the number of leaves, " "you regularize on the sum of the inverse of the volume " "of the leaves (meaning you penalize " "low volume leaves.", "R"); // some flags for output of some information about the tree PARAM_FLAG("flag/print_tree", "If you just wish to print the tree " "out on the command line.", "P"); PARAM_FLAG("flag/print_vi", "If you just wish to print the " "variable importance of each feature " "out on the command line.", "I"); int main(int argc, char *argv[]) { CLI::ParseCommandLine(argc, argv); string train_set_file = CLI::GetParam<string>("S"); arma::Mat<double> training_data; Log::Info << "Loading training set..." << endl; if (!data::Load(train_set_file, training_data)) Log::Fatal << "Training set file "<< train_set_file << " can't be loaded." << endl; Log::Info << "Training set (" << training_data.n_rows << ", " << training_data.n_cols << ")" << endl; // cross-validation here size_t folds = CLI::GetParam<int>("F"); if (folds == 0) { folds = training_data.n_cols; Log::Info << "Starting Leave-One-Out Cross validation" << endl; } else Log::Info << "Starting " << folds << "-fold Cross validation" << endl; // obtaining the optimal tree string unpruned_tree_estimate_file = CLI::GetParam<string>("u"); Timer::Start("DET/Training"); DTree<double> *dtree_opt = Trainer<double> (&training_data, folds, CLI::HasParam("R"), CLI::GetParam<int>("M"), CLI::GetParam<int>("N"), unpruned_tree_estimate_file); Timer::Stop("DET/Training"); // computing densities for the train points in the // optimal tree FILE *fp = NULL; if (CLI::GetParam<string>("s") != "") { string optimal_estimates_file = CLI::GetParam<string>("s"); fp = fopen(optimal_estimates_file.c_str(), "w"); } // Computation timing is more accurate when you do not // perform the printing. Timer::Start("DET/EstimationTime"); for (size_t i = 0; i < training_data.n_cols; i++) { arma::Col<double> test_p = training_data.unsafe_col(i); long double f = dtree_opt->ComputeValue(&test_p); if (fp != NULL) fprintf(fp, "%Lg\n", f); } // end for Timer::Stop("DET/EstimationTime"); if (fp != NULL) fclose(fp); // computing the density at the provided test points // and outputting the density in the given file. if (CLI::GetParam<string>("T") != "") { string test_file = CLI::GetParam<string>("T"); arma::Mat<double> test_data; Log::Info << "Loading test set..." << endl; if (!data::Load(test_file, test_data)) Log::Fatal << "Test set file "<< test_file << " can't be loaded." << endl; Log::Info << "Test set (" << test_data.n_rows << ", " << test_data.n_cols << ")" << endl; fp = NULL; if (CLI::GetParam<string>("t") != "") { string test_density_file = CLI::GetParam<string>("t"); fp = fopen(test_density_file.c_str(), "w"); } Timer::Start("DET/TestSetEstimation"); for (size_t i = 0; i < test_data.n_cols; i++) { arma::Col<double> test_p = test_data.unsafe_col(i); long double f = dtree_opt->ComputeValue(&test_p); if (fp != NULL) fprintf(fp, "%Lg\n", f); } // end for Timer::Stop("DET/TestSetEstimation"); if (fp != NULL) fclose(fp); } // Test set estimation // printing the final tree if (CLI::HasParam("P")) { fp = NULL; if (CLI::GetParam<string>("p") != "") { string print_tree_file = CLI::GetParam<string>("p"); fp = fopen(print_tree_file.c_str(), "w"); if (fp != NULL) { dtree_opt->WriteTree(0, fp); fclose(fp); } } else { dtree_opt->WriteTree(0, stdout); printf("\n"); } } // Printing the tree // print the leaf memberships for the optimal tree if (CLI::GetParam<string>("L") != "") { std::string labels_file = CLI::GetParam<string>("L"); arma::Mat<int> labels; Log::Info << "Loading label file..." << endl; if (!data::Load(labels_file, labels)) Log::Fatal << "Label file "<< labels_file << " can't be loaded." << endl; Log::Info << "Labels (" << labels.n_rows << ", " << labels.n_cols << ")" << endl; size_t num_classes = CLI::GetParam<int>("C"); if (num_classes == 0) Log::Fatal << "Please provide the number of classes" << " present in the label file" << endl; assert(training_data.n_cols == labels.n_cols); assert(labels.n_rows == 1); PrintLeafMembership<double> (dtree_opt, training_data, labels, num_classes, (string) CLI::GetParam<string>("l")); } // leaf class membership if(CLI::HasParam("I")) { PrintVariableImportance<double> (dtree_opt, training_data.n_rows, (string) CLI::GetParam<string>("i")); } // print variable importance delete dtree_opt; return 0; } // end main <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX24T/RX66T グループ・CMPC 定義 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016, 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/device.hpp" /// CMPC モジュールが無いデバイスでエラーとする #if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) # error "cmpc.hpp: This module does not exist" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンパレータ C(CMPC) @param[in] base ベース・アドレス @param[in] per ペリフェラル型 @param[in] ivec 割り込みベクタ型 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per, ICU::VECTOR ivec> struct cmpc_t { static const auto PERIPHERAL = per; ///< ペリフェラル型 static const auto IVEC = ivec; ///< 割り込みベクター //-----------------------------------------------------------------// /*! @brief コンパレータ制御レジスタ(CMPCTL) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct cmpctl_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bit_rw_t <io_, bitpos::B0> CINV; bit_rw_t <io_, bitpos::B1> COE; bits_rw_t<io_, bitpos::B3, 2> CEG; bits_rw_t<io_, bitpos::B5, 2> CDFS; bit_rw_t <io_, bitpos::B7> HCMPON; }; static cmpctl_t<base + 0x00> CMPCTL; //-----------------------------------------------------------------// /*! @brief コンパレータ入力切り替えレジスタ(CMPSEL0) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct cmpsel0_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 4> CMPSEL; }; static cmpsel0_t<base + 0x04> CMPSEL0; //-----------------------------------------------------------------// /*! @brief コンパレータ入力切り替えレジスタ(CMPSEL1) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct cmpsel1_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> CVRS; }; static cmpsel1_t<base + 0x08> CMPSEL1; //-----------------------------------------------------------------// /*! @brief コンパレータ出力モニタレジスタ(CMPMON) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct cmpmon_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bit_rw_t<io_, bitpos::B0> CMPMON0; }; static cmpmon_t<base + 0x0C> CMPMON; //-----------------------------------------------------------------// /*! @brief コンパレータ外部出力許可レジスタ(CMPIOC) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct cmpioc_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bit_rw_t<io_, bitpos::B0> CPOE; }; static cmpioc_t<base + 0x10> CMPIOC; }; #if defined(SIG_RX24T) typedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0; typedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1; typedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2; typedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3; #elif defined(SIG_RX66T) typedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0; typedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1; typedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2; typedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3; typedef cmpc_t<0x000A0D00, peripheral::CMPC4, ICU::VECTOR::CMPC4> CMPC4; typedef cmpc_t<0x000A0D20, peripheral::CMPC5, ICU::VECTOR::CMPC5> CMPC5; #endif } <commit_msg>Update: The reality of the template when it is not optimized<commit_after>#pragma once //=====================================================================// /*! @file @brief RX24T/RX66T グループ・CMPC 定義 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016, 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/device.hpp" /// CMPC モジュールが無いデバイスでエラーとする #if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) # error "cmpc.hpp: This module does not exist" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンパレータ C(CMPC) @param[in] base ベース・アドレス @param[in] per ペリフェラル型 @param[in] ivec 割り込みベクタ型 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per, ICU::VECTOR ivec> struct cmpc_t { static const auto PERIPHERAL = per; ///< ペリフェラル型 static const auto IVEC = ivec; ///< 割り込みベクター //-----------------------------------------------------------------// /*! @brief コンパレータ制御レジスタ(CMPCTL) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct cmpctl_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bit_rw_t <io_, bitpos::B0> CINV; bit_rw_t <io_, bitpos::B1> COE; bits_rw_t<io_, bitpos::B3, 2> CEG; bits_rw_t<io_, bitpos::B5, 2> CDFS; bit_rw_t <io_, bitpos::B7> HCMPON; }; typedef cmpctl_t<base + 0x00> CMPCTL_; static CMPCTL_ CMPCTL; //-----------------------------------------------------------------// /*! @brief コンパレータ入力切り替えレジスタ(CMPSEL0) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct cmpsel0_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 4> CMPSEL; }; typedef cmpsel0_t<base + 0x04> CMPSEL0_; static CMPSEL0_ CMPSEL0; //-----------------------------------------------------------------// /*! @brief コンパレータ入力切り替えレジスタ(CMPSEL1) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct cmpsel1_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> CVRS; }; typedef cmpsel1_t<base + 0x08> CMPSEL1_; static CMPSEL1_ CMPSEL1; //-----------------------------------------------------------------// /*! @brief コンパレータ出力モニタレジスタ(CMPMON) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct cmpmon_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bit_rw_t<io_, bitpos::B0> CMPMON0; }; typedef cmpmon_t<base + 0x0C> CMPMON_; static CMPMON_ CMPMON; //-----------------------------------------------------------------// /*! @brief コンパレータ外部出力許可レジスタ(CMPIOC) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct cmpioc_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bit_rw_t<io_, bitpos::B0> CPOE; }; typedef cmpioc_t<base + 0x10> CMPIOC_; static CMPIOC_ CMPIOC; }; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmpc_t<base, per, ivec>::CMPCTL_ cmpc_t<base, per, ivec>::CMPCTL; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmpc_t<base, per, ivec>::CMPSEL0_ cmpc_t<base, per, ivec>::CMPSEL0; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmpc_t<base, per, ivec>::CMPSEL1_ cmpc_t<base, per, ivec>::CMPSEL1; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmpc_t<base, per, ivec>::CMPMON_ cmpc_t<base, per, ivec>::CMPMON; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmpc_t<base, per, ivec>::CMPIOC_ cmpc_t<base, per, ivec>::CMPIOC; #if defined(SIG_RX24T) typedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0; typedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1; typedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2; typedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3; #elif defined(SIG_RX66T) typedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0; typedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1; typedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2; typedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3; typedef cmpc_t<0x000A0D00, peripheral::CMPC4, ICU::VECTOR::CMPC4> CMPC4; typedef cmpc_t<0x000A0D20, peripheral::CMPC5, ICU::VECTOR::CMPC5> CMPC5; #endif } <|endoftext|>
<commit_before>#include "shadow/util/boxes.hpp" #include "shadow/util/log.hpp" namespace Boxes { template <typename Dtype> void Clip(const Box<Dtype> &box, Box<Dtype> *clip_box, Dtype min, Dtype max) { clip_box->xmin = std::max(std::min(box.xmin, max), min); clip_box->ymin = std::max(std::min(box.ymin, max), min); clip_box->xmax = std::max(std::min(box.xmax, max), min); clip_box->ymax = std::max(std::min(box.ymax, max), min); } template <typename Dtype> Dtype Size(const Box<Dtype> &box) { return (box.xmax - box.xmin) * (box.ymax - box.ymin); } template <typename Dtype> inline Dtype BorderOverlap(Dtype a1, Dtype a2, Dtype b1, Dtype b2) { Dtype left = a1 > b1 ? a1 : b1; Dtype right = a2 < b2 ? a2 : b2; return right - left; } template <typename Dtype> float Intersection(const Box<Dtype> &box_a, const Box<Dtype> &box_b) { Dtype width = BorderOverlap(box_a.xmin, box_a.xmax, box_b.xmin, box_b.xmax); Dtype height = BorderOverlap(box_a.ymin, box_a.ymax, box_b.ymin, box_b.ymax); if (width < 0 || height < 0) return 0; return width * height; } template <typename Dtype> float Union(const Box<Dtype> &box_a, const Box<Dtype> &box_b) { return Size(box_a) + Size(box_b) - Intersection(box_a, box_b); } template <typename Dtype> float IoU(const Box<Dtype> &box_a, const Box<Dtype> &box_b) { return Intersection(box_a, box_b) / Union(box_a, box_b); } template <typename Dtype> std::vector<Box<Dtype>> NMS(const std::vector<std::vector<Box<Dtype>>> &Bboxes, float iou_threshold) { std::vector<Box<Dtype>> all_boxes; for (const auto &boxes : Bboxes) { for (const auto &box : boxes) { if (box.label != -1) all_boxes.push_back(box); } } for (int i = 0; i < all_boxes.size(); ++i) { Box<Dtype> &box_i = all_boxes[i]; if (box_i.label == -1) continue; for (int j = i + 1; j < all_boxes.size(); ++j) { Box<Dtype> &box_j = all_boxes[j]; if (box_j.label == -1 || box_i.label != box_j.label) continue; if (IoU(box_i, box_j) > iou_threshold) { float smooth = box_i.score / (box_i.score + box_j.score); Smooth(box_j, &box_i, smooth); box_j.label = -1; continue; } float in = Intersection(box_i, box_j); float cover_i = in / Size(box_i); float cover_j = in / Size(box_j); if (cover_i > cover_j && cover_i > 0.7) box_i.label = -1; if (cover_i < cover_j && cover_j > 0.7) box_j.label = -1; } } std::vector<Box<Dtype>> out_boxes; for (const auto &box : all_boxes) { if (box.label != -1) out_boxes.push_back(box); } all_boxes.clear(); return out_boxes; } template <typename Dtype> void Smooth(const Box<Dtype> &old_box, Box<Dtype> *new_box, float smooth) { new_box->xmin = old_box.xmin + (new_box->xmin - old_box.xmin) * smooth; new_box->ymin = old_box.ymin + (new_box->ymin - old_box.ymin) * smooth; new_box->xmax = old_box.xmax + (new_box->xmax - old_box.xmax) * smooth; new_box->ymax = old_box.ymax + (new_box->ymax - old_box.ymax) * smooth; } template <typename Dtype> void Smooth(const std::vector<Box<Dtype>> &old_boxes, std::vector<Box<Dtype>> *new_boxes, float smooth) { for (auto &new_box : *new_boxes) { for (auto &old_box : old_boxes) { if (IoU(old_box, new_box) > 0.7) { Smooth(old_box, &new_box, smooth); break; } } } } template <typename Dtype> void Amend(std::vector<std::vector<Box<Dtype>>> *Bboxes, const VecRectF &crops, int height, int width) { CHECK_EQ(Bboxes->size(), crops.size()); for (int i = 0; i < crops.size(); ++i) { std::vector<Box<Dtype>> &boxes = Bboxes->at(i); const RectF &crop = crops[i]; float x_off = crop.x <= 1 ? crop.x * width : crop.x; float y_off = crop.y <= 1 ? crop.y * height : crop.y; for (auto &box : boxes) { box.xmin += x_off; box.xmax += x_off; box.ymin += y_off; box.ymax += y_off; } } } // Explicit instantiation template void Clip(const BoxI &box, BoxI *clip_box, int min, int max); template void Clip(const BoxF &box, BoxF *clip_box, float min, float max); template int Size(const BoxI &box); template float Size(const BoxF &box); template float Intersection(const BoxI &box_a, const BoxI &box_b); template float Intersection(const BoxF &box_a, const BoxF &box_b); template float Union(const BoxI &box_a, const BoxI &box_b); template float Union(const BoxF &box_a, const BoxF &box_b); template float IoU(const BoxI &box_a, const BoxI &box_b); template float IoU(const BoxF &box_a, const BoxF &box_b); template VecBoxI NMS(const std::vector<VecBoxI> &Bboxes, float iou_threshold); template VecBoxF NMS(const std::vector<VecBoxF> &Bboxes, float iou_threshold); template void Smooth(const BoxI &old_boxes, BoxI *new_boxes, float smooth); template void Smooth(const BoxF &old_boxes, BoxF *new_boxes, float smooth); template void Smooth(const VecBoxI &old_boxes, VecBoxI *new_boxes, float smooth); template void Smooth(const VecBoxF &old_boxes, VecBoxF *new_boxes, float smooth); template void Amend(std::vector<VecBoxI> *Bboxes, const VecRectF &crops, int height, int width); template void Amend(std::vector<VecBoxF> *Bboxes, const VecRectF &crops, int height, int width); } // namespace Boxes <commit_msg>fix bug: fix crop region normalize or none normalize error in amend function<commit_after>#include "shadow/util/boxes.hpp" #include "shadow/util/log.hpp" namespace Boxes { template <typename Dtype> void Clip(const Box<Dtype> &box, Box<Dtype> *clip_box, Dtype min, Dtype max) { clip_box->xmin = std::max(std::min(box.xmin, max), min); clip_box->ymin = std::max(std::min(box.ymin, max), min); clip_box->xmax = std::max(std::min(box.xmax, max), min); clip_box->ymax = std::max(std::min(box.ymax, max), min); } template <typename Dtype> Dtype Size(const Box<Dtype> &box) { return (box.xmax - box.xmin) * (box.ymax - box.ymin); } template <typename Dtype> inline Dtype BorderOverlap(Dtype a1, Dtype a2, Dtype b1, Dtype b2) { Dtype left = a1 > b1 ? a1 : b1; Dtype right = a2 < b2 ? a2 : b2; return right - left; } template <typename Dtype> float Intersection(const Box<Dtype> &box_a, const Box<Dtype> &box_b) { Dtype width = BorderOverlap(box_a.xmin, box_a.xmax, box_b.xmin, box_b.xmax); Dtype height = BorderOverlap(box_a.ymin, box_a.ymax, box_b.ymin, box_b.ymax); if (width < 0 || height < 0) return 0; return width * height; } template <typename Dtype> float Union(const Box<Dtype> &box_a, const Box<Dtype> &box_b) { return Size(box_a) + Size(box_b) - Intersection(box_a, box_b); } template <typename Dtype> float IoU(const Box<Dtype> &box_a, const Box<Dtype> &box_b) { return Intersection(box_a, box_b) / Union(box_a, box_b); } template <typename Dtype> std::vector<Box<Dtype>> NMS(const std::vector<std::vector<Box<Dtype>>> &Bboxes, float iou_threshold) { std::vector<Box<Dtype>> all_boxes; for (const auto &boxes : Bboxes) { for (const auto &box : boxes) { if (box.label != -1) all_boxes.push_back(box); } } for (int i = 0; i < all_boxes.size(); ++i) { Box<Dtype> &box_i = all_boxes[i]; if (box_i.label == -1) continue; for (int j = i + 1; j < all_boxes.size(); ++j) { Box<Dtype> &box_j = all_boxes[j]; if (box_j.label == -1 || box_i.label != box_j.label) continue; if (IoU(box_i, box_j) > iou_threshold) { float smooth = box_i.score / (box_i.score + box_j.score); Smooth(box_j, &box_i, smooth); box_j.label = -1; continue; } float in = Intersection(box_i, box_j); float cover_i = in / Size(box_i); float cover_j = in / Size(box_j); if (cover_i > cover_j && cover_i > 0.7) box_i.label = -1; if (cover_i < cover_j && cover_j > 0.7) box_j.label = -1; } } std::vector<Box<Dtype>> out_boxes; for (const auto &box : all_boxes) { if (box.label != -1) out_boxes.push_back(box); } all_boxes.clear(); return out_boxes; } template <typename Dtype> void Smooth(const Box<Dtype> &old_box, Box<Dtype> *new_box, float smooth) { new_box->xmin = old_box.xmin + (new_box->xmin - old_box.xmin) * smooth; new_box->ymin = old_box.ymin + (new_box->ymin - old_box.ymin) * smooth; new_box->xmax = old_box.xmax + (new_box->xmax - old_box.xmax) * smooth; new_box->ymax = old_box.ymax + (new_box->ymax - old_box.ymax) * smooth; } template <typename Dtype> void Smooth(const std::vector<Box<Dtype>> &old_boxes, std::vector<Box<Dtype>> *new_boxes, float smooth) { for (auto &new_box : *new_boxes) { for (auto &old_box : old_boxes) { if (IoU(old_box, new_box) > 0.7) { Smooth(old_box, &new_box, smooth); break; } } } } template <typename Dtype> void Amend(std::vector<std::vector<Box<Dtype>>> *Bboxes, const VecRectF &crops, int height, int width) { CHECK_EQ(Bboxes->size(), crops.size()); for (int i = 0; i < crops.size(); ++i) { std::vector<Box<Dtype>> &boxes = Bboxes->at(i); const RectF &crop = crops[i]; bool normalize = crop.h <= 1 || crop.w <= 1; if (normalize) { CHECK_GT(height, 1); CHECK_GT(width, 1); } float x_off = normalize ? crop.x * width : crop.x; float y_off = normalize ? crop.y * height : crop.y; for (auto &box : boxes) { box.xmin += x_off; box.xmax += x_off; box.ymin += y_off; box.ymax += y_off; } } } // Explicit instantiation template void Clip(const BoxI &box, BoxI *clip_box, int min, int max); template void Clip(const BoxF &box, BoxF *clip_box, float min, float max); template int Size(const BoxI &box); template float Size(const BoxF &box); template float Intersection(const BoxI &box_a, const BoxI &box_b); template float Intersection(const BoxF &box_a, const BoxF &box_b); template float Union(const BoxI &box_a, const BoxI &box_b); template float Union(const BoxF &box_a, const BoxF &box_b); template float IoU(const BoxI &box_a, const BoxI &box_b); template float IoU(const BoxF &box_a, const BoxF &box_b); template VecBoxI NMS(const std::vector<VecBoxI> &Bboxes, float iou_threshold); template VecBoxF NMS(const std::vector<VecBoxF> &Bboxes, float iou_threshold); template void Smooth(const BoxI &old_boxes, BoxI *new_boxes, float smooth); template void Smooth(const BoxF &old_boxes, BoxF *new_boxes, float smooth); template void Smooth(const VecBoxI &old_boxes, VecBoxI *new_boxes, float smooth); template void Smooth(const VecBoxF &old_boxes, VecBoxF *new_boxes, float smooth); template void Amend(std::vector<VecBoxI> *Bboxes, const VecRectF &crops, int height, int width); template void Amend(std::vector<VecBoxF> *Bboxes, const VecRectF &crops, int height, int width); } // namespace Boxes <|endoftext|>
<commit_before>#include <cudaarithm.hpp> #include <opencv2/highgui.hpp> extern "C" struct TensorWrapper minCuda( struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst) { GpuMatT dstMat = dst.toGpuMatT(); cuda::GpuMat & mat = dstMat.mat; cuda::min(src1.toGpuMat(), src2.toGpuMat(), dstMat, prepareStream(info)); return TensorWrapper(dstMat, info.state); } extern "C" struct TensorWrapper maxCuda( struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst) { if (dst.isNull()) { cuda::GpuMat result; cuda::max(src1.toGpuMat(), src2.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::max(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), prepareStream(info)); return dst; } } extern "C" struct TensorPlusDouble thresholdCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst, double thresh, double maxval, int type) { TensorPlusDouble retval; if (dst.isNull()) { cuda::GpuMat result; retval.val = cuda::threshold(src.toGpuMat(), result, thresh, maxval, type, prepareStream(info)); new (&retval.tensor) TensorWrapper(result, info.state); } else { retval.val = cuda::threshold(src.toGpuMat(), dst.toGpuMat(), thresh, maxval, type, prepareStream(info)); retval.tensor = dst; } return retval; } extern "C" struct TensorWrapper magnitudeCuda( struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude) { if (magnitude.isNull()) { cuda::GpuMat result; cuda::magnitude(xy.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::magnitude(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info)); return magnitude; } } extern "C" struct TensorWrapper magnitudeSqrCuda( struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude) { if (magnitude.isNull()) { cuda::GpuMat result; cuda::magnitudeSqr(xy.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::magnitudeSqr(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info)); return magnitude; } } extern "C" struct TensorWrapper magnitude2Cuda( struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitude) { if (magnitude.isNull()) { cuda::GpuMat result; cuda::magnitude(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::magnitude(x.toGpuMat(), y.toGpuMat(), magnitude.toGpuMat(), prepareStream(info)); return magnitude; } } extern "C" struct TensorWrapper magnitudeSqr2Cuda( struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitudeSqr) { if (magnitudeSqr.isNull()) { cuda::GpuMat result; cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), magnitudeSqr.toGpuMat(), prepareStream(info)); return magnitudeSqr; } } extern "C" struct TensorWrapper phaseCuda( struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper angle, bool angleInDegrees) { if (angle.isNull()) { cuda::GpuMat result; cuda::phase(x.toGpuMat(), y.toGpuMat(), result, angleInDegrees, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::phase(x.toGpuMat(), y.toGpuMat(), angle.toGpuMat(), angleInDegrees, prepareStream(info)); return angle; } } extern "C" struct TensorArray cartToPolarCuda( struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitude, struct TensorWrapper angle, bool angleInDegrees) { std::vector<cuda::GpuMat> result(2); result[0] = magnitude.toGpuMat(); result[1] = angle.toGpuMat(); cuda::cartToPolar(x.toGpuMat(), y.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info)); return TensorArray(result, info.state); } extern "C" struct TensorArray polarToCartCuda( struct cutorchInfo info, struct TensorWrapper magnitude, struct TensorWrapper angle, struct TensorWrapper x, struct TensorWrapper y, bool angleInDegrees) { std::vector<cuda::GpuMat> result; result[0] = x.toGpuMat(); result[1] = y.toGpuMat(); cuda::polarToCart(magnitude.toGpuMat(), angle.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info)); return TensorArray(result, info.state); } extern "C" struct LookUpTablePtr LookUpTable_ctorCuda( struct cutorchInfo info, struct TensorWrapper lut) { return rescueObjectFromPtr(cuda::createLookUpTable(lut.toGpuMat())); } extern "C" struct TensorWrapper LookUpTable_transformCuda( struct cutorchInfo info, struct LookUpTablePtr ptr, struct TensorWrapper src, struct TensorWrapper dst) { if (dst.isNull()) { cuda::GpuMat result; ptr->transform(src.toGpuMat(), result); return TensorWrapper(result, info.state); } else { ptr->transform(src.toGpuMat(), dst.toGpuMat(), prepareStream(info)); return dst; } } extern "C" struct TensorWrapper rectStdDevCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sqr, struct TensorWrapper dst, struct RectWrapper rect) { if (dst.isNull()) { cv::Mat result; cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), result, rect, prepareStream(info)); return TensorWrapper(result); } else { cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), dst.toGpuMat(), rect, prepareStream(info)); return dst; } } extern "C" struct TensorWrapper normalizeCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst, double alpha, double beta, int norm_type, int dtype, struct TensorWrapper mask) { if (dst.isNull()) { cv::Mat result; cuda::normalize(src.toGpuMat(), result, alpha, beta, norm_type, dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info)); return TensorWrapper(result); } else { cuda::normalize(src.toGpuMat(), dst.toGpuMat(), alpha, beta, norm_type, dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info)); return dst; } } extern "C" struct TensorWrapper integralCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum) { if (sum.isNull()) { cv::Mat result; cuda::integral(src.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result); } else { cuda::integral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info)); return sum; } } extern "C" struct TensorWrapper sqrIntegralCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum) { if (sum.isNull()) { cv::Mat result; cuda::sqrIntegral(src.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result); } else { cuda::sqrIntegral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info)); return sum; } } extern "C" struct TensorWrapper mulSpectrumsCuda( struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst, int flags, bool conjB) { if (dst.isNull()) { cuda::GpuMat result; cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, conjB, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, conjB, prepareStream(info)); return dst; } } extern "C" struct TensorWrapper mulAndScaleSpectrumsCuda( struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst, int flags, float scale, bool conjB) { if (dst.isNull()) { cuda::GpuMat result; cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, scale, conjB, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, scale, conjB, prepareStream(info)); return dst; } } extern "C" struct TensorWrapper dftCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst, struct SizeWrapper dft_size, int flags) { if (dst.isNull()) { cv::Mat result; cuda::dft(src.toGpuMat(), result, dft_size, flags, prepareStream(info)); return TensorWrapper(result); } else { cuda::dft(src.toGpuMat(), dst.toGpuMat(), dft_size, flags, prepareStream(info)); return dst; } } extern "C" struct ConvolutionPtr Convolution_ctorCuda( struct cutorchInfo info, struct SizeWrapper user_block_size) { return rescueObjectFromPtr(cuda::createConvolution(user_block_size)); } extern "C" struct TensorWrapper Convolution_convolveCuda( struct cutorchInfo info, struct ConvolutionPtr ptr, struct TensorWrapper image, struct TensorWrapper templ, struct TensorWrapper result, bool ccor) { if (result.isNull()) { cuda::GpuMat resultMat; ptr->convolve(image.toGpuMat(), templ.toGpuMat(), resultMat, ccor, prepareStream(info)); return TensorWrapper(resultMat, info.state); } else { ptr->convolve(image.toGpuMat(), templ.toGpuMat(), result.toGpuMat(), ccor); return result; } } <commit_msg>Fix #193<commit_after>#include <cudaarithm.hpp> #include <opencv2/highgui.hpp> extern "C" struct TensorWrapper minCuda( struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst) { GpuMatT dstMat = dst.toGpuMatT(); cuda::GpuMat & mat = dstMat.mat; cuda::min(src1.toGpuMat(), src2.toGpuMat(), dstMat, prepareStream(info)); return TensorWrapper(dstMat, info.state); } extern "C" struct TensorWrapper maxCuda( struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst) { if (dst.isNull()) { cuda::GpuMat result; cuda::max(src1.toGpuMat(), src2.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::max(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), prepareStream(info)); return dst; } } extern "C" struct TensorPlusDouble thresholdCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst, double thresh, double maxval, int type) { TensorPlusDouble retval; if (dst.isNull()) { cuda::GpuMat result; retval.val = cuda::threshold(src.toGpuMat(), result, thresh, maxval, type, prepareStream(info)); new (&retval.tensor) TensorWrapper(result, info.state); } else { retval.val = cuda::threshold(src.toGpuMat(), dst.toGpuMat(), thresh, maxval, type, prepareStream(info)); retval.tensor = dst; } return retval; } extern "C" struct TensorWrapper magnitudeCuda( struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude) { if (magnitude.isNull()) { cuda::GpuMat result; cuda::magnitude(xy.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::magnitude(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info)); return magnitude; } } extern "C" struct TensorWrapper magnitudeSqrCuda( struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude) { if (magnitude.isNull()) { cuda::GpuMat result; cuda::magnitudeSqr(xy.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::magnitudeSqr(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info)); return magnitude; } } extern "C" struct TensorWrapper magnitude2Cuda( struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitude) { if (magnitude.isNull()) { cuda::GpuMat result; cuda::magnitude(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::magnitude(x.toGpuMat(), y.toGpuMat(), magnitude.toGpuMat(), prepareStream(info)); return magnitude; } } extern "C" struct TensorWrapper magnitudeSqr2Cuda( struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitudeSqr) { if (magnitudeSqr.isNull()) { cuda::GpuMat result; cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), magnitudeSqr.toGpuMat(), prepareStream(info)); return magnitudeSqr; } } extern "C" struct TensorWrapper phaseCuda( struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper angle, bool angleInDegrees) { if (angle.isNull()) { cuda::GpuMat result; cuda::phase(x.toGpuMat(), y.toGpuMat(), result, angleInDegrees, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::phase(x.toGpuMat(), y.toGpuMat(), angle.toGpuMat(), angleInDegrees, prepareStream(info)); return angle; } } extern "C" struct TensorArray cartToPolarCuda( struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitude, struct TensorWrapper angle, bool angleInDegrees) { std::vector<cuda::GpuMat> result(2); result[0] = magnitude.toGpuMat(); result[1] = angle.toGpuMat(); cuda::cartToPolar(x.toGpuMat(), y.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info)); return TensorArray(result, info.state); } extern "C" struct TensorArray polarToCartCuda( struct cutorchInfo info, struct TensorWrapper magnitude, struct TensorWrapper angle, struct TensorWrapper x, struct TensorWrapper y, bool angleInDegrees) { std::vector<cuda::GpuMat> result; result[0] = x.toGpuMat(); result[1] = y.toGpuMat(); cuda::polarToCart(magnitude.toGpuMat(), angle.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info)); return TensorArray(result, info.state); } extern "C" struct LookUpTablePtr LookUpTable_ctorCuda( struct cutorchInfo info, struct TensorWrapper lut) { return rescueObjectFromPtr(cuda::createLookUpTable(lut.toGpuMat())); } extern "C" struct TensorWrapper LookUpTable_transformCuda( struct cutorchInfo info, struct LookUpTablePtr ptr, struct TensorWrapper src, struct TensorWrapper dst) { if (dst.isNull()) { cuda::GpuMat result; ptr->transform(src.toGpuMat(), result); return TensorWrapper(result, info.state); } else { ptr->transform(src.toGpuMat(), dst.toGpuMat(), prepareStream(info)); return dst; } } extern "C" struct TensorWrapper rectStdDevCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sqr, struct TensorWrapper dst, struct RectWrapper rect) { if (dst.isNull()) { cuda::GpuMat result; cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), result, rect, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), dst.toGpuMat(), rect, prepareStream(info)); return dst; } } extern "C" struct TensorWrapper normalizeCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst, double alpha, double beta, int norm_type, int dtype, struct TensorWrapper mask) { if (dst.isNull()) { cuda::GpuMat result; cuda::normalize(src.toGpuMat(), result, alpha, beta, norm_type, dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::normalize(src.toGpuMat(), dst.toGpuMat(), alpha, beta, norm_type, dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info)); return dst; } } extern "C" struct TensorWrapper integralCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum) { if (sum.isNull()) { cuda::GpuMat result; cuda::integral(src.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::integral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info)); return sum; } } extern "C" struct TensorWrapper sqrIntegralCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum) { if (sum.isNull()) { cuda::GpuMat result; cuda::sqrIntegral(src.toGpuMat(), result, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::sqrIntegral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info)); return sum; } } extern "C" struct TensorWrapper mulSpectrumsCuda( struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst, int flags, bool conjB) { if (dst.isNull()) { cuda::GpuMat result; cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, conjB, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, conjB, prepareStream(info)); return dst; } } extern "C" struct TensorWrapper mulAndScaleSpectrumsCuda( struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst, int flags, float scale, bool conjB) { if (dst.isNull()) { cuda::GpuMat result; cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, scale, conjB, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, scale, conjB, prepareStream(info)); return dst; } } extern "C" struct TensorWrapper dftCuda( struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst, struct SizeWrapper dft_size, int flags) { if (dst.isNull()) { cuda::GpuMat result; cuda::dft(src.toGpuMat(), result, dft_size, flags, prepareStream(info)); return TensorWrapper(result, info.state); } else { cuda::dft(src.toGpuMat(), dst.toGpuMat(), dft_size, flags, prepareStream(info)); return dst; } } extern "C" struct ConvolutionPtr Convolution_ctorCuda( struct cutorchInfo info, struct SizeWrapper user_block_size) { return rescueObjectFromPtr(cuda::createConvolution(user_block_size)); } extern "C" struct TensorWrapper Convolution_convolveCuda( struct cutorchInfo info, struct ConvolutionPtr ptr, struct TensorWrapper image, struct TensorWrapper templ, struct TensorWrapper result, bool ccor) { if (result.isNull()) { cuda::GpuMat resultMat; ptr->convolve(image.toGpuMat(), templ.toGpuMat(), resultMat, ccor, prepareStream(info)); return TensorWrapper(resultMat, info.state); } else { ptr->convolve(image.toGpuMat(), templ.toGpuMat(), result.toGpuMat(), ccor); return result; } } <|endoftext|>
<commit_before>#pragma once #include <dispatch/dispatch.h> #include <sstream> #include <string> class gcd_utility final { public: class scoped_queue final { public: scoped_queue(void) { auto label = get_next_queue_label(); queue_ = dispatch_queue_create(label.c_str(), nullptr); } ~scoped_queue(void) { dispatch_release(queue_); } dispatch_queue_t _Nonnull get(void) { return queue_; } private: dispatch_queue_t _Nonnull queue_; }; private: static std::string get_next_queue_label(void) { static std::mutex mutex; static int id = 0; std::lock_guard<std::mutex> guard(mutex); std::stringstream stream; stream << "org.pqrs.gcd_utility." << id++; return stream.str(); } }; <commit_msg>add gcd_utility::scoped_queue::get_label<commit_after>#pragma once #include <dispatch/dispatch.h> #include <sstream> #include <string> class gcd_utility final { public: class scoped_queue final { public: scoped_queue(void) { auto label = get_next_queue_label(); queue_ = dispatch_queue_create(label.c_str(), nullptr); } ~scoped_queue(void) { dispatch_release(queue_); } dispatch_queue_t _Nonnull get(void) { return queue_; } std::string get_label(void) { auto p = dispatch_queue_get_label(queue_); return p ? p : ""; } private: dispatch_queue_t _Nonnull queue_; }; private: static std::string get_next_queue_label(void) { static std::mutex mutex; static int id = 0; std::lock_guard<std::mutex> guard(mutex); std::stringstream stream; stream << "org.pqrs.gcd_utility." << id++; return stream.str(); } }; <|endoftext|>
<commit_before>#include "SysConfig.h" #if(HAS_PCA9539) #include <CI2C.h> #include "CPCA9539.h" #include "CTimer.h" #include "NDataManager.h" namespace { CTimer pcaSampleTimer; namespace knight_rider { //Knight rider stuff //Bit counter uint8_t counter; //Value that stores the mutated counter uint8_t value; //Bit mask for the PCA uint8_t bitmask = 0x1F; bool firstPass; } } CPCA9539::CPCA9539( CI2C *i2cInterfaceIn ) : m_pca( i2cInterfaceIn ) { } void CPCA9539::Initialize() { Serial.println( "CPCA9539.Status:INIT;" ); //Timer resets pcaSampleTimer.Reset(); //Knight rider stuff knight_rider::counter = 0; knight_rider::firstPass = true; //Expander init m_pca.Initialize(); m_pca.PinMode( OUTPUT ); Serial.println( "CPCA9539.Status:POST_INIT;"); } void CPCA9539::Update( CCommand &commandIn ) { if( pcaSampleTimer.HasElapsed( 100 ) ) { KnightRider(); } } void CPCA9539::KnightRider() { if( knight_rider::firstPass ) { if( knight_rider::counter = 0 ) { knight_rider::counter = 2; } //For the PCA, 1 is low and 0 is high //So we need to not and then mask the counter to get the desired pattern knight_rider::value = ~(knight_rider::counter); knight_rider::value &= knight_rider::bitmask; //Write the desired pattern auto ret = m_pca.DigitalWriteDecimal( knight_rider::value ); if( ret != pca9539::ERetCode::SUCCESS ) { Serial.println(ret); } //Increase the counter knight_rider::counter <<= 1; if( knight_rider::counter == 16 ) { //Start the second half of the pattern knight_rider::firstPass = false; } } else { //For the PCA, 1 is low and 0 is high //So we need to not and then mask the counter to get the desired pattern knight_rider::value = ~(knight_rider::counter); knight_rider::value &= knight_rider::bitmask; //Write the desired pattern auto ret = m_pca.DigitalWriteDecimal( knight_rider::value ); if( ret != pca9539::ERetCode::SUCCESS ) { Serial.println(ret); } //Increase the counter knight_rider::counter >>= 1; if( knight_rider::counter == 0 ) { //Reset the counter to the first section of the pattern knight_rider::firstPass = true; } } } #endif<commit_msg>typo Honestly I don't know how this compiles w/o warns<commit_after>#include "SysConfig.h" #if(HAS_PCA9539) #include <CI2C.h> #include "CPCA9539.h" #include "CTimer.h" #include "NDataManager.h" namespace { CTimer pcaSampleTimer; namespace knight_rider { //Knight rider stuff //Bit counter uint8_t counter; //Value that stores the mutated counter uint8_t value; //Bit mask for the PCA uint8_t bitmask = 0x1F; bool firstPass; } } CPCA9539::CPCA9539( CI2C *i2cInterfaceIn ) : m_pca( i2cInterfaceIn ) { } void CPCA9539::Initialize() { Serial.println( "CPCA9539.Status:INIT;" ); //Timer resets pcaSampleTimer.Reset(); //Knight rider stuff knight_rider::counter = 0; knight_rider::firstPass = true; //Expander init m_pca.Initialize(); m_pca.PinMode( OUTPUT ); Serial.println( "CPCA9539.Status:POST_INIT;"); } void CPCA9539::Update( CCommand &commandIn ) { if( pcaSampleTimer.HasElapsed( 100 ) ) { KnightRider(); } } void CPCA9539::KnightRider() { if( knight_rider::firstPass ) { if( knight_rider::counter == 0 ) { knight_rider::counter = 2; } //For the PCA, 1 is low and 0 is high //So we need to not and then mask the counter to get the desired pattern knight_rider::value = ~(knight_rider::counter); knight_rider::value &= knight_rider::bitmask; //Write the desired pattern auto ret = m_pca.DigitalWriteDecimal( knight_rider::value ); if( ret != pca9539::ERetCode::SUCCESS ) { Serial.println(ret); } //Increase the counter knight_rider::counter <<= 1; if( knight_rider::counter == 16 ) { //Start the second half of the pattern knight_rider::firstPass = false; } } else { //For the PCA, 1 is low and 0 is high //So we need to not and then mask the counter to get the desired pattern knight_rider::value = ~(knight_rider::counter); knight_rider::value &= knight_rider::bitmask; //Write the desired pattern auto ret = m_pca.DigitalWriteDecimal( knight_rider::value ); if( ret != pca9539::ERetCode::SUCCESS ) { Serial.println(ret); } //Increase the counter knight_rider::counter >>= 1; if( knight_rider::counter == 0 ) { //Reset the counter to the first section of the pattern knight_rider::firstPass = true; } } } #endif<|endoftext|>
<commit_before>/* * AddSimMessage.cpp * * Created on: 18.04.2016 * Author: Marc Hartung */ #include "../../include/messages/AddSimMessage.hpp" #include "../../include/messages/AbstractMessage.hpp" #include "../../include/AdditionalTypes.hpp" #include "../../include/network_impl/SimNetworkFunctions.hpp" #include <iostream> namespace NetOff { ////////////////////////////////////////////// /////////////AddSimRequestMessage///////////// ////////////////////////////////////////////// AddSimRequestMessage::AddSimRequestMessage(const int & id, const std::string & path) : AbstractMessage<InitialClientMessageSpecifyer>(InitialClientMessageSpecifyer::ADD_SIM) { _dataSize = sizeof(InitialClientMessageSpecifyer) + sizeof(int) + getStringDataSize(path); _data = std::shared_ptr<char>(new char[_dataSize]); char * p = _data.get(); p = saveShiftIntegralInData(InitialClientMessageSpecifyer::ADD_SIM, p); p = saveShiftIntegralInData(id, p); saveStringInData(path, p); } AddSimRequestMessage::AddSimRequestMessage(std::shared_ptr<char> & data) : AbstractMessage<InitialClientMessageSpecifyer>(*reinterpret_cast<InitialClientMessageSpecifyer *>(data.get())), _data(data), _dataSize(0) { } char * AddSimRequestMessage::data() { return _data.get(); } const char * AddSimRequestMessage::data() const { return _data.get(); } size_t AddSimRequestMessage::dataSize() const { return _dataSize; } int AddSimRequestMessage::getSimId() { return *reinterpret_cast<int*>(shift<InitialClientMessageSpecifyer>(_data.get())); } std::string AddSimRequestMessage::getPath() { return createStringFromData(shift<int>(shift<InitialClientMessageSpecifyer>(_data.get()))); } ////////////////////////////////////////////// /////////AddSimRequestSuccessMessage////////// ////////////////////////////////////////////// AddSimSuccessMessage::AddSimSuccessMessage(const int & id, const VariableList & inputs, const VariableList & outputs) : AbstractMessage<InitialServerMessageSpecifyer>(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM), _dataSize(0) { _dataSize = sizeof(InitialServerMessageSpecifyer) + sizeof(int) + inputs.dataSize() + outputs.dataSize(); _data = std::shared_ptr<char>(new char[_dataSize]); char * p = _data.get(); p = saveShiftIntegralInData(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM, p); p = saveShiftIntegralInData(id, p); inputs.saveVariablesTo(p); p = shiftDataAccessable<VariableList>(inputs,p); outputs.saveVariablesTo(p); } AddSimSuccessMessage::AddSimSuccessMessage(std::shared_ptr<char> & data) : AbstractMessage<InitialServerMessageSpecifyer>(getIntegralFromData<InitialServerMessageSpecifyer>(data.get())), _data(data), _dataSize(0) { } char * AddSimSuccessMessage::data() { return _data.get(); } const char * AddSimSuccessMessage::data() const { return _data.get(); } size_t AddSimSuccessMessage::dataSize() const { return _dataSize; } const int & AddSimSuccessMessage::getSimId() const { return *reinterpret_cast<int*>(shift<InitialServerMessageSpecifyer>(_data.get())); } VariableList AddSimSuccessMessage::getInputVariableList() const { return VariableList::getVariableListFromData(shift<const int>(shift<const InitialServerMessageSpecifyer>(_data.get()))); } VariableList AddSimSuccessMessage::getOutputVariableList() const { return VariableList::getVariableListFromData(shift<const int>(shiftDataAccessable<VariableList>(getInputVariableList(),shift<const InitialServerMessageSpecifyer>(_data.get())))); } std::string AddSimSuccessMessage::getPath() { return createStringFromData(shift<int>(shift<InitialServerMessageSpecifyer>(_data.get()))); } } <commit_msg>Add default initialization of members to constructor<commit_after>/* * AddSimMessage.cpp * * Created on: 18.04.2016 * Author: Marc Hartung */ #include "../../include/messages/AddSimMessage.hpp" #include "../../include/messages/AbstractMessage.hpp" #include "../../include/AdditionalTypes.hpp" #include "../../include/network_impl/SimNetworkFunctions.hpp" #include <iostream> namespace NetOff { ////////////////////////////////////////////// /////////////AddSimRequestMessage///////////// ////////////////////////////////////////////// AddSimRequestMessage::AddSimRequestMessage(const int & id, const std::string & path) : AbstractMessage<InitialClientMessageSpecifyer>(InitialClientMessageSpecifyer::ADD_SIM), _data(nullptr), _dataSize(0) { _dataSize = sizeof(InitialClientMessageSpecifyer) + sizeof(int) + getStringDataSize(path); _data = std::shared_ptr<char>(new char[_dataSize]); char * p = _data.get(); p = saveShiftIntegralInData(InitialClientMessageSpecifyer::ADD_SIM, p); p = saveShiftIntegralInData(id, p); saveStringInData(path, p); } AddSimRequestMessage::AddSimRequestMessage(std::shared_ptr<char> & data) : AbstractMessage<InitialClientMessageSpecifyer>(*reinterpret_cast<InitialClientMessageSpecifyer *>(data.get())), _data(data), _dataSize(0) { } char * AddSimRequestMessage::data() { return _data.get(); } const char * AddSimRequestMessage::data() const { return _data.get(); } size_t AddSimRequestMessage::dataSize() const { return _dataSize; } int AddSimRequestMessage::getSimId() { return *reinterpret_cast<int*>(shift<InitialClientMessageSpecifyer>(_data.get())); } std::string AddSimRequestMessage::getPath() { return createStringFromData(shift<int>(shift<InitialClientMessageSpecifyer>(_data.get()))); } ////////////////////////////////////////////// /////////AddSimRequestSuccessMessage////////// ////////////////////////////////////////////// AddSimSuccessMessage::AddSimSuccessMessage(const int & id, const VariableList & inputs, const VariableList & outputs) : AbstractMessage<InitialServerMessageSpecifyer>(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM), _data(nullptr), _dataSize(0) { _dataSize = sizeof(InitialServerMessageSpecifyer) + sizeof(int) + inputs.dataSize() + outputs.dataSize(); _data = std::shared_ptr<char>(new char[_dataSize]); char * p = _data.get(); p = saveShiftIntegralInData(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM, p); p = saveShiftIntegralInData(id, p); inputs.saveVariablesTo(p); p = shiftDataAccessable<VariableList>(inputs, p); outputs.saveVariablesTo(p); } AddSimSuccessMessage::AddSimSuccessMessage(std::shared_ptr<char> & data) : AbstractMessage<InitialServerMessageSpecifyer>(getIntegralFromData<InitialServerMessageSpecifyer>(data.get())), _data(data), _dataSize(0) { } char * AddSimSuccessMessage::data() { return _data.get(); } const char * AddSimSuccessMessage::data() const { return _data.get(); } size_t AddSimSuccessMessage::dataSize() const { return _dataSize; } const int & AddSimSuccessMessage::getSimId() const { return *reinterpret_cast<int*>(shift<InitialServerMessageSpecifyer>(_data.get())); } VariableList AddSimSuccessMessage::getInputVariableList() const { return VariableList::getVariableListFromData(shift<const int>(shift<const InitialServerMessageSpecifyer>(_data.get()))); } VariableList AddSimSuccessMessage::getOutputVariableList() const { return VariableList::getVariableListFromData(shift<const int>(shiftDataAccessable<VariableList>(getInputVariableList(), shift<const InitialServerMessageSpecifyer>(_data.get())))); } std::string AddSimSuccessMessage::getPath() { return createStringFromData(shift<int>(shift<InitialServerMessageSpecifyer>(_data.get()))); } } <|endoftext|>
<commit_before>/*! * Copyright (c) 2017 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_ #define LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_ #include <LightGBM/meta.h> #include <LightGBM/metric.h> #include <LightGBM/utils/common.h> #include <LightGBM/utils/log.h> #include <string> #include <algorithm> #include <sstream> #include <vector> /* * Implements three related metrics: * * (1) standard cross-entropy that can be used for continuous labels in [0, 1] * (2) "intensity-weighted" cross-entropy, also for continuous labels in [0, 1] * (3) Kullback-Leibler divergence, also for continuous labels in [0, 1] * * (3) adds an offset term to (1); the entropy of the label * * See xentropy_objective.hpp for further details. * */ namespace LightGBM { // label should be in interval [0, 1]; // prob should be in interval (0, 1); prob is clipped if needed inline static double XentLoss(label_t label, double prob) { const double log_arg_epsilon = 1.0e-12; double a = label; if (prob > log_arg_epsilon) { a *= std::log(prob); } else { a *= std::log(log_arg_epsilon); } double b = 1.0f - label; if (1.0f - prob > log_arg_epsilon) { b *= std::log(1.0f - prob); } else { b *= std::log(log_arg_epsilon); } return - (a + b); } // hhat >(=) 0 assumed; and weight > 0 required; but not checked here inline static double XentLambdaLoss(label_t label, label_t weight, double hhat) { return XentLoss(label, 1.0f - std::exp(-weight * hhat)); } // Computes the (negative) entropy for label p; p should be in interval [0, 1]; // This is used to presum the KL-divergence offset term (to be _added_ to the cross-entropy loss). // NOTE: x*log(x) = 0 for x=0,1; so only add when in (0, 1); avoid log(0)*0 inline static double YentLoss(double p) { double hp = 0.0; if (p > 0) hp += p * std::log(p); double q = 1.0f - p; if (q > 0) hp += q * std::log(q); return hp; } // // CrossEntropyMetric : "xentropy" : (optional) weights are used linearly // class CrossEntropyMetric : public Metric { public: explicit CrossEntropyMetric(const Config&) {} virtual ~CrossEntropyMetric() {} void Init(const Metadata& metadata, data_size_t num_data) override { name_.emplace_back("cross_entropy"); num_data_ = num_data; label_ = metadata.label(); weights_ = metadata.weights(); CHECK_NOTNULL(label_); // ensure that labels are in interval [0, 1], interval ends included Common::CheckElementsIntervalClosed<label_t>(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str()); Log::Info("[%s:%s]: (metric) labels passed interval [0, 1] check", GetName()[0].c_str(), __func__); // check that weights are non-negative and sum is positive if (weights_ == nullptr) { sum_weights_ = static_cast<double>(num_data_); } else { label_t minw; Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast<label_t*>(nullptr), &sum_weights_); if (minw < 0.0f) { Log::Fatal("[%s:%s]: (metric) weights not allowed to be negative", GetName()[0].c_str(), __func__); } } // check weight sum (may fail to be zero) if (sum_weights_ <= 0.0f) { Log::Fatal("[%s:%s]: sum-of-weights = %f is non-positive", __func__, GetName()[0].c_str(), sum_weights_); } Log::Info("[%s:%s]: sum-of-weights = %f", GetName()[0].c_str(), __func__, sum_weights_); } std::vector<double> Eval(const double* score, const ObjectiveFunction* objective) const override { double sum_loss = 0.0f; if (objective == nullptr) { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { sum_loss += XentLoss(label_[i], score[i]); // NOTE: does not work unless score is a probability } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { sum_loss += XentLoss(label_[i], score[i]) * weights_[i]; // NOTE: does not work unless score is a probability } } } else { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double p = 0; objective->ConvertOutput(&score[i], &p); sum_loss += XentLoss(label_[i], p); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double p = 0; objective->ConvertOutput(&score[i], &p); sum_loss += XentLoss(label_[i], p) * weights_[i]; } } } double loss = sum_loss / sum_weights_; return std::vector<double>(1, loss); } const std::vector<std::string>& GetName() const override { return name_; } double factor_to_bigger_better() const override { return -1.0f; // negative means smaller loss is better, positive means larger loss is better } private: /*! \brief Number of data points */ data_size_t num_data_; /*! \brief Pointer to label */ const label_t* label_; /*! \brief Pointer to weights */ const label_t* weights_; /*! \brief Sum of weights */ double sum_weights_; /*! \brief Name of this metric */ std::vector<std::string> name_; }; // // CrossEntropyLambdaMetric : "xentlambda" : (optional) weights have a different meaning than for "xentropy" // ATTENTION: Supposed to be used when the objective also is "xentlambda" // class CrossEntropyLambdaMetric : public Metric { public: explicit CrossEntropyLambdaMetric(const Config&) {} virtual ~CrossEntropyLambdaMetric() {} void Init(const Metadata& metadata, data_size_t num_data) override { name_.emplace_back("cross_entropy_lambda"); num_data_ = num_data; label_ = metadata.label(); weights_ = metadata.weights(); CHECK_NOTNULL(label_); Common::CheckElementsIntervalClosed<label_t>(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str()); Log::Info("[%s:%s]: (metric) labels passed interval [0, 1] check", GetName()[0].c_str(), __func__); // check all weights are strictly positive; throw error if not if (weights_ != nullptr) { label_t minw; Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast<label_t*>(nullptr), static_cast<label_t*>(nullptr)); if (minw <= 0.0f) { Log::Fatal("[%s:%s]: (metric) all weights must be positive", GetName()[0].c_str(), __func__); } } } std::vector<double> Eval(const double* score, const ObjectiveFunction* objective) const override { double sum_loss = 0.0f; if (objective == nullptr) { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double hhat = std::log(1.0f + std::exp(score[i])); // auto-convert sum_loss += XentLambdaLoss(label_[i], 1.0f, hhat); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double hhat = std::log(1.0f + std::exp(score[i])); // auto-convert sum_loss += XentLambdaLoss(label_[i], weights_[i], hhat); } } } else { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double hhat = 0; objective->ConvertOutput(&score[i], &hhat); // NOTE: this only works if objective = "xentlambda" sum_loss += XentLambdaLoss(label_[i], 1.0f, hhat); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double hhat = 0; objective->ConvertOutput(&score[i], &hhat); // NOTE: this only works if objective = "xentlambda" sum_loss += XentLambdaLoss(label_[i], weights_[i], hhat); } } } return std::vector<double>(1, sum_loss / static_cast<double>(num_data_)); } const std::vector<std::string>& GetName() const override { return name_; } double factor_to_bigger_better() const override { return -1.0f; } private: /*! \brief Number of data points */ data_size_t num_data_; /*! \brief Pointer to label */ const label_t* label_; /*! \brief Pointer to weights */ const label_t* weights_; /*! \brief Name of this metric */ std::vector<std::string> name_; }; // // KullbackLeiblerDivergence : "kldiv" : (optional) weights are used linearly // class KullbackLeiblerDivergence : public Metric { public: explicit KullbackLeiblerDivergence(const Config&) {} virtual ~KullbackLeiblerDivergence() {} void Init(const Metadata& metadata, data_size_t num_data) override { name_.emplace_back("kullback_leibler"); num_data_ = num_data; label_ = metadata.label(); weights_ = metadata.weights(); CHECK_NOTNULL(label_); Common::CheckElementsIntervalClosed<label_t>(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str()); Log::Info("[%s:%s]: (metric) labels passed interval [0, 1] check", GetName()[0].c_str(), __func__); if (weights_ == nullptr) { sum_weights_ = static_cast<double>(num_data_); } else { label_t minw; Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast<label_t*>(nullptr), &sum_weights_); if (minw < 0.0f) { Log::Fatal("[%s:%s]: (metric) at least one weight is negative", GetName()[0].c_str(), __func__); } } // check weight sum if (sum_weights_ <= 0.0f) { Log::Fatal("[%s:%s]: sum-of-weights = %f is non-positive", GetName()[0].c_str(), __func__, sum_weights_); } Log::Info("[%s:%s]: sum-of-weights = %f", GetName()[0].c_str(), __func__, sum_weights_); // evaluate offset term presum_label_entropy_ = 0.0f; if (weights_ == nullptr) { // #pragma omp parallel for schedule(static) for (data_size_t i = 0; i < num_data; ++i) { presum_label_entropy_ += YentLoss(label_[i]); } } else { // #pragma omp parallel for schedule(static) for (data_size_t i = 0; i < num_data; ++i) { presum_label_entropy_ += YentLoss(label_[i]) * weights_[i]; } } presum_label_entropy_ /= sum_weights_; // communicate the value of the offset term to be added Log::Info("%s offset term = %f", GetName()[0].c_str(), presum_label_entropy_); } std::vector<double> Eval(const double* score, const ObjectiveFunction* objective) const override { double sum_loss = 0.0f; if (objective == nullptr) { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { sum_loss += XentLoss(label_[i], score[i]); // NOTE: does not work unless score is a probability } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { sum_loss += XentLoss(label_[i], score[i]) * weights_[i]; // NOTE: does not work unless score is a probability } } } else { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double p = 0; objective->ConvertOutput(&score[i], &p); sum_loss += XentLoss(label_[i], p); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double p = 0; objective->ConvertOutput(&score[i], &p); sum_loss += XentLoss(label_[i], p) * weights_[i]; } } } double loss = presum_label_entropy_ + sum_loss / sum_weights_; return std::vector<double>(1, loss); } const std::vector<std::string>& GetName() const override { return name_; } double factor_to_bigger_better() const override { return -1.0f; } private: /*! \brief Number of data points */ data_size_t num_data_; /*! \brief Pointer to label */ const label_t* label_; /*! \brief Pointer to weights */ const label_t* weights_; /*! \brief Sum of weights */ double sum_weights_; /*! \brief Offset term to cross-entropy; precomputed during init */ double presum_label_entropy_; /*! \brief Name of this metric */ std::vector<std::string> name_; }; } // end namespace LightGBM #endif // end #ifndef LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_ <commit_msg>remove commented-out code in cross-entropy metric source (#3999)<commit_after>/*! * Copyright (c) 2017 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_ #define LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_ #include <LightGBM/meta.h> #include <LightGBM/metric.h> #include <LightGBM/utils/common.h> #include <LightGBM/utils/log.h> #include <string> #include <algorithm> #include <sstream> #include <vector> /* * Implements three related metrics: * * (1) standard cross-entropy that can be used for continuous labels in [0, 1] * (2) "intensity-weighted" cross-entropy, also for continuous labels in [0, 1] * (3) Kullback-Leibler divergence, also for continuous labels in [0, 1] * * (3) adds an offset term to (1); the entropy of the label * * See xentropy_objective.hpp for further details. * */ namespace LightGBM { // label should be in interval [0, 1]; // prob should be in interval (0, 1); prob is clipped if needed inline static double XentLoss(label_t label, double prob) { const double log_arg_epsilon = 1.0e-12; double a = label; if (prob > log_arg_epsilon) { a *= std::log(prob); } else { a *= std::log(log_arg_epsilon); } double b = 1.0f - label; if (1.0f - prob > log_arg_epsilon) { b *= std::log(1.0f - prob); } else { b *= std::log(log_arg_epsilon); } return - (a + b); } // hhat >(=) 0 assumed; and weight > 0 required; but not checked here inline static double XentLambdaLoss(label_t label, label_t weight, double hhat) { return XentLoss(label, 1.0f - std::exp(-weight * hhat)); } // Computes the (negative) entropy for label p; p should be in interval [0, 1]; // This is used to presum the KL-divergence offset term (to be _added_ to the cross-entropy loss). // NOTE: x*log(x) = 0 for x=0,1; so only add when in (0, 1); avoid log(0)*0 inline static double YentLoss(double p) { double hp = 0.0; if (p > 0) hp += p * std::log(p); double q = 1.0f - p; if (q > 0) hp += q * std::log(q); return hp; } // // CrossEntropyMetric : "xentropy" : (optional) weights are used linearly // class CrossEntropyMetric : public Metric { public: explicit CrossEntropyMetric(const Config&) {} virtual ~CrossEntropyMetric() {} void Init(const Metadata& metadata, data_size_t num_data) override { name_.emplace_back("cross_entropy"); num_data_ = num_data; label_ = metadata.label(); weights_ = metadata.weights(); CHECK_NOTNULL(label_); // ensure that labels are in interval [0, 1], interval ends included Common::CheckElementsIntervalClosed<label_t>(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str()); Log::Info("[%s:%s]: (metric) labels passed interval [0, 1] check", GetName()[0].c_str(), __func__); // check that weights are non-negative and sum is positive if (weights_ == nullptr) { sum_weights_ = static_cast<double>(num_data_); } else { label_t minw; Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast<label_t*>(nullptr), &sum_weights_); if (minw < 0.0f) { Log::Fatal("[%s:%s]: (metric) weights not allowed to be negative", GetName()[0].c_str(), __func__); } } // check weight sum (may fail to be zero) if (sum_weights_ <= 0.0f) { Log::Fatal("[%s:%s]: sum-of-weights = %f is non-positive", __func__, GetName()[0].c_str(), sum_weights_); } Log::Info("[%s:%s]: sum-of-weights = %f", GetName()[0].c_str(), __func__, sum_weights_); } std::vector<double> Eval(const double* score, const ObjectiveFunction* objective) const override { double sum_loss = 0.0f; if (objective == nullptr) { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { sum_loss += XentLoss(label_[i], score[i]); // NOTE: does not work unless score is a probability } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { sum_loss += XentLoss(label_[i], score[i]) * weights_[i]; // NOTE: does not work unless score is a probability } } } else { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double p = 0; objective->ConvertOutput(&score[i], &p); sum_loss += XentLoss(label_[i], p); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double p = 0; objective->ConvertOutput(&score[i], &p); sum_loss += XentLoss(label_[i], p) * weights_[i]; } } } double loss = sum_loss / sum_weights_; return std::vector<double>(1, loss); } const std::vector<std::string>& GetName() const override { return name_; } double factor_to_bigger_better() const override { return -1.0f; // negative means smaller loss is better, positive means larger loss is better } private: /*! \brief Number of data points */ data_size_t num_data_; /*! \brief Pointer to label */ const label_t* label_; /*! \brief Pointer to weights */ const label_t* weights_; /*! \brief Sum of weights */ double sum_weights_; /*! \brief Name of this metric */ std::vector<std::string> name_; }; // // CrossEntropyLambdaMetric : "xentlambda" : (optional) weights have a different meaning than for "xentropy" // ATTENTION: Supposed to be used when the objective also is "xentlambda" // class CrossEntropyLambdaMetric : public Metric { public: explicit CrossEntropyLambdaMetric(const Config&) {} virtual ~CrossEntropyLambdaMetric() {} void Init(const Metadata& metadata, data_size_t num_data) override { name_.emplace_back("cross_entropy_lambda"); num_data_ = num_data; label_ = metadata.label(); weights_ = metadata.weights(); CHECK_NOTNULL(label_); Common::CheckElementsIntervalClosed<label_t>(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str()); Log::Info("[%s:%s]: (metric) labels passed interval [0, 1] check", GetName()[0].c_str(), __func__); // check all weights are strictly positive; throw error if not if (weights_ != nullptr) { label_t minw; Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast<label_t*>(nullptr), static_cast<label_t*>(nullptr)); if (minw <= 0.0f) { Log::Fatal("[%s:%s]: (metric) all weights must be positive", GetName()[0].c_str(), __func__); } } } std::vector<double> Eval(const double* score, const ObjectiveFunction* objective) const override { double sum_loss = 0.0f; if (objective == nullptr) { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double hhat = std::log(1.0f + std::exp(score[i])); // auto-convert sum_loss += XentLambdaLoss(label_[i], 1.0f, hhat); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double hhat = std::log(1.0f + std::exp(score[i])); // auto-convert sum_loss += XentLambdaLoss(label_[i], weights_[i], hhat); } } } else { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double hhat = 0; objective->ConvertOutput(&score[i], &hhat); // NOTE: this only works if objective = "xentlambda" sum_loss += XentLambdaLoss(label_[i], 1.0f, hhat); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double hhat = 0; objective->ConvertOutput(&score[i], &hhat); // NOTE: this only works if objective = "xentlambda" sum_loss += XentLambdaLoss(label_[i], weights_[i], hhat); } } } return std::vector<double>(1, sum_loss / static_cast<double>(num_data_)); } const std::vector<std::string>& GetName() const override { return name_; } double factor_to_bigger_better() const override { return -1.0f; } private: /*! \brief Number of data points */ data_size_t num_data_; /*! \brief Pointer to label */ const label_t* label_; /*! \brief Pointer to weights */ const label_t* weights_; /*! \brief Name of this metric */ std::vector<std::string> name_; }; // // KullbackLeiblerDivergence : "kldiv" : (optional) weights are used linearly // class KullbackLeiblerDivergence : public Metric { public: explicit KullbackLeiblerDivergence(const Config&) {} virtual ~KullbackLeiblerDivergence() {} void Init(const Metadata& metadata, data_size_t num_data) override { name_.emplace_back("kullback_leibler"); num_data_ = num_data; label_ = metadata.label(); weights_ = metadata.weights(); CHECK_NOTNULL(label_); Common::CheckElementsIntervalClosed<label_t>(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str()); Log::Info("[%s:%s]: (metric) labels passed interval [0, 1] check", GetName()[0].c_str(), __func__); if (weights_ == nullptr) { sum_weights_ = static_cast<double>(num_data_); } else { label_t minw; Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast<label_t*>(nullptr), &sum_weights_); if (minw < 0.0f) { Log::Fatal("[%s:%s]: (metric) at least one weight is negative", GetName()[0].c_str(), __func__); } } // check weight sum if (sum_weights_ <= 0.0f) { Log::Fatal("[%s:%s]: sum-of-weights = %f is non-positive", GetName()[0].c_str(), __func__, sum_weights_); } Log::Info("[%s:%s]: sum-of-weights = %f", GetName()[0].c_str(), __func__, sum_weights_); // evaluate offset term presum_label_entropy_ = 0.0f; if (weights_ == nullptr) { for (data_size_t i = 0; i < num_data; ++i) { presum_label_entropy_ += YentLoss(label_[i]); } } else { for (data_size_t i = 0; i < num_data; ++i) { presum_label_entropy_ += YentLoss(label_[i]) * weights_[i]; } } presum_label_entropy_ /= sum_weights_; // communicate the value of the offset term to be added Log::Info("%s offset term = %f", GetName()[0].c_str(), presum_label_entropy_); } std::vector<double> Eval(const double* score, const ObjectiveFunction* objective) const override { double sum_loss = 0.0f; if (objective == nullptr) { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { sum_loss += XentLoss(label_[i], score[i]); // NOTE: does not work unless score is a probability } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { sum_loss += XentLoss(label_[i], score[i]) * weights_[i]; // NOTE: does not work unless score is a probability } } } else { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double p = 0; objective->ConvertOutput(&score[i], &p); sum_loss += XentLoss(label_[i], p); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { double p = 0; objective->ConvertOutput(&score[i], &p); sum_loss += XentLoss(label_[i], p) * weights_[i]; } } } double loss = presum_label_entropy_ + sum_loss / sum_weights_; return std::vector<double>(1, loss); } const std::vector<std::string>& GetName() const override { return name_; } double factor_to_bigger_better() const override { return -1.0f; } private: /*! \brief Number of data points */ data_size_t num_data_; /*! \brief Pointer to label */ const label_t* label_; /*! \brief Pointer to weights */ const label_t* weights_; /*! \brief Sum of weights */ double sum_weights_; /*! \brief Offset term to cross-entropy; precomputed during init */ double presum_label_entropy_; /*! \brief Name of this metric */ std::vector<std::string> name_; }; } // end namespace LightGBM #endif // end #ifndef LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_ <|endoftext|>
<commit_before>#include "GPU.H" #include "CAMERA.H" #include "LOAD_LEV.H" #include "PROFILE.H" #include <assert.h> #include <LIBGPU.H> unsigned long GnFrameCounter = 19; unsigned long GnLastFrameCount = 19; struct PSXTEXTSTRUCT* psxtextinfo; struct PSXSPRITESTRUCT* psxspriteinfo; int rgbscaleme = 256; int gfx_debugging_mode; struct DB_STRUCT db; struct MMTEXTURE* RoomTextInfo; unsigned long GadwOrderingTables_V2[512]; static int LnFlipFrame; unsigned long GadwOrderingTables[5128]; unsigned long GadwPolygonBuffers[52260]; void GPU_UseOrderingTables(unsigned long* pBuffers, int nOTSize)//5DF68(<), 5F1C8(<) { db.order_table[0] = &pBuffers[0]; db.order_table[1] = &pBuffers[nOTSize]; db.nOTSize = nOTSize; db.pickup_order_table[0] = &db.disp[1]; db.pickup_order_table[1] = &GadwOrderingTables_V2[256]; #if 0 //Should be safe to use 32-bit ptrs tho db.order_table[0] = (unsigned long*)((unsigned long) pBuffers & 0xFFFFFF); db.order_table[1] = (unsigned long*)((unsigned long) &pBuffers[nOTSize] & 0xFFFFFF); db.nOTSize = nOTSize; db.pickup_order_table[0] = (unsigned long*)((unsigned long)&db.disp[1] & 0xFFFFFF); db.pickup_order_table[1] = (unsigned long*)((unsigned long)&GadwOrderingTables_V2[256] & 0xFFFFFF); #endif return; } void GPU_UsePolygonBuffers(unsigned long* pBuffers, int nPBSize)//5DFB0(<), { #if 1 db.nPBSize = nPBSize; db.poly_buffer[0] = &pBuffers[0]; db.poly_buffer[1] = &pBuffers[nPBSize]; #else db.nPBSize = nPBSize; db.poly_buffer[0] = (unsigned long*)((unsigned long)pBuffers & 0xFFFFFF); db.poly_buffer[1] = (unsigned long*)((unsigned long)&pBuffers[nPBSize] & 0xFFFFFF); #endif return; } void GPU_SyncBothScreens()//5F374(<), 60054(<) { DrawSync(0); db.current_buffer ^= 1; if (db.current_buffer != 0) { MoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y); //TODO: Verify ra += 0x10;! prolly else skip loc_5F3A8 (implemented but should be checked). } else { //loc_5F3A8 MoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y); } DrawSync(0); return; } void GPU_BeginScene()//5F0F0(<), 5FDD0(<) { db.ot = db.order_table[db.current_buffer]; db.polyptr = (char*)db.poly_buffer[db.current_buffer]; db.curpolybuf = (char*)db.poly_buffer[db.current_buffer]; db.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer]) + 26000; db.pickup_ot = db.pickup_order_table[db.current_buffer]; ClearOTagR(db.order_table[db.current_buffer], db.nOTSize); return; } int GPU_FlipNoIdle()//5E078(<), 5F264(<) { #if INTERNAL if (ProfileDraw) { ProfileRGB(255, 255, 255); ProfileAddOT(&db.ot[0]); }//loc_5E0B0 #endif DrawSync(0);//TODO confirm retail is sub_6B144 draw sync #if _INTERNAL if (ProfileDraw) { ProfileAddDrawOT(&db.ot[0]); }//loc_5E0D8 #endif LnFlipFrame = GnLastFrameCount; if (GnLastFrameCount < 2) { //loc_5E0F4 do { VSync(0); LnFlipFrame++; } while (LnFlipFrame < 2); } else { //loc_5E120 VSync(0); LnFlipFrame++; } //loc_5E138 //v0 = db.current_buffer; GnLastFrameCount = 0; PutDispEnv(&db.disp[db.current_buffer]); DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[db.current_buffer]); #if INTERNAL ProfileStartCount(); #endif db.current_buffer ^= 1; return LnFlipFrame; } void GPU_GetScreenPosition(short* x, short* y)//5F34C, ? { *x = db.disp[0].screen.x; *y = db.disp[0].screen.y; return; } /* PSX VRAM (H) * ----------- 512px * | TL | TR | | * ----------- v * | BL | BR | * ----------- *(W)1024px--> * */ void GPU_ClearVRAM()//5F2D0(<), 5FFB0(<) (F) { RECT r; DrawSync(0); VSync(0); //Clear TL r.x = 0; r.y = 0; r.w = 512; r.h = 256; clear_a_rect(&r); //Clear BL r.y = 256; clear_a_rect(&r); //Clear BR r.x = 512; clear_a_rect(&r); //Clear TR r.y = 0; clear_a_rect(&r); DrawSync(0); VSync(0); return; } void clear_a_rect(RECT* r)//5F334(<), 60014(<) (F) { ClearImage(r, 0, 48, 0); return; } //@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code. void GPU_FlipToBuffer(int buffer_index)//5F3C8(<), 600A8(<) (F) { DrawSync(0); VSync(0); buffer_index &= 1; if (buffer_index) { PutDispEnv(&db.disp[1]); db.current_buffer = buffer_index ^ 1; PutDrawEnv(&db.draw[1]); } else { PutDispEnv(&db.disp[0]); db.current_buffer = buffer_index ^ 1; PutDrawEnv(&db.draw[0]); } return; } void GPU_EndScene()//5DFDC(<), 5F23C(!) { #if 0 //int nPolys; //static int nWorstPolys; lui $v0, 0x4EC4 int a0 = &db.polyptr[0]; int v1 = &db.curpolybuf[0]; int v0 = 0x4EC4EC4F; a0 -= v1; v0 = a0 * v0; a0 >>= 31; v1 = psxtextinfo->u2v2pad; v0 >>= 4; v0 -= a0; if (v1 < v0) { u2v2pad = v0; }//loc_5E020 //loc_5E020 #endif OptimiseOTagR(&db.ot[0], db.nOTSize); #if 0 nop ProfileRGB(-1, -1, -1); a0 = db.nOTSize; do_gfx_debug_mode(&db.ot[db.nOTSize - 1]); ProfileRGB(0, -1, -1); #endif return; } long OptimiseOTagR(unsigned long* ot, int nOTSize)//86CC4(<), 88D08(<) { unsigned long* a1; unsigned long* a3; unsigned long v0; unsigned long* v1; long at = 0; if (nOTSize < 8) { return 0; } a1 = &ot[nOTSize - 1]; v1 = &ot[1]; v0 = a1[0]; //loc_86CE4 do { a1--; if ((unsigned long*)v0 == a1) { a3 = a1 - 1; if (a1 == ot) { return at; } //loc_86CF4 do { v0 = a1[0]; a1--; if (a1 == v1) { break; } at++; } while ((unsigned long*) v0 == a1); //loc_86D08 a3[0] = v0; } v0 = a1[0]; } while (a1 != ot); //loc_86D0C return at; } void draw_rotate_sprite(long a0, long a1, long a2)//5F134, 5FE14 { #if 1 long t0; short* v0; long t6; long t5; long* a33; long t2; long at; long* t3; long v1; long t1; long t4; long v00; t0 = (DelRotAng - 52) & 0xFFF; a2 = -a2; v0 = &rcossin_tbl[t0 * 2]; t6 = v0[0]; a2 >>= 1; t6 = a2 * t6;// t3 = &db.ot[0]; t5 = v0[1]; a33 = db.polyptr; t2 = 0x2C808080; t5 = a2 * t5; at = 0x1303F00; DelRotAng = t0; *(long*) &db.polyptr[4] = t2; *(long*) &db.polyptr[12] = 0; *(long*) &db.polyptr[20] = at; t6 >>= 12; t5 >>= 12; t0 = t6 - t5; a2 = -t6; t4 = a2 - t5; a2 += t5; t1 = t6 + t5; v00 = t0 >> 1; v00 += a0; t0 += v00; v1 = t4 >> 1; v1 += a0; t4 += v1; v00 = a2 >> 1; v00 += a0; a2 += v00; v1 = t1 >> 1; v1 += a0; t1 += v1; v00 = t5 + t6; v00 += a1; v1 = -t5; *(short*) &db.polyptr[8] = t0; *(short*) &db.polyptr[10] = v00; v00 = v1 + t6; v00 += a1; *(short*) &db.polyptr[16] = t4; *(short*) &db.polyptr[18] = v00; v00 = t5 - t6; v00 += a1; v1 -= t6; *(short*) &db.polyptr[24] = t1; *(short*) &db.polyptr[26] = v00; t4 = 0x3F;//width/height? *(short*) &db.polyptr[28] = t4; t4 = 0x3F3F; *(short*) &db.polyptr[36] = t4; a1 += v1; *(short*) &db.polyptr[32] = a2; *(short*) &db.polyptr[34] = a1;//Verified v00 = db.ot[0]; at = 0x09000000; v00 |= at; db.ot[0] = &db.polyptr[0]; *(int*) &db.polyptr[0] = v00; db.polyptr += 0x28;//sizeof(POLY_F3); * 2 v00 = 0x780100; v1 = 0x6800; a0 = 0x7801FF; *(long*) &db.polyptr[4] = t2; *(long*) &db.polyptr[8] = v00; *(long*) &db.polyptr[12] = v1; *(long*) &db.polyptr[16] = a0; at = 0x13468FF; v00 = 0xEF0100; v1 = 0xDF00; a0 = 0xEF01FF; *(long*) &db.polyptr[20] = at; *(long*) &db.polyptr[24] = v00; *(short*) &db.polyptr[28] = v1; *(long*) &db.polyptr[32] = a0; at = 0xDFFF; *(short*) &db.polyptr[36] = at; v00 = t3[0]; v00 |= 0x9000000; t3[0] = db.polyptr; *(long*) &db.polyptr[0] = v00; db.polyptr += 0x28; #endif return; } void GPU_SetScreenPosition(short x, short y)//5F360(<), 60040(<) { db.disp[0].screen.x = x; db.disp[0].screen.y = y; db.disp[1].screen.x = x; db.disp[1].screen.y = y; return; }<commit_msg>draw_rotate_sprite Clean<commit_after>#include "GPU.H" #include "CAMERA.H" #include "LOAD_LEV.H" #include "PROFILE.H" #include <assert.h> #include <LIBGPU.H> unsigned long GnFrameCounter = 19; unsigned long GnLastFrameCount = 19; struct PSXTEXTSTRUCT* psxtextinfo; struct PSXSPRITESTRUCT* psxspriteinfo; int rgbscaleme = 256; int gfx_debugging_mode; struct DB_STRUCT db; struct MMTEXTURE* RoomTextInfo; unsigned long GadwOrderingTables_V2[512]; static int LnFlipFrame; unsigned long GadwOrderingTables[5128]; unsigned long GadwPolygonBuffers[52260]; void GPU_UseOrderingTables(unsigned long* pBuffers, int nOTSize)//5DF68(<), 5F1C8(<) { db.order_table[0] = &pBuffers[0]; db.order_table[1] = &pBuffers[nOTSize]; db.nOTSize = nOTSize; db.pickup_order_table[0] = &db.disp[1]; db.pickup_order_table[1] = &GadwOrderingTables_V2[256]; #if 0 //Should be safe to use 32-bit ptrs tho db.order_table[0] = (unsigned long*)((unsigned long) pBuffers & 0xFFFFFF); db.order_table[1] = (unsigned long*)((unsigned long) &pBuffers[nOTSize] & 0xFFFFFF); db.nOTSize = nOTSize; db.pickup_order_table[0] = (unsigned long*)((unsigned long)&db.disp[1] & 0xFFFFFF); db.pickup_order_table[1] = (unsigned long*)((unsigned long)&GadwOrderingTables_V2[256] & 0xFFFFFF); #endif return; } void GPU_UsePolygonBuffers(unsigned long* pBuffers, int nPBSize)//5DFB0(<), { #if 1 db.nPBSize = nPBSize; db.poly_buffer[0] = &pBuffers[0]; db.poly_buffer[1] = &pBuffers[nPBSize]; #else db.nPBSize = nPBSize; db.poly_buffer[0] = (unsigned long*)((unsigned long)pBuffers & 0xFFFFFF); db.poly_buffer[1] = (unsigned long*)((unsigned long)&pBuffers[nPBSize] & 0xFFFFFF); #endif return; } void GPU_SyncBothScreens()//5F374(<), 60054(<) { DrawSync(0); db.current_buffer ^= 1; if (db.current_buffer != 0) { MoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y); //TODO: Verify ra += 0x10;! prolly else skip loc_5F3A8 (implemented but should be checked). } else { //loc_5F3A8 MoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y); } DrawSync(0); return; } void GPU_BeginScene()//5F0F0(<), 5FDD0(<) { db.ot = db.order_table[db.current_buffer]; db.polyptr = (char*)db.poly_buffer[db.current_buffer]; db.curpolybuf = (char*)db.poly_buffer[db.current_buffer]; db.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer]) + 26000; db.pickup_ot = db.pickup_order_table[db.current_buffer]; ClearOTagR(db.order_table[db.current_buffer], db.nOTSize); return; } int GPU_FlipNoIdle()//5E078(<), 5F264(<) { #if INTERNAL if (ProfileDraw) { ProfileRGB(255, 255, 255); ProfileAddOT(&db.ot[0]); }//loc_5E0B0 #endif DrawSync(0);//TODO confirm retail is sub_6B144 draw sync #if _INTERNAL if (ProfileDraw) { ProfileAddDrawOT(&db.ot[0]); }//loc_5E0D8 #endif LnFlipFrame = GnLastFrameCount; if (GnLastFrameCount < 2) { //loc_5E0F4 do { VSync(0); LnFlipFrame++; } while (LnFlipFrame < 2); } else { //loc_5E120 VSync(0); LnFlipFrame++; } //loc_5E138 //v0 = db.current_buffer; GnLastFrameCount = 0; PutDispEnv(&db.disp[db.current_buffer]); DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[db.current_buffer]); #if INTERNAL ProfileStartCount(); #endif db.current_buffer ^= 1; return LnFlipFrame; } void GPU_GetScreenPosition(short* x, short* y)//5F34C, ? { *x = db.disp[0].screen.x; *y = db.disp[0].screen.y; return; } /* PSX VRAM (H) * ----------- 512px * | TL | TR | | * ----------- v * | BL | BR | * ----------- *(W)1024px--> * */ void GPU_ClearVRAM()//5F2D0(<), 5FFB0(<) (F) { RECT r; DrawSync(0); VSync(0); //Clear TL r.x = 0; r.y = 0; r.w = 512; r.h = 256; clear_a_rect(&r); //Clear BL r.y = 256; clear_a_rect(&r); //Clear BR r.x = 512; clear_a_rect(&r); //Clear TR r.y = 0; clear_a_rect(&r); DrawSync(0); VSync(0); return; } void clear_a_rect(RECT* r)//5F334(<), 60014(<) (F) { ClearImage(r, 0, 48, 0); return; } //@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code. void GPU_FlipToBuffer(int buffer_index)//5F3C8(<), 600A8(<) (F) { DrawSync(0); VSync(0); buffer_index &= 1; if (buffer_index) { PutDispEnv(&db.disp[1]); db.current_buffer = buffer_index ^ 1; PutDrawEnv(&db.draw[1]); } else { PutDispEnv(&db.disp[0]); db.current_buffer = buffer_index ^ 1; PutDrawEnv(&db.draw[0]); } return; } void GPU_EndScene()//5DFDC(<), 5F23C(!) { #if 0 //int nPolys; //static int nWorstPolys; lui $v0, 0x4EC4 int a0 = &db.polyptr[0]; int v1 = &db.curpolybuf[0]; int v0 = 0x4EC4EC4F; a0 -= v1; v0 = a0 * v0; a0 >>= 31; v1 = psxtextinfo->u2v2pad; v0 >>= 4; v0 -= a0; if (v1 < v0) { u2v2pad = v0; }//loc_5E020 //loc_5E020 #endif OptimiseOTagR(&db.ot[0], db.nOTSize); #if 0 nop ProfileRGB(-1, -1, -1); a0 = db.nOTSize; do_gfx_debug_mode(&db.ot[db.nOTSize - 1]); ProfileRGB(0, -1, -1); #endif return; } long OptimiseOTagR(unsigned long* ot, int nOTSize)//86CC4(<), 88D08(<) { unsigned long* a1; unsigned long* a3; unsigned long v0; unsigned long* v1; long at = 0; if (nOTSize < 8) { return 0; } a1 = &ot[nOTSize - 1]; v1 = &ot[1]; v0 = a1[0]; //loc_86CE4 do { a1--; if ((unsigned long*)v0 == a1) { a3 = a1 - 1; if (a1 == ot) { return at; } //loc_86CF4 do { v0 = a1[0]; a1--; if (a1 == v1) { break; } at++; } while ((unsigned long*) v0 == a1); //loc_86D08 a3[0] = v0; } v0 = a1[0]; } while (a1 != ot); //loc_86D0C return at; } void draw_rotate_sprite(long a0, long a1, long a2)//5F134, 5FE14 { long t0; short* r_cossinptr; long t6; long t5; long t1; long t4; DelRotAng = (DelRotAng - 52) & 0xFFF; r_cossinptr = &rcossin_tbl[DelRotAng * 2]; t6 = ((-a2 / 2) * r_cossinptr[0]) / 4096; t5 = ((-a2 / 2) * r_cossinptr[1]) / 4096; *(long*) &db.polyptr[4] = 0x2C808080; *(long*) &db.polyptr[12] = 0; *(long*) &db.polyptr[20] = 0x1303F00; t0 = t6 - t5; a2 = -t6; t4 = a2 - t5; a2 += t5; t1 = t6 + t5; *(short*) &db.polyptr[8] = t0 + (t0 / 2) + a0; *(short*) &db.polyptr[10] = t5 + t6 + a1; *(short*) &db.polyptr[16] = t4 + (t4 / 2) + a0; *(short*) &db.polyptr[18] = -t5 + t6 + a1; *(short*) &db.polyptr[24] = t1 + (t1 / 2) + a0; *(short*) &db.polyptr[26] = (t5 - t6) + a1; *(short*) &db.polyptr[28] = 0x3F;//width/height of loading cd? *(short*) &db.polyptr[36] = 0x3F3F; *(short*) &db.polyptr[32] = a2 + (a2 / 2) + a0; *(short*) &db.polyptr[34] = a1 + (-t5 - t6); *(long*) &db.polyptr[0] = db.ot[0] | 0x09000000; db.ot[0] = &db.polyptr[0]; db.polyptr += 0x28;//sizeof(POLY_F3); * 2? *(long*) &db.polyptr[4] = 0x2C808080; *(long*) &db.polyptr[8] = 0x780100; *(long*) &db.polyptr[12] = 0x6800; *(long*) &db.polyptr[16] = 0x7801FF; *(long*) &db.polyptr[20] = 0x13468FF; *(long*) &db.polyptr[24] = 0xEF0100; *(short*) &db.polyptr[28] = 0xDF00; *(long*) &db.polyptr[32] = 0xEF01FF; *(short*) &db.polyptr[36] = 0xDFFF; *(long*) &db.polyptr[0] = db.ot[0] | 0x9000000; db.ot[0] = db.polyptr; db.polyptr += 0x28; return; } void GPU_SetScreenPosition(short x, short y)//5F360(<), 60040(<) { db.disp[0].screen.x = x; db.disp[0].screen.y = y; db.disp[1].screen.x = x; db.disp[1].screen.y = y; return; }<|endoftext|>
<commit_before>/*! \mainpage The QtSparql library \brief <center>unstable</center> \section Introduction <b>Description</b> QtSparql is a client-side library for accessing RDF stores. The query language for RDF stores is <a href="http://www.w3.org/TR/rdf-sparql-query/">SPARQL</a>. QtSparql takes in SPARQL queries, forwards them to the selected backend, and gives back the results of the query. It can return the results asynchronously if the backend supports asynchronous operations. QtSparql can connect to different backends. Currently the following backends exist: - QTRACKER for accessing <a href="http://projects.gnome.org/tracker/">Tracker</a> over D-Bus - QTRACKER_DIRECT for accessing <a href="http://projects.gnome.org/tracker/">Tracker</a> via direct database access and D-Bus - QSPARQL_ENDPOINT for accessing online RDF stores, e.g., <a href="http://dbpedia.org">DBpedia</a> - QVIRTUOSO backend for accessing <a href="http://docs.openlinksw.com/virtuoso/">Virtuoso</a> <b>List of classes QtSparql API provides:</b> <p><table width="100%"> <tr valign="top" bgcolor="#ffffff"><td><i>Class</i></td><td><i>Description</i></td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlConnection</b></td> <td>Interface for accessing an RDF store.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlConnectionOptions</b></td> <td>Encapsulates options given to QSparqlConnection. Some options are used only by some drivers.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlError</b></td><td>SPARQL error information.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlBinding</b></td><td>Handles a binding between a SPARQL query variable name and the value of the RDF node.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlQuery</b></td><td>Means of executing and manipulating SPARQL statements.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlQueryOptions</b></td> <td>Encapsulates query execution options given to QSparqlConnection::exec(const QSparqlQuery&, const QSparqlQueryOptions&) Some options are used only by some drivers.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlQueryModel</b></td><td>Read-only data model for SPARQL result sets.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlResultRow</b></td><td>Encapsulates a row in the results of a query.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlResult</b></td><td>Abstract interface for accessing the results of an executed QSparqlQuery.</td></tr> </table></p> \attention The QtSparql library is not yet stable; we make no promises about API / ABI compatibility! \section gettingstarted Getting started The following code snippets demonstrate how to retrieve data from a RDF database using QtSparql. - Create a QSparqlConnection object specifiying the backend you want to use. If necessary, specify the parameters by using QSparqlConnectionOptions and passing it to QSparqlConnection. E.g. to use tracker: \dontinclude simple/main.cpp \skipline QSparqlConnection E.g. to use DBpedia: \dontinclude dbpedia/main.cpp \skip QSparqlConnectionOptions \until QSPARQL_ENDPOINT - Construct a QSparqlQuery with the SPARQL query string. Specify the query type, if needed. E.g. \dontinclude simple/main.cpp \skipline QSparqlQuery or \dontinclude iteration/main.cpp \skip QSparqlQuery insert \until InsertStatement - Use QSparqlConnection::exec() to execute the query. It returns a pointer to QSparqlResult. E.g. \dontinclude simple/main.cpp \skipline QSparqlResult - You can then connect to the QSparqlResult::finished() and QSparqlResult::dataReady signals. - The QSparqlResult can be iterated over by using the following functions: QSparqlResult::first(), QSparqlResult::last(), QSparqlResult::next(), QSparqlResult::previous(), QSparqlResult::setPos(). The caller is responsible for deleting the QSparqlResult. E.g. \dontinclude simple/main.cpp \skip result->next \until toString - Data can be retrieved by using QSparqlResult::value(). The following classes are the most relevant for getting started with QSparql: - QSparqlConnection - QSparqlQuery - QSparqlResult - QSparqlQueryModel \section querymodels Query models The QSparqlQueryModel class provides a convienient, read-only, data model for SPARQL results which can be used to provide data to view classes such as QTableView. After creating the model, use QSparqlQueryModel::setQuery() to set the query for the connection, header data for the model can also be set using QSparqlQueryModel::setHeaderData(). E.g. \dontinclude querymodel/main.cpp \skip model; \until setHeaderData You can then use this in an a view class by using it's setModel() function. E.g. \dontinclude querymodel/main.cpp \skip *view \until model It is also easy to implement custom query models by reimplementing QSparqlQueryModel::data(), see the querymodel example for an example of this. \section connectionoptions Connection options supported by drivers QTRACKER_DIRECT driver supports the following connection options: - dataReadyInterval (int, default 1), controls the interval for emitting the dataReady signal. - maxThread (int), sets the maximum number of threads for the thread pool to use. If not set a default of number of cores * 2 will be used. - threadExpiry (int, default 2000), controls the expiry time (in milliseconds) of the threads created by the thread pool. QENDPOINT driver supports the following connection options: - hostName (QString) - path (QString) - port (int) - userName (QString) - password (QString) - networkAccessManager (QNetworkAccessManager*) - proxy (const QNetworkProxy&) - custom: "timeout" (int) (for virtuoso endpoints) - custom: "maxrows" (int) (for virtuoso endpoints) QVIRTUOSO driver supports the following connection options: - hostName (QString) - port (int) - userName (QString) - password (QString) - databaseName (QString) For setting custom options, use QSparqlConnectionOptions::setOption() and give the option name as a string, followed by the value. Other options can be set using QSparqlConnectionOptions::setOption(), however it is preferable to use the convinence functions in QSparqlConnectionOptions, as these provide additional error checking. \section connectionfeatures Connection features The following table describes the features supported by each driver. The features can be queried with QSparqlConnection::hasFeature(). <table> <tr> <td></td> <th>QuerySize</th> <th>DefaultGraph</th> <th>AskQueries</th> <th>ConstructQueries</th> <th>UpdateQueries</th> <th>SyncExec</th> <th>AsyncExec</th> </tr> <tr> <th>QTRACKER</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> <td>No</td> <td>Yes</td> </tr> <tr> <th>QTRACKER_DIRECT</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>No</td> </tr> <tr> <th>QSPARQL_ENDPOINT</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> </tr> <tr> <th>QVIRTUOSO</th> <td>Yes</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No (*)</td> <td>No</td> </tr> </table> (*) The QVIRTUOSO driver is natively synchronous, but support for syncExec directly is not currently implemented. \section backendspecific Accessing backend-specific functionalities QtSparql doesn't offer backend-specific functionalities. For that purpose, there are separate add-on libraries, e.g., libqtsparql-tracker-extensions. */ <commit_msg>Add QTRACKER_DIRECT specific information<commit_after>/*! \mainpage The QtSparql library \brief <center>unstable</center> \section Introduction <b>Description</b> QtSparql is a client-side library for accessing RDF stores. The query language for RDF stores is <a href="http://www.w3.org/TR/rdf-sparql-query/">SPARQL</a>. QtSparql takes in SPARQL queries, forwards them to the selected backend, and gives back the results of the query. It can return the results asynchronously if the backend supports asynchronous operations. QtSparql can connect to different backends. Currently the following backends exist: - QTRACKER for accessing <a href="http://projects.gnome.org/tracker/">Tracker</a> over D-Bus - QTRACKER_DIRECT for accessing <a href="http://projects.gnome.org/tracker/">Tracker</a> via direct database access and D-Bus. See the \ref trackerdirectspecific "specific useage section" for more information - QSPARQL_ENDPOINT for accessing online RDF stores, e.g., <a href="http://dbpedia.org">DBpedia</a> - QVIRTUOSO backend for accessing <a href="http://docs.openlinksw.com/virtuoso/">Virtuoso</a> <b>List of classes QtSparql API provides:</b> <p><table width="100%"> <tr valign="top" bgcolor="#ffffff"><td><i>Class</i></td><td><i>Description</i></td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlConnection</b></td> <td>Interface for accessing an RDF store.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlConnectionOptions</b></td> <td>Encapsulates options given to QSparqlConnection. Some options are used only by some drivers.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlError</b></td><td>SPARQL error information.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlBinding</b></td><td>Handles a binding between a SPARQL query variable name and the value of the RDF node.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlQuery</b></td><td>Means of executing and manipulating SPARQL statements.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlQueryOptions</b></td> <td>Encapsulates query execution options given to QSparqlConnection::exec(const QSparqlQuery&, const QSparqlQueryOptions&) Some options are used only by some drivers.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlQueryModel</b></td><td>Read-only data model for SPARQL result sets.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlResultRow</b></td><td>Encapsulates a row in the results of a query.</td></tr> <tr valign="top" bgcolor="#f0f0f0"><td><b>QSparqlResult</b></td><td>Abstract interface for accessing the results of an executed QSparqlQuery.</td></tr> </table></p> \attention The QtSparql library is not yet stable; we make no promises about API / ABI compatibility! \section gettingstarted Getting started The following code snippets demonstrate how to retrieve data from a RDF database using QtSparql. - Create a QSparqlConnection object specifiying the backend you want to use. If necessary, specify the parameters by using QSparqlConnectionOptions and passing it to QSparqlConnection. E.g. to use tracker: \dontinclude simple/main.cpp \skipline QSparqlConnection E.g. to use DBpedia: \dontinclude dbpedia/main.cpp \skip QSparqlConnectionOptions \until QSPARQL_ENDPOINT - Construct a QSparqlQuery with the SPARQL query string. Specify the query type, if needed. E.g. \dontinclude simple/main.cpp \skipline QSparqlQuery or \dontinclude iteration/main.cpp \skip QSparqlQuery insert \until InsertStatement - Use QSparqlConnection::exec() to execute the query. It returns a pointer to QSparqlResult. E.g. \dontinclude simple/main.cpp \skipline QSparqlResult - You can then connect to the QSparqlResult::finished() and QSparqlResult::dataReady signals. - The QSparqlResult can be iterated over by using the following functions: QSparqlResult::first(), QSparqlResult::last(), QSparqlResult::next(), QSparqlResult::previous(), QSparqlResult::setPos(). The caller is responsible for deleting the QSparqlResult. E.g. \dontinclude simple/main.cpp \skip result->next \until toString - Data can be retrieved by using QSparqlResult::value(). The following classes are the most relevant for getting started with QSparql: - QSparqlConnection - QSparqlQuery - QSparqlResult - QSparqlQueryModel \section querymodels Query models The QSparqlQueryModel class provides a convienient, read-only, data model for SPARQL results which can be used to provide data to view classes such as QTableView. After creating the model, use QSparqlQueryModel::setQuery() to set the query for the connection, header data for the model can also be set using QSparqlQueryModel::setHeaderData(). E.g. \dontinclude querymodel/main.cpp \skip model; \until setHeaderData You can then use this in an a view class by using it's setModel() function. E.g. \dontinclude querymodel/main.cpp \skip *view \until model It is also easy to implement custom query models by reimplementing QSparqlQueryModel::data(), see the querymodel example for an example of this. \section connectionoptions Connection options supported by drivers QTRACKER_DIRECT driver supports the following connection options: - dataReadyInterval (int, default 1), controls the interval for emitting the dataReady signal. - maxThread (int), sets the maximum number of threads for the thread pool to use. If not set a default of number of cores * 2 will be used. - threadExpiry (int, default 2000), controls the expiry time (in milliseconds) of the threads created by the thread pool. QENDPOINT driver supports the following connection options: - hostName (QString) - path (QString) - port (int) - userName (QString) - password (QString) - networkAccessManager (QNetworkAccessManager*) - proxy (const QNetworkProxy&) - custom: "timeout" (int) (for virtuoso endpoints) - custom: "maxrows" (int) (for virtuoso endpoints) QVIRTUOSO driver supports the following connection options: - hostName (QString) - port (int) - userName (QString) - password (QString) - databaseName (QString) For setting custom options, use QSparqlConnectionOptions::setOption() and give the option name as a string, followed by the value. Other options can be set using QSparqlConnectionOptions::setOption(), however it is preferable to use the convinence functions in QSparqlConnectionOptions, as these provide additional error checking. \section connectionfeatures Connection features The following table describes the QSparclConnection::Feature support of each driver. The features can be queried with QSparqlConnection::hasFeature(). <table> <tr> <td></td> <th>QuerySize</th> <th>DefaultGraph</th> <th>AskQueries</th> <th>ConstructQueries</th> <th>UpdateQueries</th> <th>SyncExec</th> <th>AsyncExec</th> </tr> <tr> <th>QTRACKER</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> <td>No</td> <td>Yes</td> </tr> <tr> <th>QTRACKER_DIRECT</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>No</td> </tr> <tr> <th>QSPARQL_ENDPOINT</th> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> </tr> <tr> <th>QVIRTUOSO</th> <td>Yes</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No (*)</td> <td>No</td> </tr> </table> (*) The QVIRTUOSO driver is natively synchronous, but support for syncExec directly is not currently implemented. \section trackerdirectspecific QTRACKER_DIRECT specific useage There are two ways to use the QTRACKER_DIRECT driver, synchronously using QSparqlConnection::syncExec(), and asynchronously using QSparqlConnection::exec(). The result behaviour is different, and supports different features, depending on the method used. The following table describes the QSparqlResult::Feature support of each method. <table> <tr> <td></td> <th>QuerySize</th> <th>ForwardOnly</th> <th>Sync</th> </tr> <tr> <th>exec()</th> <td>Yes</td> <td>No</td> <td>No</td> </tr> <tr> <th>syncExec()</th> <td>No</td> <td>Yes</td> <td>Yes</td> </tr> </table> When using synchronous execution, it is important to fully use the results returned before making another query, either synchronously or asynchronously, by using QSparqlResult::next until it returns false. If you fail to do this, any new results that may have been added after your original query will not be included in any subsequent queries you make. \section backendspecific Accessing backend-specific functionalities QtSparql doesn't offer backend-specific functionalities. For that purpose, there are separate add-on libraries, e.g., libqtsparql-tracker-extensions. */ <|endoftext|>
<commit_before>// Copyright (c) 2012-2015 Dano Pernis // See LICENSE for details #include "ssa.h" namespace hcc { namespace ssa { namespace { struct congruence_classes { std::map<argument, reg> classes; std::function<void(argument&)> replacer() { return [&](argument& arg) { if (!arg.is_reg()) { return; } auto it = classes.find(arg); if (it != classes.end()) { arg = it->second; } }; } }; // Implements "Method I" from paper by Sreedhar et al. // "Translating Out of Static Single Assignment Form" // FIXME copies are not parallel void naive_copy_insertion(subroutine& s, congruence_classes& cc) { // worklist of MOV instructions to be inserted at the end of basic block, // indexed by basic block std::map<label, instruction_list> worklist; // pass 1: fill worklist and insert primed copy s.for_each_bb([&](basic_block& bb) { for (auto i = bb.instructions.begin(), e = bb.instructions.end(); i != e; ++i) { if (i->type != instruction_type::PHI) continue; auto arg = i->arguments.begin(); // invent a new primed name const auto base = s.create_reg(); s.add_debug(base, "phi_dst_reg", *arg); // insert MOV after PHI bb.instructions.insert(++decltype(i)(i), instruction(instruction_type::MOV, {*arg, base})); cc.classes.emplace(base, base); cc.classes.emplace(*arg, base); // rename PHI's dest *arg++ = base; while (arg != i->arguments.end()) { auto label = *arg++; auto value = *arg; const auto name = s.create_reg(); s.add_debug(name, "phi_src_reg", base); s.add_debug(name, "phi_src_label", label); // insert MOV into worklist worklist[label.get_label()].emplace_back( instruction(instruction_type::MOV, {name, value})); cc.classes.emplace(name, base); // rename PHI's src *arg++ = name; } } }); // pass 2: paste instructions from worklist at the end of respective basic block s.for_each_bb([&](basic_block& bb) { bb.instructions.splice(--bb.instructions.end(), worklist[bb.name]); }); } // live(x) ... set of statements were x is live // live(a) intersects live(b) ... def(a) in live(b) or def(b) in live(a) // V(x) ... V(b) = V(a) if b <- a // V(b) = b otherwise // a interfere b ... live(a) intersects live(b) and V(a) != V(b) bool interfere(const argument& a, const argument& b, subroutine& s) { assert(a.is_reg() && b.is_reg()); bool def_a_in_live_b = false; bool def_b_in_live_a = false; bool live_a = false; bool live_b = false; std::map<std::string, std::string> V; // value of variable // TODO investigate if domtree is really needed // TODO live ranges are probably overestimated at the end s.for_each_bb_in_domtree_preorder([&](basic_block& block) { for (auto& instr : block.instructions) { // live ranges instr.def_apply([&](argument& def) { if (def == a) { live_a = true; if (live_b) def_a_in_live_b = true; } else if (def == b) { live_b = true; if (live_a) def_b_in_live_a = true; } }); // values if (instr.type == instruction_type::MOV) { auto s0 = instr.arguments[0].save_fast(); auto s1 = instr.arguments[1].save_fast(); V[std::move(s0)] = V[std::move(s1)]; } else { instr.def_apply([&](argument& arg) { auto s0 = arg.save_fast(); auto s1 = instr.save_fast(); V[std::move(s0)] = std::move(s1); }); } } }); const bool intersect = def_a_in_live_b || def_b_in_live_a; auto sa = a.save_fast(); auto sb = b.save_fast(); const bool differ_in_value = V.at(sa) != V.at(sb); return intersect && differ_in_value; } } // namespace { // Inspired by paper // "Revisiting Out-of-SSA Translation for Correctness, Code Quality, and Efficiency" void subroutine::ssa_deconstruct() { recompute_dominance(); congruence_classes cc; naive_copy_insertion(*this, cc); // incidental classes, rising from the code for_each_bb([&](basic_block& bb) { for (auto& instr : bb.instructions) { if (instr.type == instruction_type::MOV) { auto& dest = instr.arguments[0]; auto& src = instr.arguments[1]; const bool has_src_class = cc.classes.count(src) > 0; const bool has_dest_class = cc.classes.count(dest) > 0; if (has_src_class && has_dest_class && cc.classes.at(src) == cc.classes.at(dest)) continue; if (src.is_reg() && dest.is_reg()) { if (!interfere(src, dest, *this)) { if (!has_src_class && !has_dest_class) { const auto r = create_reg(); add_debug(r, "congruence_class"); cc.classes.emplace(src, r); cc.classes.emplace(dest, r); } else if (has_src_class && has_dest_class) { auto keep_class = cc.classes.at(src); auto remove_class = cc.classes.at(dest); for (auto& kv : cc.classes) { if (kv.second == remove_class) kv.second = keep_class; } } } } } } }); // pass 2: remove phis, replace names, remove nop moves // FIXME materialize parallel moves here, do not add them in the first place for_each_bb([&](basic_block& bb) { for (auto i = bb.instructions.begin(), e = bb.instructions.end(); i != e;) { if (i->type == instruction_type::PHI) { i = bb.instructions.erase(i); } else { i->def_apply(cc.replacer()); i->use_apply(cc.replacer()); if (i->type == instruction_type::MOV && i->arguments[0] == i->arguments[1]) { i = bb.instructions.erase(i); } else { ++i; } } } }); } } // namespace ssa { } // namespace hcc { <commit_msg>Optimize interference computation<commit_after>// Copyright (c) 2012-2015 Dano Pernis // See LICENSE for details #include "ssa.h" namespace hcc { namespace ssa { namespace { struct congruence_classes { std::map<argument, reg> classes; std::function<void(argument&)> replacer() { return [&](argument& arg) { if (!arg.is_reg()) { return; } auto it = classes.find(arg); if (it != classes.end()) { arg = it->second; } }; } }; // Implements "Method I" from paper by Sreedhar et al. // "Translating Out of Static Single Assignment Form" // FIXME copies are not parallel void naive_copy_insertion(subroutine& s, congruence_classes& cc) { // worklist of MOV instructions to be inserted at the end of basic block, // indexed by basic block std::map<label, instruction_list> worklist; // pass 1: fill worklist and insert primed copy s.for_each_bb([&](basic_block& bb) { for (auto i = bb.instructions.begin(), e = bb.instructions.end(); i != e; ++i) { if (i->type != instruction_type::PHI) continue; auto arg = i->arguments.begin(); // invent a new primed name const auto base = s.create_reg(); s.add_debug(base, "phi_dst_reg", *arg); // insert MOV after PHI bb.instructions.insert(++decltype(i)(i), instruction(instruction_type::MOV, {*arg, base})); cc.classes.emplace(base, base); cc.classes.emplace(*arg, base); // rename PHI's dest *arg++ = base; while (arg != i->arguments.end()) { auto label = *arg++; auto value = *arg; const auto name = s.create_reg(); s.add_debug(name, "phi_src_reg", base); s.add_debug(name, "phi_src_label", label); // insert MOV into worklist worklist[label.get_label()].emplace_back( instruction(instruction_type::MOV, {name, value})); cc.classes.emplace(name, base); // rename PHI's src *arg++ = name; } } }); // pass 2: paste instructions from worklist at the end of respective basic block s.for_each_bb([&](basic_block& bb) { bb.instructions.splice(--bb.instructions.end(), worklist[bb.name]); }); } // Determine if two registers *a* and *b* interfere in subroutine *s* // // Interfering registers have intersecting live ranges and different values: // // live(x) ... set of statements where x is live // live(a) intersects live(b) ... def(a) in live(b) or def(b) in live(a) // V(x) ... V(b) = V(a) if b <- a // V(b) = b otherwise // a interfere b ... live(a) intersects live(b) and V(a) != V(b) bool interfere(const reg& a, const reg& b, subroutine& s) { bool def_a_in_live_b = false; bool def_b_in_live_a = false; bool live_a = false; bool live_b = false; // At this point, code is still in SSA, so value of each register // is determined solely by its defining instruction. What is more, // we can use pointer here because nothing gets reallocated. // TODO use const *s* to prove that pointer usage is indeed safe. std::map<reg, const instruction*> value; // TODO investigate if domtree is really needed // TODO live ranges are probably overestimated at the end s.for_each_bb_in_domtree_preorder([&](basic_block& block) { for (auto& instr : block.instructions) { // live ranges instr.def_apply([&](argument& def) { assert (def.is_reg()); if (def.get_reg() == a) { live_a = true; if (live_b) def_a_in_live_b = true; } else if (def == b) { live_b = true; if (live_a) def_b_in_live_a = true; } }); // values if (instr.type == instruction_type::MOV) { if (instr.arguments[1].is_reg()) { value.emplace(instr.arguments[0].get_reg(), value.at(instr.arguments[1].get_reg())); } else { value.emplace(instr.arguments[0].get_reg(), &instr); } } else { instr.def_apply([&](argument& arg) { assert (arg.is_reg()); value.emplace(arg.get_reg(), &instr); }); } } }); const bool intersect = def_a_in_live_b || def_b_in_live_a; const bool differ_in_value = value.at(a) != value.at(b); return intersect && differ_in_value; } } // namespace { // Inspired by paper // "Revisiting Out-of-SSA Translation for Correctness, Code Quality, and Efficiency" void subroutine::ssa_deconstruct() { recompute_dominance(); congruence_classes cc; naive_copy_insertion(*this, cc); // incidental classes, rising from the code for_each_bb([&](basic_block& bb) { for (auto& instr : bb.instructions) { if (instr.type == instruction_type::MOV) { auto& dest = instr.arguments[0]; auto& src = instr.arguments[1]; const bool has_src_class = cc.classes.count(src) > 0; const bool has_dest_class = cc.classes.count(dest) > 0; if (has_src_class && has_dest_class && cc.classes.at(src) == cc.classes.at(dest)) continue; if (src.is_reg() && dest.is_reg()) { if (!interfere(src.get_reg(), dest.get_reg(), *this)) { if (!has_src_class && !has_dest_class) { const auto r = create_reg(); add_debug(r, "congruence_class"); cc.classes.emplace(src, r); cc.classes.emplace(dest, r); } else if (has_src_class && has_dest_class) { auto keep_class = cc.classes.at(src); auto remove_class = cc.classes.at(dest); for (auto& kv : cc.classes) { if (kv.second == remove_class) kv.second = keep_class; } } } } } } }); // pass 2: remove phis, replace names, remove nop moves // FIXME materialize parallel moves here, do not add them in the first place for_each_bb([&](basic_block& bb) { for (auto i = bb.instructions.begin(), e = bb.instructions.end(); i != e;) { if (i->type == instruction_type::PHI) { i = bb.instructions.erase(i); } else { i->def_apply(cc.replacer()); i->use_apply(cc.replacer()); if (i->type == instruction_type::MOV && i->arguments[0] == i->arguments[1]) { i = bb.instructions.erase(i); } else { ++i; } } } }); } } // namespace ssa { } // namespace hcc { <|endoftext|>
<commit_before>// Copyright 2018 Google Inc. 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 <gmock/gmock.h> #include <gtest/gtest.h> #include <string> #include "class_names.h" #include "common_action_mocks.h" #include "i_dbg_object_factory_mock.h" #include "i_eval_coordinator_mock.h" #include "string_evaluator.h" #include "type_signature.h" using google_cloud_debugger::ConvertStringToWCharPtr; using google_cloud_debugger::DbgObject; using google_cloud_debugger::StringEvaluator; using google_cloud_debugger::TypeSignature; using std::string; using ::testing::_; using ::testing::Return; using ::testing::SetArgPointee; using ::testing::SetArrayArgument; namespace google_cloud_debugger_test { // Test Fixture for DbgString. class StringEvaluatorTest : public ::testing::Test { protected: virtual void SetUp() {} // Sets up IEvalCoordinator for mock call. virtual void SetUpEvalCoordinator() { EXPECT_CALL(eval_coordinator_mock_, CreateEval(_)) .Times(1) .WillRepeatedly( DoAll(SetArgPointee<0>(&debug_eval_mock_), Return(S_OK))); EXPECT_CALL(eval_coordinator_mock_, WaitForEval(_, &debug_eval_mock_, _)) .Times(1) .WillRepeatedly( DoAll(SetArgPointee<2>(&debug_string_mock_), Return(S_OK))); EXPECT_CALL(debug_eval_mock_, NewString(_)) .Times(1) .WillRepeatedly(Return(S_OK)); } // Sets up object factory for object creation. virtual void SetUpObjFactory() { EXPECT_CALL(object_factory_mock_, CreateDbgObject(&debug_string_mock_, _, _, _)) .Times(1) .WillRepeatedly(Return(S_OK)); } // Mock of IEvalCoordinator used for evaluate. IEvalCoordinatorMock eval_coordinator_mock_; // Mock used for object creation. IDbgObjectFactoryMock object_factory_mock_; // Mock eval returned by IEvalCoordinatorMock. ICorDebugEvalMock debug_eval_mock_; // Debug String returned by IEvalCoordinatorMock. ICorDebugStringValueMock debug_string_mock_; // Content of the string. string string_content_ = "String Content"; }; // Tests Compile function of DbgString. // This function returns S_OK without anywork. TEST_F(StringEvaluatorTest, Compile) { StringEvaluator evaluator(string_content_); EXPECT_EQ(evaluator.Compile(nullptr, nullptr, nullptr), S_OK); } // Tests that GetStaticType returns string type. TEST_F(StringEvaluatorTest, GetStaticType) { StringEvaluator evaluator(string_content_); TypeSignature type_sig = evaluator.GetStaticType(); EXPECT_EQ(type_sig.cor_type, CorElementType::ELEMENT_TYPE_STRING); EXPECT_EQ(type_sig.type_name, google_cloud_debugger::kStringClassName); } // Tests that Evaluate function creates a string. TEST_F(StringEvaluatorTest, Evaluate) { StringEvaluator evaluator(string_content_); SetUpEvalCoordinator(); SetUpObjFactory(); std::shared_ptr<DbgObject> result; std::ostringstream err_stream; EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, &object_factory_mock_, &err_stream), S_OK); } // Tests that error cases for Evaluate function. TEST_F(StringEvaluatorTest, EvaluateError) { StringEvaluator evaluator(string_content_); std::shared_ptr<DbgObject> result; std::ostringstream err_stream; // Null tests. EXPECT_EQ(evaluator.Evaluate(nullptr, &eval_coordinator_mock_, &object_factory_mock_, &err_stream), E_INVALIDARG); EXPECT_EQ( evaluator.Evaluate(&result, nullptr, &object_factory_mock_, &err_stream), E_INVALIDARG); EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, nullptr, &err_stream), E_INVALIDARG); EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, &object_factory_mock_, nullptr), E_INVALIDARG); { // Tests that Evaluate fails if we cannot create ICorDebugEval. EXPECT_CALL(eval_coordinator_mock_, CreateEval(_)) .Times(1) .WillRepeatedly(Return(E_ACCESSDENIED)); EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, &object_factory_mock_, &err_stream), E_ACCESSDENIED); } { // Tests that Evaluate fails if we cannot Object Factory fails. SetUpEvalCoordinator(); EXPECT_CALL(object_factory_mock_, CreateDbgObject(&debug_string_mock_, _, _, _)) .Times(1) .WillRepeatedly(Return(CORDBG_E_PROCESS_TERMINATED)); EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, &object_factory_mock_, &err_stream), CORDBG_E_PROCESS_TERMINATED); } } } // namespace google_cloud_debugger_test <commit_msg>Address PR comments<commit_after>// Copyright 2018 Google Inc. 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 <gmock/gmock.h> #include <gtest/gtest.h> #include <string> #include "class_names.h" #include "common_action_mocks.h" #include "dbg_string.h" #include "i_dbg_object_factory_mock.h" #include "i_eval_coordinator_mock.h" #include "string_evaluator.h" #include "type_signature.h" #include "error_messages.h" using google_cloud_debugger::ConvertStringToWCharPtr; using google_cloud_debugger::DbgObject; using google_cloud_debugger::DbgString; using google_cloud_debugger::StringEvaluator; using google_cloud_debugger::TypeSignature; using std::string; using ::testing::_; using ::testing::Return; using ::testing::SetArgPointee; using ::testing::SetArrayArgument; namespace google_cloud_debugger_test { // Test Fixture for StringEvaluator. class StringEvaluatorTest : public ::testing::Test { protected: virtual void SetUp() {} // Sets up IEvalCoordinator for mock call. virtual void SetUpEvalCoordinator() { EXPECT_CALL(eval_coordinator_mock_, CreateEval(_)) .Times(1) .WillRepeatedly( DoAll(SetArgPointee<0>(&debug_eval_mock_), Return(S_OK))); EXPECT_CALL(eval_coordinator_mock_, WaitForEval(_, &debug_eval_mock_, _)) .Times(1) .WillRepeatedly( DoAll(SetArgPointee<2>(&debug_string_mock_), Return(S_OK))); EXPECT_CALL(debug_eval_mock_, NewString(_)) .Times(1) .WillRepeatedly(Return(S_OK)); } // Sets up object factory for object creation. virtual void SetUpObjFactory() { EXPECT_CALL(object_factory_mock_, CreateDbgObject(&debug_string_mock_, _, _, _)) .Times(1) .WillRepeatedly(Return(S_OK)); } // Mock of IEvalCoordinator used for evaluate. IEvalCoordinatorMock eval_coordinator_mock_; // Mock used for object creation. IDbgObjectFactoryMock object_factory_mock_; // Mock eval returned by IEvalCoordinatorMock. ICorDebugEvalMock debug_eval_mock_; // Debug String returned by IEvalCoordinatorMock. ICorDebugStringValueMock debug_string_mock_; // Content of the string. string string_content_ = "String Content"; // Error stream. std::ostringstream err_stream_; }; // Tests Compile function of DbgString. // This function returns S_OK without anywork. TEST_F(StringEvaluatorTest, Compile) { StringEvaluator evaluator(string_content_); EXPECT_EQ(evaluator.Compile(nullptr, nullptr, nullptr), S_OK); } // Tests that GetStaticType returns string type. TEST_F(StringEvaluatorTest, GetStaticType) { StringEvaluator evaluator(string_content_); TypeSignature type_sig = evaluator.GetStaticType(); EXPECT_EQ(type_sig.cor_type, CorElementType::ELEMENT_TYPE_STRING); EXPECT_EQ(type_sig.type_name, google_cloud_debugger::kStringClassName); } // Tests that Evaluate function creates a string. TEST_F(StringEvaluatorTest, Evaluate) { StringEvaluator evaluator(string_content_); SetUpEvalCoordinator(); SetUpObjFactory(); std::shared_ptr<DbgObject> result; std::ostringstream err_stream; EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, &object_factory_mock_, &err_stream), S_OK); } // Tests null error cases for Evaluate function. TEST_F(StringEvaluatorTest, EvaluateError) { StringEvaluator evaluator(string_content_); std::shared_ptr<DbgObject> result; EXPECT_EQ(evaluator.Evaluate(nullptr, &eval_coordinator_mock_, &object_factory_mock_, &err_stream_), E_INVALIDARG); EXPECT_EQ( evaluator.Evaluate(&result, nullptr, &object_factory_mock_, &err_stream_), E_INVALIDARG); EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, nullptr, &err_stream_), E_INVALIDARG); EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, &object_factory_mock_, nullptr), E_INVALIDARG); } // Tests that Evaluate fails if we cannot create ICorDebugEval. TEST_F(StringEvaluatorTest, EvaluateErrorEvalCoordinator) { StringEvaluator evaluator(string_content_); std::shared_ptr<DbgObject> result; EXPECT_CALL(eval_coordinator_mock_, CreateEval(_)) .Times(1) .WillRepeatedly(Return(E_ACCESSDENIED)); EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, &object_factory_mock_, &err_stream_), E_ACCESSDENIED); EXPECT_EQ(err_stream_.str(), google_cloud_debugger::kFailedEvalCreation.c_str()); } // Tests that Evaluate fails if the IDbgObjectFactory cannot create // a new object. TEST_F(StringEvaluatorTest, EvaluateErrorObjCreation) { StringEvaluator evaluator(string_content_); std::shared_ptr<DbgObject> result; SetUpEvalCoordinator(); EXPECT_CALL(object_factory_mock_, CreateDbgObject(&debug_string_mock_, _, _, _)) .Times(1) .WillRepeatedly(Return(CORDBG_E_PROCESS_TERMINATED)); EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, &object_factory_mock_, &err_stream_), CORDBG_E_PROCESS_TERMINATED); EXPECT_EQ(err_stream_.str(), google_cloud_debugger::kFailedToCreateDbgObject.c_str()); } } // namespace google_cloud_debugger_test <|endoftext|>
<commit_before>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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. */ #ifndef RESEMBLA_ELIMINATOR_HPP #define RESEMBLA_ELIMINATOR_HPP #include <string> #include <vector> #include <map> #include "string_util.hpp" namespace resembla { template<typename string_type, typename bitvector_type = uint64_t> struct Eliminator { using size_type = typename string_type::size_type; using symbol_type = typename string_type::value_type; using distance_type = int; Eliminator(string_type const& pattern = string_type()) { init(pattern); } void init(string_type const& pattern) { this->pattern = pattern; if(pattern.empty()){ return; } pattern_length = pattern.size(); block_size = ((pattern_length - 1) >> bit_offset<bitvector_type>()) + 1; rest_bits = pattern_length - (block_size - 1) * bit_width<bitvector_type>(); sink = bitvector_type{1} << (rest_bits - 1); constructPM(); zeroes.resize(block_size, 0); work.resize(block_size); } void operator()(std::vector<string_type>& candidates, size_type k) { using index_distance = std::pair<size_type, distance_type>; // calculate scores std::vector<index_distance> work(candidates.size()); for(size_type i = 0; i < work.size(); ++i){ work[i].first = i; work[i].second = -distance(candidates[i]); } // sort partially to obtain top-k elements std::nth_element(std::begin(work), std::begin(work) + k, std::end(work), [](const index_distance& a, const index_distance& b) -> bool{ return a.second > b.second; }); // ensure that work[i].first < work[j].first if i < j < k std::partial_sort(std::begin(work), std::begin(work) + k, std::begin(work) + k, [](const index_distance& a, const index_distance& b) -> bool{ return a.first < b.first; }); #ifdef DEBUG std::cerr << "narrow " << work.size() << " strings" << std::endl; for(size_type i = 0; i < k; ++i){ std::cerr << cast_string<std::string>(candidates[work[i].first]) << ": " << work[i].second << std::endl; } #endif // sort original list for(size_type i = 0; i < k; ++i){ std::swap(candidates[i], candidates[work[i].first]); } candidates.erase(std::begin(candidates) + k, std::end(candidates)); } protected: string_type pattern; size_type pattern_length; size_type block_size; size_type rest_bits; bitvector_type sink; std::vector<std::pair<symbol_type, std::vector<bitvector_type>>> PM; std::vector<bitvector_type> zeroes; struct WorkData { bitvector_type D0; bitvector_type HP; bitvector_type HN; bitvector_type VP; bitvector_type VN; void reset() { D0 = HP = HN = VN = 0; VP = ~(bitvector_type{0}); } }; mutable std::vector<WorkData> work; template<typename Integer> static constexpr int bit_width() { return 8 * sizeof(Integer); } static constexpr int bit_offset(int w) { return w < 2 ? 0 : (bit_offset(w >> 1) + 1); } template<typename Integer> static constexpr int bit_offset() { return bit_offset(bit_width<Integer>()); } template<typename key_type, typename value_type> const value_type& find_value(const std::vector<std::pair<key_type, value_type>>& data, const key_type c, const value_type& default_value) const { size_type l = 0, r = data.size(); while(r - l > 8){ auto i = (l + r) / 2; if(data[i].first < c){ l = i + 1; } else if(data[i].first > c){ r = i; } else{ return data[i].second; } } for(size_type i = l; i < r; ++i){ if(data[i].first == c){ return data[i].second; } } return default_value; } void constructPM() { std::map<symbol_type, std::vector<bitvector_type>> PM_work; for(size_type i = 0; i < block_size - 1; ++i){ for(size_type j = 0; j < bit_width<bitvector_type>(); ++j){ if(PM_work[pattern[i * bit_width<bitvector_type>() + j]].empty()){ PM_work[pattern[i * bit_width<bitvector_type>() + j]].resize(block_size, 0); } PM_work[pattern[i * bit_width<bitvector_type>() + j]][i] |= bitvector_type{1} << j; } } for(size_type i = 0; i < rest_bits; ++i){ if(PM_work[pattern[(block_size - 1) * bit_width<bitvector_type>() + i]].empty()){ PM_work[pattern[(block_size - 1) * bit_width<bitvector_type>() + i]].resize(block_size, 0); } PM_work[pattern[(block_size - 1) * bit_width<bitvector_type>() + i]].back() |= bitvector_type{1} << i; } PM.clear(); for(const auto& p: PM_work){ PM.push_back(p); } } distance_type distance_sp(string_type const &text) const { auto& w = work.front(); w.reset(); for(size_type i = 0; i < pattern_length; ++i){ w.VP |= bitvector_type{1} << i; } distance_type D = pattern_length; for(auto c: text){ auto X = find_value(PM, c, zeroes).front() | w.VN; w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X; w.HP = w.VN | ~(w.VP | w.D0); w.HN = w.VP & w.D0; X = (w.HP << 1) | 1; w.VP = (w.HN << 1) | ~(X | w.D0); w.VN = X & w.D0; if(w.HP & sink){ ++D; } else if(w.HN & sink){ --D; } } return D; } distance_type distance_lp(string_type const &text) const { constexpr bitvector_type msb = bitvector_type{1} << (bit_width<bitvector_type>() - 1); for(auto& w: work){ w.reset(); } for(size_type i = 0; i < rest_bits; ++i){ work.back().VP |= bitvector_type{1} << i; } distance_type D = pattern_length; for(auto c: text){ const auto& PMc = find_value(PM, c, zeroes); for(size_type r = 0; r < block_size; ++r){ auto& w = work[r]; auto X = PMc[r]; if(r > 0 && (work[r - 1].HN & msb)){ X |= 1; } w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN; w.HP = w.VN | ~(w.VP | w.D0); w.HN = w.VP & w.D0; X = w.HP << 1; if(r == 0 || work[r - 1].HP & msb){ X |= 1; } w.VP = (w.HN << 1) | ~(X | w.D0); if(r > 0 && (work[r - 1].HN & msb)){ w.VP |= 1; } w.VN = X & w.D0; } if(work.back().HP & sink){ ++D; } else if(work.back().HN & sink){ --D; } } return D; } distance_type distance(string_type const &text) const { if(text.empty()){ return pattern_length; } else if(pattern_length == 0){ return text.size(); } if(block_size == 1){ return distance_sp(text); } else{ return distance_lp(text); } } }; } #endif <commit_msg>add heuristics<commit_after>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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. */ #ifndef RESEMBLA_ELIMINATOR_HPP #define RESEMBLA_ELIMINATOR_HPP #include <string> #include <vector> #include <map> #include "string_util.hpp" namespace resembla { template<typename string_type, typename bitvector_type = uint64_t> struct Eliminator { using size_type = typename string_type::size_type; using symbol_type = typename string_type::value_type; using distance_type = int; Eliminator(string_type const& pattern = string_type()) { init(pattern); } void init(string_type const& pattern) { this->pattern = pattern; if(pattern.empty()){ return; } pattern_length = pattern.size(); block_size = ((pattern_length - 1) >> bit_offset<bitvector_type>()) + 1; rest_bits = pattern_length - (block_size - 1) * bit_width<bitvector_type>(); sink = bitvector_type{1} << (rest_bits - 1); constructPM(); zeroes.resize(block_size, 0); work.resize(block_size); } void operator()(std::vector<string_type>& candidates, size_type k) { using index_distance = std::pair<size_type, distance_type>; // calculate scores std::vector<index_distance> work(candidates.size()); for(size_type i = 0; i < work.size(); ++i){ work[i].first = i; work[i].second = -distance(candidates[i]); } // sort partially to obtain top-k elements std::nth_element(std::begin(work), std::begin(work) + k, std::end(work), [](const index_distance& a, const index_distance& b) -> bool{ return a.second > b.second; }); // ensure that work[i].first < work[j].first if i < j < k std::partial_sort(std::begin(work), std::begin(work) + k, std::begin(work) + k, [](const index_distance& a, const index_distance& b) -> bool{ return a.first < b.first; }); #ifdef DEBUG std::cerr << "narrow " << work.size() << " strings" << std::endl; for(size_type i = 0; i < k; ++i){ std::cerr << cast_string<std::string>(candidates[work[i].first]) << ": " << work[i].second << std::endl; } #endif // sort original list for(size_type i = 0; i < k; ++i){ std::swap(candidates[i], candidates[work[i].first]); } candidates.erase(std::begin(candidates) + k, std::end(candidates)); } protected: string_type pattern; size_type pattern_length; symbol_type c_min, c_max; size_type block_size; size_type rest_bits; bitvector_type sink; std::vector<std::pair<symbol_type, std::vector<bitvector_type>>> PM; std::vector<bitvector_type> zeroes; struct WorkData { bitvector_type D0; bitvector_type HP; bitvector_type HN; bitvector_type VP; bitvector_type VN; void reset() { D0 = HP = HN = VN = 0; VP = ~(bitvector_type{0}); } }; mutable std::vector<WorkData> work; template<typename Integer> static constexpr int bit_width() { return 8 * sizeof(Integer); } static constexpr int bit_offset(int w) { return w < 2 ? 0 : (bit_offset(w >> 1) + 1); } template<typename Integer> static constexpr int bit_offset() { return bit_offset(bit_width<Integer>()); } template<typename key_type, typename value_type> const value_type& find_value(const std::vector<std::pair<key_type, value_type>>& data, const key_type c, const value_type& default_value) const { if(c < c_min || c_max < c){ return default_value; } else if(c == c_min){ return PM.front().second; } else if(c == c_max){ return PM.back().second; } size_type l = 1, r = data.size() - 1; while(r - l > 8){ auto i = (l + r) / 2; if(data[i].first < c){ l = i + 1; } else if(data[i].first > c){ r = i; } else{ return data[i].second; } } for(size_type i = l; i < r; ++i){ if(data[i].first == c){ return data[i].second; } } return default_value; } void constructPM() { std::map<symbol_type, std::vector<bitvector_type>> PM_work; for(size_type i = 0; i < block_size - 1; ++i){ for(size_type j = 0; j < bit_width<bitvector_type>(); ++j){ if(PM_work[pattern[i * bit_width<bitvector_type>() + j]].empty()){ PM_work[pattern[i * bit_width<bitvector_type>() + j]].resize(block_size, 0); } PM_work[pattern[i * bit_width<bitvector_type>() + j]][i] |= bitvector_type{1} << j; } } for(size_type i = 0; i < rest_bits; ++i){ if(PM_work[pattern[(block_size - 1) * bit_width<bitvector_type>() + i]].empty()){ PM_work[pattern[(block_size - 1) * bit_width<bitvector_type>() + i]].resize(block_size, 0); } PM_work[pattern[(block_size - 1) * bit_width<bitvector_type>() + i]].back() |= bitvector_type{1} << i; } PM.clear(); for(const auto& p: PM_work){ PM.push_back(p); } c_min = PM.front().first; c_max = PM.back().first; } distance_type distance_sp(string_type const &text) const { auto& w = work.front(); w.reset(); for(size_type i = 0; i < pattern_length; ++i){ w.VP |= bitvector_type{1} << i; } distance_type D = pattern_length; for(auto c: text){ auto X = find_value(PM, c, zeroes).front() | w.VN; w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X; w.HP = w.VN | ~(w.VP | w.D0); w.HN = w.VP & w.D0; X = (w.HP << 1) | 1; w.VP = (w.HN << 1) | ~(X | w.D0); w.VN = X & w.D0; if(w.HP & sink){ ++D; } else if(w.HN & sink){ --D; } } return D; } distance_type distance_lp(string_type const &text) const { constexpr bitvector_type msb = bitvector_type{1} << (bit_width<bitvector_type>() - 1); for(auto& w: work){ w.reset(); } for(size_type i = 0; i < rest_bits; ++i){ work.back().VP |= bitvector_type{1} << i; } distance_type D = pattern_length; for(auto c: text){ const auto& PMc = find_value(PM, c, zeroes); for(size_type r = 0; r < block_size; ++r){ auto& w = work[r]; auto X = PMc[r]; if(r > 0 && (work[r - 1].HN & msb)){ X |= 1; } w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN; w.HP = w.VN | ~(w.VP | w.D0); w.HN = w.VP & w.D0; X = w.HP << 1; if(r == 0 || work[r - 1].HP & msb){ X |= 1; } w.VP = (w.HN << 1) | ~(X | w.D0); if(r > 0 && (work[r - 1].HN & msb)){ w.VP |= 1; } w.VN = X & w.D0; } if(work.back().HP & sink){ ++D; } else if(work.back().HN & sink){ --D; } } return D; } distance_type distance(string_type const &text) const { if(text.empty()){ return pattern_length; } else if(pattern_length == 0){ return text.size(); } if(block_size == 1){ return distance_sp(text); } else{ return distance_lp(text); } } }; } #endif <|endoftext|>
<commit_before>// Convert DMD CodeView debug information to PDB files // Copyright (c) 2009-2010 by Rainer Schuetze, All Rights Reserved // // License for redistribution is given by the Artistic License 2.0 // see file LICENSE for further details #include <algorithm> #include "symutil.h" #include "demangle.h" extern "C" { #include "mscvpdb.h" } #include <assert.h> char dotReplacementChar = '@'; bool demangleSymbols = true; bool useTypedefEnum = false; int dsym2c(const BYTE* p, int len, char* cname, int maxclen) { const BYTE* beg = p; const BYTE* end = p + len; int zlen, zpos, cpos = 0; // decompress symbol while (p < end) { int ch = *p++; if(ch == 0) break; if ((ch & 0xc0) == 0xc0) { zlen = (ch & 0x7) + 1; zpos = ((ch >> 3) & 7) + 1; // + zlen; if (zpos > cpos) break; if (cpos + zlen >= maxclen) break; for (int z = 0; z < zlen; z++) cname[cpos + z] = cname[cpos - zpos + z]; cpos += zlen; } else if (ch >= 0x80) { if (p >= end) break; int ch2 = *p++; zlen = (ch2 & 0x7f) | ((ch & 0x38) << 4); if (p >= end) break; int ch3 = *p++; zpos = (ch3 & 0x7f) | ((ch & 7) << 7); if (zpos > cpos) break; if (cpos + zlen >= maxclen) break; for(int z = 0; z < zlen; z++) cname[cpos + z] = cname[cpos - zpos + z]; cpos += zlen; } #if 0 if (ch == 0x80) { if (p >= end) break; zlen = *p++ & 0x7f; if (p >= end) break; zpos = *p++ & 0x7f; if (zpos > cpos) break; for(int z = 0; z < zlen; z++) cname[cpos + z] = cname[cpos - zpos + z]; cpos += zlen; } else if (ch > 0x80) { zlen = (ch & 0x7) + 1; zpos = ((ch >> 3) & 0xf) - 7; // + zlen; for(int z = 0; z < zlen; z++) cname[cpos + z] = cname[cpos - zpos + z]; cpos += zlen; } #endif else cname[cpos++] = ch; } if (p < end) { // decompression failed, assume it's containing UTF8 encoded characters cpos = min(maxclen, len); memcpy(cname, beg, cpos); } cname[cpos] = 0; if(demangleSymbols) if (cname[0] == '_' && cname[1] == 'D' && isdigit(cname[2])) d_demangle(cname, cname, maxclen, true); #if 1 for(int i = 0; i < cpos; i++) if (cname[i] == '.') cname[i] = dotReplacementChar; #endif return cpos; } int pstrlen(const BYTE* &p) { int len = *p++; if(len == 0xff && *p == 0) { len = p[1] | (p[2] << 8); p += 3; } return len; } int pstrmemlen(const BYTE* p) { const BYTE* q = p; int len = pstrlen(p); return len + (p - q); } int dstrlen(const BYTE* &p, bool cstr) { if(cstr) return strlen((const char*)p); return pstrlen(p); } char* p2c(const BYTE* p, int idx) { static char cname[4][2560]; int len = pstrlen(p); #if 1 memcpy(cname[idx], p, len); cname[idx][len] = 0; #else dsym2c(p, len, cname[idx], 2560); #endif return cname[idx]; } char* p2c(const p_string& p, int idx) { return p2c(&p.namelen, idx); } int c2p(const char* c, BYTE* p) { BYTE* q = p; int len = strlen(c); if(len > 255) { *p++ = 0xff; *p++ = 0; *p++ = len & 0xff; *p++ = len >> 8; } else *p++ = len; memcpy(p, c, len); return p + len - q; } int c2p(const char* c, p_string& p) { return c2p(c, &p.namelen); } int p2ccpy(char* p, const BYTE* s) { int len = pstrlen(s); memcpy(p, s, len); p[len] = 0; return len + 1; } int pstrcpy(BYTE* p, const BYTE* s) { const BYTE* src = s; int len = pstrlen(s); for(int i = 0; i <= s - src; i++) *p++ = src[i]; for(int i = 0; i < len; i++) if (s[i] == '.') { //p[i++] = ':'; p[i] = dotReplacementChar; } else p[i] = s[i]; return len + src - s; // *(BYTE*) memcpy (p, s, *s + 1) + 1; } int dmemcmp(const void* v1, const void* v2, int len) { const BYTE* p1 = (const BYTE*) v1; const BYTE* p2 = (const BYTE*) v2; for(int i = 0; i < len; i++) { int b1 = p1[i]; int b2 = p2[i]; if(b1 == '.') b1 = dotReplacementChar; if(b2 == '.') b2 = dotReplacementChar; if(b1 != b2) return b2 - b1; } return 0; } int pstrcpy(p_string& p, const p_string& s) { return *(BYTE*) memcpy (&p, &s, s.namelen + 1) + 1; } int pstrcmp(const BYTE* p1, const BYTE* p2) { int len1 = pstrlen(p1); int len2 = pstrlen(p2); if (len1 != len2) return len2 - len1; return dmemcmp(p1, p2, len1); } bool p2ccmp(const BYTE* pp, const char* cp) { int len = strlen(cp); int plen = pstrlen(pp); if (len != plen) return false; return dmemcmp(pp, cp, len) == 0; } bool p2ccmp(const p_string& pp, const char* cp) { return p2ccmp(&pp.namelen, cp); } bool dstrcmp(const BYTE* s1, bool cstr1, const BYTE* s2, bool cstr2) { int len1 = dstrlen(s1, cstr1); int len2 = dstrlen(s2, cstr2); if(len1 != len2) return false; return dmemcmp(s1, s2, len1) == 0; } int pstrcpy_v(bool v3, BYTE* d, const BYTE* s) { if (!v3) return pstrcpy(d, s); int len = pstrlen(s); int clen = dsym2c(s, len, (char*) d, kMaxNameLen) + 1; return clen; } int cstrcpy_v(bool v3, BYTE* d, const char* s) { int len = strlen(s); if(!v3) { assert(len < 256); *d++ = len; } len = (std::min)(len, kMaxNameLen-1); memcpy(d, s, len + 1); d[len] = '\0'; for(int i = 0; i < len; i++) if (d[i] == '.') d[i] = dotReplacementChar; return len + 1; } <commit_msg>Do not crash when handling anonymous entities<commit_after>// Convert DMD CodeView debug information to PDB files // Copyright (c) 2009-2010 by Rainer Schuetze, All Rights Reserved // // License for redistribution is given by the Artistic License 2.0 // see file LICENSE for further details #include <algorithm> #include "symutil.h" #include "demangle.h" extern "C" { #include "mscvpdb.h" } #include <assert.h> char dotReplacementChar = '@'; bool demangleSymbols = true; bool useTypedefEnum = false; int dsym2c(const BYTE* p, int len, char* cname, int maxclen) { const BYTE* beg = p; const BYTE* end = p + len; int zlen, zpos, cpos = 0; // decompress symbol while (p < end) { int ch = *p++; if(ch == 0) break; if ((ch & 0xc0) == 0xc0) { zlen = (ch & 0x7) + 1; zpos = ((ch >> 3) & 7) + 1; // + zlen; if (zpos > cpos) break; if (cpos + zlen >= maxclen) break; for (int z = 0; z < zlen; z++) cname[cpos + z] = cname[cpos - zpos + z]; cpos += zlen; } else if (ch >= 0x80) { if (p >= end) break; int ch2 = *p++; zlen = (ch2 & 0x7f) | ((ch & 0x38) << 4); if (p >= end) break; int ch3 = *p++; zpos = (ch3 & 0x7f) | ((ch & 7) << 7); if (zpos > cpos) break; if (cpos + zlen >= maxclen) break; for(int z = 0; z < zlen; z++) cname[cpos + z] = cname[cpos - zpos + z]; cpos += zlen; } #if 0 if (ch == 0x80) { if (p >= end) break; zlen = *p++ & 0x7f; if (p >= end) break; zpos = *p++ & 0x7f; if (zpos > cpos) break; for(int z = 0; z < zlen; z++) cname[cpos + z] = cname[cpos - zpos + z]; cpos += zlen; } else if (ch > 0x80) { zlen = (ch & 0x7) + 1; zpos = ((ch >> 3) & 0xf) - 7; // + zlen; for(int z = 0; z < zlen; z++) cname[cpos + z] = cname[cpos - zpos + z]; cpos += zlen; } #endif else cname[cpos++] = ch; } if (p < end) { // decompression failed, assume it's containing UTF8 encoded characters cpos = min(maxclen, len); memcpy(cname, beg, cpos); } cname[cpos] = 0; if(demangleSymbols) if (cname[0] == '_' && cname[1] == 'D' && isdigit(cname[2])) d_demangle(cname, cname, maxclen, true); #if 1 for(int i = 0; i < cpos; i++) if (cname[i] == '.') cname[i] = dotReplacementChar; #endif return cpos; } int pstrlen(const BYTE* &p) { int len = *p++; if(len == 0xff && *p == 0) { len = p[1] | (p[2] << 8); p += 3; } return len; } int pstrmemlen(const BYTE* p) { const BYTE* q = p; int len = pstrlen(p); return len + (p - q); } int dstrlen(const BYTE* &p, bool cstr) { if(cstr) return strlen((const char*)p); return pstrlen(p); } char* p2c(const BYTE* p, int idx) { static char cname[4][2560]; int len = pstrlen(p); #if 1 memcpy(cname[idx], p, len); cname[idx][len] = 0; #else dsym2c(p, len, cname[idx], 2560); #endif return cname[idx]; } char* p2c(const p_string& p, int idx) { return p2c(&p.namelen, idx); } int c2p(const char* c, BYTE* p) { BYTE* q = p; int len = strlen(c); if(len > 255) { *p++ = 0xff; *p++ = 0; *p++ = len & 0xff; *p++ = len >> 8; } else *p++ = len; memcpy(p, c, len); return p + len - q; } int c2p(const char* c, p_string& p) { return c2p(c, &p.namelen); } int p2ccpy(char* p, const BYTE* s) { int len = pstrlen(s); memcpy(p, s, len); p[len] = 0; return len + 1; } int pstrcpy(BYTE* p, const BYTE* s) { const BYTE* src = s; int len = pstrlen(s); for(int i = 0; i <= s - src; i++) *p++ = src[i]; for(int i = 0; i < len; i++) if (s[i] == '.') { //p[i++] = ':'; p[i] = dotReplacementChar; } else p[i] = s[i]; return len + src - s; // *(BYTE*) memcpy (p, s, *s + 1) + 1; } int dmemcmp(const void* v1, const void* v2, int len) { const BYTE* p1 = (const BYTE*) v1; const BYTE* p2 = (const BYTE*) v2; for(int i = 0; i < len; i++) { int b1 = p1[i]; int b2 = p2[i]; if(b1 == '.') b1 = dotReplacementChar; if(b2 == '.') b2 = dotReplacementChar; if(b1 != b2) return b2 - b1; } return 0; } int pstrcpy(p_string& p, const p_string& s) { return *(BYTE*) memcpy (&p, &s, s.namelen + 1) + 1; } int pstrcmp(const BYTE* p1, const BYTE* p2) { int len1 = pstrlen(p1); int len2 = pstrlen(p2); if (len1 != len2) return len2 - len1; return dmemcmp(p1, p2, len1); } bool p2ccmp(const BYTE* pp, const char* cp) { int len = strlen(cp); int plen = pstrlen(pp); if (len != plen) return false; return dmemcmp(pp, cp, len) == 0; } bool p2ccmp(const p_string& pp, const char* cp) { return p2ccmp(&pp.namelen, cp); } bool dstrcmp(const BYTE* s1, bool cstr1, const BYTE* s2, bool cstr2) { int len1 = dstrlen(s1, cstr1); int len2 = dstrlen(s2, cstr2); if(len1 != len2) return false; return dmemcmp(s1, s2, len1) == 0; } int pstrcpy_v(bool v3, BYTE* d, const BYTE* s) { if (!v3) return pstrcpy(d, s); int len = pstrlen(s); int clen = dsym2c(s, len, (char*) d, kMaxNameLen) + 1; return clen; } int cstrcpy_v(bool v3, BYTE* d, const char* s) { // Process absent names as empty ones if (s == NULL) s = ""; int len = strlen(s); if(!v3) { assert(len < 256); *d++ = len; } len = (std::min)(len, kMaxNameLen-1); memcpy(d, s, len + 1); d[len] = '\0'; for(int i = 0; i < len; i++) if (d[i] == '.') d[i] = dotReplacementChar; return len + 1; } <|endoftext|>
<commit_before>#include <numpy_eigen/boost_python_headers.hpp> #include <sm/eigen/matrix_sqrt.hpp> #include <sm/assert_macros.hpp> Eigen::MatrixXd matrixSqrt(const Eigen::MatrixXd & M) { SM_ASSERT_EQ(std::runtime_error, M.rows(), M.cols(), "The matrix must be square"); Eigen::MatrixXd sqrtM; Eigen::ComputationInfo result = sm::eigen::computeMatrixSqrt(M, sqrtM); SM_ASSERT_EQ(std::runtime_error, result, Eigen::Success, "The matrix square root was not successful") return sqrtM; } void exportEigen() { boost::python::def("computeMatrixSqrt", &matrixSqrt); } <commit_msg>Fixed a compilation error in the python interface<commit_after>#include <numpy_eigen/boost_python_headers.hpp> #include <sm/eigen/matrix_sqrt.hpp> #include <sm/assert_macros.hpp> Eigen::MatrixXd matrixSqrt(const Eigen::MatrixXd & M) { SM_ASSERT_EQ(std::runtime_error, M.rows(), M.cols(), "The matrix must be square"); Eigen::MatrixXd sqrtM; /*Eigen::ComputationInfo result =*/ sm::eigen::computeMatrixSqrt(M, sqrtM); //SM_ASSERT_EQ(std::runtime_error, result, Eigen::Success, "The matrix square root was not successful") return sqrtM; } void exportEigen() { boost::python::def("computeMatrixSqrt", &matrixSqrt); } <|endoftext|>
<commit_before>#pragma once namespace svgren{ struct SubSurface{ std::uint8_t* data; //RGBA premultiplied alpha unsigned stride; unsigned width; unsigned height; unsigned posx; unsigned posy; }; } <commit_msg>stuff<commit_after>#pragma once namespace svgren{ struct SubSurface{ std::uint8_t* data; //RGBA premultiplied alpha unsigned stride; unsigned width; unsigned height; //position of subsurface on the canvas unsigned posx; unsigned posy; }; } <|endoftext|>
<commit_before><commit_msg>Measurement jacobians<commit_after><|endoftext|>
<commit_before><commit_msg>indexcodec: Add extensive comments<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/cert_status_flags.h" #include "base/logging.h" #include "net/base/net_errors.h" namespace net { int MapNetErrorToCertStatus(int error) { switch (error) { case ERR_CERT_COMMON_NAME_INVALID: return CERT_STATUS_COMMON_NAME_INVALID; case ERR_CERT_DATE_INVALID: return CERT_STATUS_DATE_INVALID; case ERR_CERT_AUTHORITY_INVALID: return CERT_STATUS_AUTHORITY_INVALID; case ERR_CERT_NO_REVOCATION_MECHANISM: return CERT_STATUS_NO_REVOCATION_MECHANISM; case ERR_CERT_UNABLE_TO_CHECK_REVOCATION: return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION; case ERR_CERT_REVOKED: return CERT_STATUS_REVOKED; // We added the ERR_CERT_CONTAINS_ERRORS error code when we were using // WinInet, but we never figured out how it differs from ERR_CERT_INVALID. // We should not use ERR_CERT_CONTAINS_ERRORS in new code. case ERR_CERT_CONTAINS_ERRORS: NOTREACHED(); // Falls through. case ERR_CERT_INVALID: return CERT_STATUS_INVALID; case ERR_CERT_WEAK_SIGNATURE_ALGORITHM: return CERT_STATUS_WEAK_SIGNATURE_ALGORITHM; default: return 0; } } int MapCertStatusToNetError(int cert_status) { // A certificate may have multiple errors. We report the most // serious error. // Unrecoverable errors if (cert_status & CERT_STATUS_INVALID) return ERR_CERT_INVALID; if (cert_status & CERT_STATUS_REVOKED) return ERR_CERT_REVOKED; // Recoverable errors if (cert_status & CERT_STATUS_AUTHORITY_INVALID) return ERR_CERT_AUTHORITY_INVALID; if (cert_status & CERT_STATUS_COMMON_NAME_INVALID) return ERR_CERT_COMMON_NAME_INVALID; if (cert_status & CERT_STATUS_WEAK_SIGNATURE_ALGORITHM) return ERR_CERT_WEAK_SIGNATURE_ALGORITHM; if (cert_status & CERT_STATUS_DATE_INVALID) return ERR_CERT_DATE_INVALID; // Unknown status. Give it the benefit of the doubt. if (cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION) return ERR_CERT_UNABLE_TO_CHECK_REVOCATION; if (cert_status & CERT_STATUS_NO_REVOCATION_MECHANISM) return ERR_CERT_NO_REVOCATION_MECHANISM; NOTREACHED(); return ERR_UNEXPECTED; } } // namespace net <commit_msg>Consider "certificate revoked" as the most serious certificate error.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/cert_status_flags.h" #include "base/logging.h" #include "net/base/net_errors.h" namespace net { int MapNetErrorToCertStatus(int error) { switch (error) { case ERR_CERT_COMMON_NAME_INVALID: return CERT_STATUS_COMMON_NAME_INVALID; case ERR_CERT_DATE_INVALID: return CERT_STATUS_DATE_INVALID; case ERR_CERT_AUTHORITY_INVALID: return CERT_STATUS_AUTHORITY_INVALID; case ERR_CERT_NO_REVOCATION_MECHANISM: return CERT_STATUS_NO_REVOCATION_MECHANISM; case ERR_CERT_UNABLE_TO_CHECK_REVOCATION: return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION; case ERR_CERT_REVOKED: return CERT_STATUS_REVOKED; // We added the ERR_CERT_CONTAINS_ERRORS error code when we were using // WinInet, but we never figured out how it differs from ERR_CERT_INVALID. // We should not use ERR_CERT_CONTAINS_ERRORS in new code. case ERR_CERT_CONTAINS_ERRORS: NOTREACHED(); // Falls through. case ERR_CERT_INVALID: return CERT_STATUS_INVALID; case ERR_CERT_WEAK_SIGNATURE_ALGORITHM: return CERT_STATUS_WEAK_SIGNATURE_ALGORITHM; default: return 0; } } int MapCertStatusToNetError(int cert_status) { // A certificate may have multiple errors. We report the most // serious error. // Unrecoverable errors if (cert_status & CERT_STATUS_REVOKED) return ERR_CERT_REVOKED; if (cert_status & CERT_STATUS_INVALID) return ERR_CERT_INVALID; // Recoverable errors if (cert_status & CERT_STATUS_AUTHORITY_INVALID) return ERR_CERT_AUTHORITY_INVALID; if (cert_status & CERT_STATUS_COMMON_NAME_INVALID) return ERR_CERT_COMMON_NAME_INVALID; if (cert_status & CERT_STATUS_WEAK_SIGNATURE_ALGORITHM) return ERR_CERT_WEAK_SIGNATURE_ALGORITHM; if (cert_status & CERT_STATUS_DATE_INVALID) return ERR_CERT_DATE_INVALID; // Unknown status. Give it the benefit of the doubt. if (cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION) return ERR_CERT_UNABLE_TO_CHECK_REVOCATION; if (cert_status & CERT_STATUS_NO_REVOCATION_MECHANISM) return ERR_CERT_NO_REVOCATION_MECHANISM; NOTREACHED(); return ERR_UNEXPECTED; } } // namespace net <|endoftext|>
<commit_before>#include <cucumber-cpp/internal/connectors/wire/WireProtocol.hpp> #include <cucumber-cpp/internal/connectors/wire/WireProtocolCommands.hpp> #include <json_spirit/json_spirit_reader_template.h> #include <json_spirit/json_spirit_writer_template.h> #include <boost/make_shared.hpp> #include <boost/shared_ptr.hpp> #include <boost/assign/list_of.hpp> #include <boost/foreach.hpp> #include <iostream> #include <string> #include <sstream> using namespace json_spirit; namespace cucumber { namespace internal { /* * Responses */ void SuccessResponse::accept(WireResponseVisitor& visitor) const { visitor.visit(*this); } FailureResponse::FailureResponse(const std::string & message, const std::string & exceptionType) : message(message), exceptionType(exceptionType) { } const std::string FailureResponse::getMessage() const { return message; } const std::string FailureResponse::getExceptionType() const { return exceptionType; } void FailureResponse::accept(WireResponseVisitor& visitor) const { visitor.visit(*this); } PendingResponse::PendingResponse(const std::string & message) : message(message) { } const std::string PendingResponse::getMessage() const { return message; } void PendingResponse::accept(WireResponseVisitor& visitor) const { visitor.visit(*this); } StepMatchesResponse::StepMatchesResponse(const std::vector<StepMatch> & matchingSteps) : matchingSteps(matchingSteps) { } const std::vector<StepMatch>& StepMatchesResponse::getMatchingSteps() const { return matchingSteps; } void StepMatchesResponse::accept(WireResponseVisitor& visitor) const { visitor.visit(*this); } SnippetTextResponse::SnippetTextResponse(const std::string & stepSnippet) : stepSnippet(stepSnippet) { } const std::string SnippetTextResponse::getStepSnippet() const { return stepSnippet; } void SnippetTextResponse::accept(WireResponseVisitor& visitor) const { visitor.visit(*this); } /* * Command decoders */ class CommandDecoder { public: virtual ~CommandDecoder() { } virtual boost::shared_ptr<WireCommand> decode(const mValue & jsonArgs) const = 0; }; class ScenarioDecoder : public CommandDecoder { protected: CukeEngine::tags_type getTags(const mValue & jsonArgs) const { CukeEngine::tags_type tags; if (!jsonArgs.is_null()) { const mArray & jsonTags = jsonArgs.get_obj().find("tags")->second.get_array(); for (mArray::const_iterator i = jsonTags.begin(); i != jsonTags.end(); ++i) { tags.push_back(i->get_str()); } } return tags; } }; class BeginScenarioDecoder : public ScenarioDecoder { public: boost::shared_ptr<WireCommand> decode(const mValue & jsonArgs) const { return boost::make_shared<BeginScenarioCommand>(getTags(jsonArgs)); } }; class EndScenarioDecoder : public ScenarioDecoder { public: boost::shared_ptr<WireCommand> decode(const mValue & jsonArgs) const { return boost::make_shared<EndScenarioCommand>(getTags(jsonArgs)); } }; class StepMatchesDecoder : public CommandDecoder { public: boost::shared_ptr<WireCommand> decode(const mValue & jsonArgs) const { mObject stepMatchesArgs(jsonArgs.get_obj()); const std::string & nameToMatch(stepMatchesArgs["name_to_match"].get_str()); return boost::make_shared<StepMatchesCommand>(nameToMatch); } }; class InvokeDecoder : public CommandDecoder { public: boost::shared_ptr<WireCommand> decode(const mValue & jsonArgs) const { mObject invokeParams(jsonArgs.get_obj()); CukeEngine::invoke_args_type args; CukeEngine::invoke_table_type tableArg; const std::string & id(invokeParams["id"].get_str()); fillInvokeArgs(invokeParams, args, tableArg); return boost::make_shared<InvokeCommand>(id, args, tableArg); } private: void fillInvokeArgs( const mObject & invokeParams, CukeEngine::invoke_args_type & args, CukeEngine::invoke_table_type & tableArg) const { const mArray & jsonArgs(invokeParams.find("args")->second.get_array()); for (mArray::const_iterator i = jsonArgs.begin(); i != jsonArgs.end(); ++i) { if (i->type() == str_type) { args.push_back(i->get_str()); } else if (i->type() == array_type) { fillTableArg(i->get_array(), tableArg); } } } void fillTableArg(const mArray & jsonTableArg, CukeEngine::invoke_table_type & tableArg) const { typedef mArray::size_type size_type; size_type rows = jsonTableArg.size(); if (rows > 0) { size_type columns = jsonTableArg[0].get_array().size(); tableArg.resize(boost::extents[rows][columns]); for (size_type i = 0; i < rows; ++i) { const mArray & jsonRow(jsonTableArg[i].get_array()); if (jsonRow.size() == columns) { for (size_type j = 0; j < columns; ++j) { tableArg[i][j] = jsonRow[j].get_str(); } } else { // TODO: Invalid row } } } else { // TODO: Invalid table (no column specified) } } }; class SnippetTextDecoder : public CommandDecoder { public: boost::shared_ptr<WireCommand> decode(const mValue & jsonArgs) const { mObject snippetTextArgs(jsonArgs.get_obj()); const std::string & stepKeyword(snippetTextArgs["step_keyword"].get_str()); const std::string & stepName(snippetTextArgs["step_name"].get_str()); const std::string & multilineArgClass(snippetTextArgs["multiline_arg_class"].get_str()); return boost::make_shared<SnippetTextCommand>(stepKeyword, stepName, multilineArgClass); } }; static const std::map<std::string, boost::shared_ptr<CommandDecoder> > commandDecodersMap = boost::assign::map_list_of<std::string, boost::shared_ptr<CommandDecoder> > ("begin_scenario", boost::make_shared< BeginScenarioDecoder >()) ("end_scenario" , boost::make_shared< EndScenarioDecoder >()) ("step_matches" , boost::make_shared< StepMatchesDecoder >()) ("invoke" , boost::make_shared< InvokeDecoder >()) ("snippet_text" , boost::make_shared< SnippetTextDecoder >()); JsonSpiritWireMessageCodec::JsonSpiritWireMessageCodec() {}; boost::shared_ptr<WireCommand> JsonSpiritWireMessageCodec::decode(const std::string &request) const { std::istringstream is(request); mValue json; try { read_stream(is, json); mArray & jsonRequest = json.get_array(); mValue & jsonCommand = jsonRequest[0]; const std::map<std::string, boost::shared_ptr<CommandDecoder> >::const_iterator commandDecoder = commandDecodersMap.find(jsonCommand.get_str()); if (commandDecoder != commandDecodersMap.end() && commandDecoder->second) { mValue jsonArgs; if (jsonRequest.size() > 1) { jsonArgs = jsonRequest[1]; } return commandDecoder->second->decode(jsonArgs); } } catch (...) { // LOG Error decoding wire protocol command } return boost::make_shared<FailingCommand>(); } namespace { class WireResponseEncoder : public WireResponseVisitor { private: mArray jsonOutput; void success(const mValue *detail = 0) { output("success", detail); } void fail(const mValue *detail = 0) { output("fail", detail); } void output(const char *responseType, const mValue *detail = 0) { jsonOutput.push_back(responseType); if (detail == 0 || detail->is_null()) { return; } jsonOutput.push_back(*detail); } public: std::string encode(const WireResponse& response) { jsonOutput.clear(); response.accept(*this); const mValue v(jsonOutput); return write_string(v, false); } void visit(const SuccessResponse& /*response*/) { success(); } void visit(const FailureResponse& response) { mObject detailObject; if (!response.getMessage().empty()) { detailObject["message"] = response.getMessage(); } if (!response.getExceptionType().empty()) { detailObject["exception"] = response.getExceptionType(); } if (detailObject.empty()) { fail(); } else { const mValue detail(detailObject); fail(&detail); } } void visit(const PendingResponse& response) { mValue jsonReponse(response.getMessage()); output("pending", &jsonReponse); } void visit(const StepMatchesResponse& response) { mArray jsonMatches; BOOST_FOREACH(StepMatch m, response.getMatchingSteps()) { mObject jsonM; jsonM["id"] = m.id; mArray jsonArgs; BOOST_FOREACH(StepMatchArg ma, m.args) { mObject jsonMa; jsonMa["val"] = ma.value; jsonMa["pos"] = ma.position; jsonArgs.push_back(jsonMa); } jsonM["args"] = jsonArgs; if (!m.source.empty()) { jsonM["source"] = m.source;; } if (!m.regexp.empty()) { jsonM["regexp"] = m.regexp; } jsonMatches.push_back(jsonM); } mValue jsonReponse(jsonMatches); output("success", &jsonReponse); } void visit(const SnippetTextResponse& response) { mValue jsonReponse(response.getStepSnippet()); success(&jsonReponse); } }; } const std::string JsonSpiritWireMessageCodec::encode(const WireResponse& response) const { try { WireResponseEncoder encoder; return encoder.encode(response); } catch (...) { throw WireMessageCodecException("Error decoding wire protocol response"); } } WireProtocolHandler::WireProtocolHandler(const WireMessageCodec& codec, CukeEngine& engine) : codec(codec), engine(engine) { } std::string WireProtocolHandler::handle(const std::string &request) const { std::string response; // LOG request try { boost::shared_ptr<const WireCommand> command = codec.decode(request); boost::shared_ptr<const WireResponse> wireResponse = command->run(engine); response = codec.encode(*wireResponse); } catch (...) { response = "[\"fail\"]"; } // LOG response return response; } } } <commit_msg>Replace CommandDecoder base class for function pointer<commit_after>#include <cucumber-cpp/internal/connectors/wire/WireProtocol.hpp> #include <cucumber-cpp/internal/connectors/wire/WireProtocolCommands.hpp> #include <json_spirit/json_spirit_reader_template.h> #include <json_spirit/json_spirit_writer_template.h> #include <boost/make_shared.hpp> #include <boost/shared_ptr.hpp> #include <boost/assign/list_of.hpp> #include <boost/foreach.hpp> #include <iostream> #include <string> #include <sstream> using namespace json_spirit; namespace cucumber { namespace internal { /* * Responses */ void SuccessResponse::accept(WireResponseVisitor& visitor) const { visitor.visit(*this); } FailureResponse::FailureResponse(const std::string & message, const std::string & exceptionType) : message(message), exceptionType(exceptionType) { } const std::string FailureResponse::getMessage() const { return message; } const std::string FailureResponse::getExceptionType() const { return exceptionType; } void FailureResponse::accept(WireResponseVisitor& visitor) const { visitor.visit(*this); } PendingResponse::PendingResponse(const std::string & message) : message(message) { } const std::string PendingResponse::getMessage() const { return message; } void PendingResponse::accept(WireResponseVisitor& visitor) const { visitor.visit(*this); } StepMatchesResponse::StepMatchesResponse(const std::vector<StepMatch> & matchingSteps) : matchingSteps(matchingSteps) { } const std::vector<StepMatch>& StepMatchesResponse::getMatchingSteps() const { return matchingSteps; } void StepMatchesResponse::accept(WireResponseVisitor& visitor) const { visitor.visit(*this); } SnippetTextResponse::SnippetTextResponse(const std::string & stepSnippet) : stepSnippet(stepSnippet) { } const std::string SnippetTextResponse::getStepSnippet() const { return stepSnippet; } void SnippetTextResponse::accept(WireResponseVisitor& visitor) const { visitor.visit(*this); } /* * Command decoders */ namespace { typedef boost::shared_ptr<WireCommand> (*CommandDecoder)(const mValue& jsonArgs); CukeEngine::tags_type getScenarioTags(const mValue& jsonArgs) { CukeEngine::tags_type tags; if (!jsonArgs.is_null()) { const mArray & jsonTags = jsonArgs.get_obj().find("tags")->second.get_array(); for (mArray::const_iterator i = jsonTags.begin(); i != jsonTags.end(); ++i) { tags.push_back(i->get_str()); } } return tags; } boost::shared_ptr<WireCommand> BeginScenarioDecoder(const mValue& jsonArgs) { return boost::make_shared<BeginScenarioCommand>(getScenarioTags(jsonArgs)); } boost::shared_ptr<WireCommand> EndScenarioDecoder(const mValue& jsonArgs) { return boost::make_shared<EndScenarioCommand>(getScenarioTags(jsonArgs)); } boost::shared_ptr<WireCommand> StepMatchesDecoder(const mValue& jsonArgs) { mObject stepMatchesArgs(jsonArgs.get_obj()); const std::string& nameToMatch(stepMatchesArgs["name_to_match"].get_str()); return boost::make_shared<StepMatchesCommand>(nameToMatch); } void fillTableArg(const mArray& jsonTableArg, CukeEngine::invoke_table_type& tableArg) { typedef mArray::size_type size_type; size_type rows = jsonTableArg.size(); if (rows > 0) { size_type columns = jsonTableArg[0].get_array().size(); tableArg.resize(boost::extents[rows][columns]); for (size_type i = 0; i < rows; ++i) { const mArray & jsonRow(jsonTableArg[i].get_array()); if (jsonRow.size() == columns) { for (size_type j = 0; j < columns; ++j) { tableArg[i][j] = jsonRow[j].get_str(); } } else { // TODO: Invalid row } } } else { // TODO: Invalid table (no column specified) } } void fillInvokeArgs( const mObject& invokeParams, CukeEngine::invoke_args_type& args, CukeEngine::invoke_table_type& tableArg) { const mArray & jsonArgs(invokeParams.find("args")->second.get_array()); for (mArray::const_iterator i = jsonArgs.begin(); i != jsonArgs.end(); ++i) { if (i->type() == str_type) { args.push_back(i->get_str()); } else if (i->type() == array_type) { fillTableArg(i->get_array(), tableArg); } } } boost::shared_ptr<WireCommand> InvokeDecoder(const mValue& jsonArgs) { mObject invokeParams(jsonArgs.get_obj()); CukeEngine::invoke_args_type args; CukeEngine::invoke_table_type tableArg; const std::string & id(invokeParams["id"].get_str()); fillInvokeArgs(invokeParams, args, tableArg); return boost::make_shared<InvokeCommand>(id, args, tableArg); } boost::shared_ptr<WireCommand> SnippetTextDecoder(const mValue& jsonArgs) { mObject snippetTextArgs(jsonArgs.get_obj()); const std::string & stepKeyword(snippetTextArgs["step_keyword"].get_str()); const std::string & stepName(snippetTextArgs["step_name"].get_str()); const std::string & multilineArgClass(snippetTextArgs["multiline_arg_class"].get_str()); return boost::make_shared<SnippetTextCommand>(stepKeyword, stepName, multilineArgClass); } } static const std::map<std::string, CommandDecoder> commandDecodersMap = boost::assign::map_list_of<std::string, CommandDecoder> ("begin_scenario", BeginScenarioDecoder) ("end_scenario" , EndScenarioDecoder ) ("step_matches" , StepMatchesDecoder ) ("invoke" , InvokeDecoder ) ("snippet_text" , SnippetTextDecoder ) ; JsonSpiritWireMessageCodec::JsonSpiritWireMessageCodec() {}; boost::shared_ptr<WireCommand> JsonSpiritWireMessageCodec::decode(const std::string &request) const { std::istringstream is(request); mValue json; try { read_stream(is, json); mArray & jsonRequest = json.get_array(); mValue & jsonCommand = jsonRequest[0]; const std::map<std::string, CommandDecoder>::const_iterator commandDecoder = commandDecodersMap.find(jsonCommand.get_str()); if (commandDecoder != commandDecodersMap.end() && commandDecoder->second) { mValue jsonArgs; if (jsonRequest.size() > 1) { jsonArgs = jsonRequest[1]; } return commandDecoder->second(jsonArgs); } } catch (...) { // LOG Error decoding wire protocol command } return boost::make_shared<FailingCommand>(); } namespace { class WireResponseEncoder : public WireResponseVisitor { private: mArray jsonOutput; void success(const mValue *detail = 0) { output("success", detail); } void fail(const mValue *detail = 0) { output("fail", detail); } void output(const char *responseType, const mValue *detail = 0) { jsonOutput.push_back(responseType); if (detail == 0 || detail->is_null()) { return; } jsonOutput.push_back(*detail); } public: std::string encode(const WireResponse& response) { jsonOutput.clear(); response.accept(*this); const mValue v(jsonOutput); return write_string(v, false); } void visit(const SuccessResponse& /*response*/) { success(); } void visit(const FailureResponse& response) { mObject detailObject; if (!response.getMessage().empty()) { detailObject["message"] = response.getMessage(); } if (!response.getExceptionType().empty()) { detailObject["exception"] = response.getExceptionType(); } if (detailObject.empty()) { fail(); } else { const mValue detail(detailObject); fail(&detail); } } void visit(const PendingResponse& response) { mValue jsonReponse(response.getMessage()); output("pending", &jsonReponse); } void visit(const StepMatchesResponse& response) { mArray jsonMatches; BOOST_FOREACH(StepMatch m, response.getMatchingSteps()) { mObject jsonM; jsonM["id"] = m.id; mArray jsonArgs; BOOST_FOREACH(StepMatchArg ma, m.args) { mObject jsonMa; jsonMa["val"] = ma.value; jsonMa["pos"] = ma.position; jsonArgs.push_back(jsonMa); } jsonM["args"] = jsonArgs; if (!m.source.empty()) { jsonM["source"] = m.source;; } if (!m.regexp.empty()) { jsonM["regexp"] = m.regexp; } jsonMatches.push_back(jsonM); } mValue jsonReponse(jsonMatches); output("success", &jsonReponse); } void visit(const SnippetTextResponse& response) { mValue jsonReponse(response.getStepSnippet()); success(&jsonReponse); } }; } const std::string JsonSpiritWireMessageCodec::encode(const WireResponse& response) const { try { WireResponseEncoder encoder; return encoder.encode(response); } catch (...) { throw WireMessageCodecException("Error decoding wire protocol response"); } } WireProtocolHandler::WireProtocolHandler(const WireMessageCodec& codec, CukeEngine& engine) : codec(codec), engine(engine) { } std::string WireProtocolHandler::handle(const std::string &request) const { std::string response; // LOG request try { boost::shared_ptr<const WireCommand> command = codec.decode(request); boost::shared_ptr<const WireResponse> wireResponse = command->run(engine); response = codec.encode(*wireResponse); } catch (...) { response = "[\"fail\"]"; } // LOG response return response; } } } <|endoftext|>
<commit_before>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorFilter.h" #include "SkColorSpaceXformCanvas.h" #include "SkColorSpaceXformer.h" #include "SkGradientShader.h" #include "SkImage_Base.h" #include "SkMakeUnique.h" #include "SkNoDrawCanvas.h" #include "SkSurface.h" class SkColorSpaceXformCanvas : public SkNoDrawCanvas { public: SkColorSpaceXformCanvas(SkCanvas* target, std::unique_ptr<SkColorSpaceXformer> xformer) : SkNoDrawCanvas(SkIRect::MakeSize(target->getBaseLayerSize())) , fTarget(target) , fXformer(std::move(xformer)) { // Set the matrix and clip to match |fTarget|. Otherwise, we'll answer queries for // bounds/matrix differently than |fTarget| would. SkCanvas::onClipRect(SkRect::MakeFromIRect(fTarget->getDeviceClipBounds()), SkClipOp::kIntersect, kHard_ClipEdgeStyle); SkCanvas::setMatrix(fTarget->getTotalMatrix()); } SkImageInfo onImageInfo() const override { return fTarget->imageInfo(); } void onDrawPaint(const SkPaint& paint) override { fTarget->drawPaint(fXformer->apply(paint)); } void onDrawRect(const SkRect& rect, const SkPaint& paint) override { fTarget->drawRect(rect, fXformer->apply(paint)); } void onDrawOval(const SkRect& oval, const SkPaint& paint) override { fTarget->drawOval(oval, fXformer->apply(paint)); } void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override { fTarget->drawRRect(rrect, fXformer->apply(paint)); } void onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) override { fTarget->drawDRRect(outer, inner, fXformer->apply(paint)); } void onDrawPath(const SkPath& path, const SkPaint& paint) override { fTarget->drawPath(path, fXformer->apply(paint)); } void onDrawArc(const SkRect& oval, SkScalar start, SkScalar sweep, bool useCenter, const SkPaint& paint) override { fTarget->drawArc(oval, start, sweep, useCenter, fXformer->apply(paint)); } void onDrawRegion(const SkRegion& region, const SkPaint& paint) override { fTarget->drawRegion(region, fXformer->apply(paint)); } void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4], const SkPoint texs[4], SkBlendMode mode, const SkPaint& paint) override { SkColor xformed[4]; if (colors) { fXformer->apply(xformed, colors, 4); colors = xformed; } fTarget->drawPatch(cubics, colors, texs, mode, fXformer->apply(paint)); } void onDrawPoints(PointMode mode, size_t count, const SkPoint* pts, const SkPaint& paint) override { fTarget->drawPoints(mode, count, pts, fXformer->apply(paint)); } void onDrawVerticesObject(const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint) override { sk_sp<SkVertices> copy; if (vertices->hasColors()) { int count = vertices->vertexCount(); SkSTArray<8, SkColor> xformed(count); fXformer->apply(xformed.begin(), vertices->colors(), count); copy = SkVertices::MakeCopy(vertices->mode(), count, vertices->positions(), vertices->texCoords(), xformed.begin(), vertices->indexCount(), vertices->indices()); vertices = copy.get(); } fTarget->drawVertices(vertices, mode, fXformer->apply(paint)); } void onDrawText(const void* ptr, size_t len, SkScalar x, SkScalar y, const SkPaint& paint) override { fTarget->drawText(ptr, len, x, y, fXformer->apply(paint)); } void onDrawPosText(const void* ptr, size_t len, const SkPoint* xys, const SkPaint& paint) override { fTarget->drawPosText(ptr, len, xys, fXformer->apply(paint)); } void onDrawPosTextH(const void* ptr, size_t len, const SkScalar* xs, SkScalar y, const SkPaint& paint) override { fTarget->drawPosTextH(ptr, len, xs, y, fXformer->apply(paint)); } void onDrawTextOnPath(const void* ptr, size_t len, const SkPath& path, const SkMatrix* matrix, const SkPaint& paint) override { fTarget->drawTextOnPath(ptr, len, path, matrix, fXformer->apply(paint)); } void onDrawTextRSXform(const void* ptr, size_t len, const SkRSXform* xforms, const SkRect* cull, const SkPaint& paint) override { fTarget->drawTextRSXform(ptr, len, xforms, cull, fXformer->apply(paint)); } void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y, const SkPaint& paint) override { fTarget->drawTextBlob(blob, x, y, fXformer->apply(paint)); } void onDrawImage(const SkImage* img, SkScalar l, SkScalar t, const SkPaint* paint) override { fTarget->drawImage(fXformer->apply(img).get(), l, t, fXformer->apply(paint)); } void onDrawImageRect(const SkImage* img, const SkRect* src, const SkRect& dst, const SkPaint* paint, SrcRectConstraint constraint) override { fTarget->drawImageRect(fXformer->apply(img).get(), src ? *src : dst, dst, fXformer->apply(paint), constraint); } void onDrawImageNine(const SkImage* img, const SkIRect& center, const SkRect& dst, const SkPaint* paint) override { fTarget->drawImageNine(fXformer->apply(img).get(), center, dst, fXformer->apply(paint)); } void onDrawImageLattice(const SkImage* img, const Lattice& lattice, const SkRect& dst, const SkPaint* paint) override { fTarget->drawImageLattice(fXformer->apply(img).get(), lattice, dst, fXformer->apply(paint)); } void onDrawAtlas(const SkImage* atlas, const SkRSXform* xforms, const SkRect* tex, const SkColor* colors, int count, SkBlendMode mode, const SkRect* cull, const SkPaint* paint) override { SkSTArray<8, SkColor> xformed; if (colors) { xformed.reset(count); fXformer->apply(xformed.begin(), colors, count); colors = xformed.begin(); } fTarget->drawAtlas(fXformer->apply(atlas).get(), xforms, tex, colors, count, mode, cull, fXformer->apply(paint)); } void onDrawBitmap(const SkBitmap& bitmap, SkScalar l, SkScalar t, const SkPaint* paint) override { if (auto image = SkImage::MakeFromBitmap(bitmap)) { this->onDrawImage(image.get(), l, t, paint); } } void onDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst, const SkPaint* paint, SrcRectConstraint constraint) override { if (auto image = SkImage::MakeFromBitmap(bitmap)) { this->onDrawImageRect(image.get(), src, dst, paint, constraint); } } void onDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, const SkRect& dst, const SkPaint* paint) override { if (auto image = SkImage::MakeFromBitmap(bitmap)) { this->onDrawImageNine(image.get(), center, dst, paint); } } void onDrawBitmapLattice(const SkBitmap& bitmap, const Lattice& lattice, const SkRect& dst, const SkPaint* paint) override { if (auto image = SkImage::MakeFromBitmap(bitmap)) { this->onDrawImageLattice(image.get(), lattice, dst, paint); } } // TODO: May not be ideal to unfurl pictures. void onDrawPicture(const SkPicture* pic, const SkMatrix* matrix, const SkPaint* paint) override { SkCanvas::onDrawPicture(pic, matrix, fXformer->apply(paint)); } void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) override { SkCanvas::onDrawDrawable(drawable, matrix); } SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec& rec) override { fTarget->saveLayer({ rec.fBounds, fXformer->apply(rec.fPaint), rec.fBackdrop, // TODO: this is an image filter rec.fSaveLayerFlags, }); return kNoLayer_SaveLayerStrategy; } // Everything from here on should be uninteresting strictly proxied state-change calls. void willSave() override { fTarget->save(); } void willRestore() override { fTarget->restore(); } void didConcat (const SkMatrix& m) override { fTarget->concat (m); } void didSetMatrix(const SkMatrix& m) override { fTarget->setMatrix(m); } void onClipRect(const SkRect& clip, SkClipOp op, ClipEdgeStyle style) override { SkCanvas::onClipRect(clip, op, style); fTarget->clipRect(clip, op, style); } void onClipRRect(const SkRRect& clip, SkClipOp op, ClipEdgeStyle style) override { SkCanvas::onClipRRect(clip, op, style); fTarget->clipRRect(clip, op, style); } void onClipPath(const SkPath& clip, SkClipOp op, ClipEdgeStyle style) override { SkCanvas::onClipPath(clip, op, style); fTarget->clipPath(clip, op, style); } void onClipRegion(const SkRegion& clip, SkClipOp op) override { SkCanvas::onClipRegion(clip, op); fTarget->clipRegion(clip, op); } void onDrawAnnotation(const SkRect& rect, const char* key, SkData* val) override { fTarget->drawAnnotation(rect, key, val); } sk_sp<SkSurface> onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props) override { return fTarget->makeSurface(info, &props); } SkISize getBaseLayerSize() const override { return fTarget->getBaseLayerSize(); } SkRect onGetLocalClipBounds() const override { return fTarget->getLocalClipBounds(); } SkIRect onGetDeviceClipBounds() const override { return fTarget->getDeviceClipBounds(); } bool isClipEmpty() const override { return fTarget->isClipEmpty(); } bool isClipRect() const override { return fTarget->isClipRect(); } bool onPeekPixels(SkPixmap* pixmap) override { return fTarget->peekPixels(pixmap); } bool onAccessTopLayerPixels(SkPixmap* pixmap) override { SkImageInfo info; size_t rowBytes; SkIPoint* origin = nullptr; void* addr = fTarget->accessTopLayerPixels(&info, &rowBytes, origin); if (addr) { *pixmap = SkPixmap(info, addr, rowBytes); return true; } return false; } bool onGetProps(SkSurfaceProps* props) const override { return fTarget->getProps(props); } void onFlush() override { return fTarget->flush(); } private: SkCanvas* fTarget; std::unique_ptr<SkColorSpaceXformer> fXformer; }; std::unique_ptr<SkCanvas> SkCreateColorSpaceXformCanvas(SkCanvas* target, sk_sp<SkColorSpace> targetCS) { std::unique_ptr<SkColorSpaceXformer> xformer = SkColorSpaceXformer::Make(std::move(targetCS)); if (!xformer) { return nullptr; } return skstd::make_unique<SkColorSpaceXformCanvas>(target, std::move(xformer)); } <commit_msg>avoid deprecated SkRect::MakeFromIRect<commit_after>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorFilter.h" #include "SkColorSpaceXformCanvas.h" #include "SkColorSpaceXformer.h" #include "SkGradientShader.h" #include "SkImage_Base.h" #include "SkMakeUnique.h" #include "SkNoDrawCanvas.h" #include "SkSurface.h" class SkColorSpaceXformCanvas : public SkNoDrawCanvas { public: SkColorSpaceXformCanvas(SkCanvas* target, std::unique_ptr<SkColorSpaceXformer> xformer) : SkNoDrawCanvas(SkIRect::MakeSize(target->getBaseLayerSize())) , fTarget(target) , fXformer(std::move(xformer)) { // Set the matrix and clip to match |fTarget|. Otherwise, we'll answer queries for // bounds/matrix differently than |fTarget| would. SkCanvas::onClipRect(SkRect::Make(fTarget->getDeviceClipBounds()), SkClipOp::kIntersect, kHard_ClipEdgeStyle); SkCanvas::setMatrix(fTarget->getTotalMatrix()); } SkImageInfo onImageInfo() const override { return fTarget->imageInfo(); } void onDrawPaint(const SkPaint& paint) override { fTarget->drawPaint(fXformer->apply(paint)); } void onDrawRect(const SkRect& rect, const SkPaint& paint) override { fTarget->drawRect(rect, fXformer->apply(paint)); } void onDrawOval(const SkRect& oval, const SkPaint& paint) override { fTarget->drawOval(oval, fXformer->apply(paint)); } void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override { fTarget->drawRRect(rrect, fXformer->apply(paint)); } void onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) override { fTarget->drawDRRect(outer, inner, fXformer->apply(paint)); } void onDrawPath(const SkPath& path, const SkPaint& paint) override { fTarget->drawPath(path, fXformer->apply(paint)); } void onDrawArc(const SkRect& oval, SkScalar start, SkScalar sweep, bool useCenter, const SkPaint& paint) override { fTarget->drawArc(oval, start, sweep, useCenter, fXformer->apply(paint)); } void onDrawRegion(const SkRegion& region, const SkPaint& paint) override { fTarget->drawRegion(region, fXformer->apply(paint)); } void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4], const SkPoint texs[4], SkBlendMode mode, const SkPaint& paint) override { SkColor xformed[4]; if (colors) { fXformer->apply(xformed, colors, 4); colors = xformed; } fTarget->drawPatch(cubics, colors, texs, mode, fXformer->apply(paint)); } void onDrawPoints(PointMode mode, size_t count, const SkPoint* pts, const SkPaint& paint) override { fTarget->drawPoints(mode, count, pts, fXformer->apply(paint)); } void onDrawVerticesObject(const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint) override { sk_sp<SkVertices> copy; if (vertices->hasColors()) { int count = vertices->vertexCount(); SkSTArray<8, SkColor> xformed(count); fXformer->apply(xformed.begin(), vertices->colors(), count); copy = SkVertices::MakeCopy(vertices->mode(), count, vertices->positions(), vertices->texCoords(), xformed.begin(), vertices->indexCount(), vertices->indices()); vertices = copy.get(); } fTarget->drawVertices(vertices, mode, fXformer->apply(paint)); } void onDrawText(const void* ptr, size_t len, SkScalar x, SkScalar y, const SkPaint& paint) override { fTarget->drawText(ptr, len, x, y, fXformer->apply(paint)); } void onDrawPosText(const void* ptr, size_t len, const SkPoint* xys, const SkPaint& paint) override { fTarget->drawPosText(ptr, len, xys, fXformer->apply(paint)); } void onDrawPosTextH(const void* ptr, size_t len, const SkScalar* xs, SkScalar y, const SkPaint& paint) override { fTarget->drawPosTextH(ptr, len, xs, y, fXformer->apply(paint)); } void onDrawTextOnPath(const void* ptr, size_t len, const SkPath& path, const SkMatrix* matrix, const SkPaint& paint) override { fTarget->drawTextOnPath(ptr, len, path, matrix, fXformer->apply(paint)); } void onDrawTextRSXform(const void* ptr, size_t len, const SkRSXform* xforms, const SkRect* cull, const SkPaint& paint) override { fTarget->drawTextRSXform(ptr, len, xforms, cull, fXformer->apply(paint)); } void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y, const SkPaint& paint) override { fTarget->drawTextBlob(blob, x, y, fXformer->apply(paint)); } void onDrawImage(const SkImage* img, SkScalar l, SkScalar t, const SkPaint* paint) override { fTarget->drawImage(fXformer->apply(img).get(), l, t, fXformer->apply(paint)); } void onDrawImageRect(const SkImage* img, const SkRect* src, const SkRect& dst, const SkPaint* paint, SrcRectConstraint constraint) override { fTarget->drawImageRect(fXformer->apply(img).get(), src ? *src : dst, dst, fXformer->apply(paint), constraint); } void onDrawImageNine(const SkImage* img, const SkIRect& center, const SkRect& dst, const SkPaint* paint) override { fTarget->drawImageNine(fXformer->apply(img).get(), center, dst, fXformer->apply(paint)); } void onDrawImageLattice(const SkImage* img, const Lattice& lattice, const SkRect& dst, const SkPaint* paint) override { fTarget->drawImageLattice(fXformer->apply(img).get(), lattice, dst, fXformer->apply(paint)); } void onDrawAtlas(const SkImage* atlas, const SkRSXform* xforms, const SkRect* tex, const SkColor* colors, int count, SkBlendMode mode, const SkRect* cull, const SkPaint* paint) override { SkSTArray<8, SkColor> xformed; if (colors) { xformed.reset(count); fXformer->apply(xformed.begin(), colors, count); colors = xformed.begin(); } fTarget->drawAtlas(fXformer->apply(atlas).get(), xforms, tex, colors, count, mode, cull, fXformer->apply(paint)); } void onDrawBitmap(const SkBitmap& bitmap, SkScalar l, SkScalar t, const SkPaint* paint) override { if (auto image = SkImage::MakeFromBitmap(bitmap)) { this->onDrawImage(image.get(), l, t, paint); } } void onDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst, const SkPaint* paint, SrcRectConstraint constraint) override { if (auto image = SkImage::MakeFromBitmap(bitmap)) { this->onDrawImageRect(image.get(), src, dst, paint, constraint); } } void onDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, const SkRect& dst, const SkPaint* paint) override { if (auto image = SkImage::MakeFromBitmap(bitmap)) { this->onDrawImageNine(image.get(), center, dst, paint); } } void onDrawBitmapLattice(const SkBitmap& bitmap, const Lattice& lattice, const SkRect& dst, const SkPaint* paint) override { if (auto image = SkImage::MakeFromBitmap(bitmap)) { this->onDrawImageLattice(image.get(), lattice, dst, paint); } } // TODO: May not be ideal to unfurl pictures. void onDrawPicture(const SkPicture* pic, const SkMatrix* matrix, const SkPaint* paint) override { SkCanvas::onDrawPicture(pic, matrix, fXformer->apply(paint)); } void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) override { SkCanvas::onDrawDrawable(drawable, matrix); } SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec& rec) override { fTarget->saveLayer({ rec.fBounds, fXformer->apply(rec.fPaint), rec.fBackdrop, // TODO: this is an image filter rec.fSaveLayerFlags, }); return kNoLayer_SaveLayerStrategy; } // Everything from here on should be uninteresting strictly proxied state-change calls. void willSave() override { fTarget->save(); } void willRestore() override { fTarget->restore(); } void didConcat (const SkMatrix& m) override { fTarget->concat (m); } void didSetMatrix(const SkMatrix& m) override { fTarget->setMatrix(m); } void onClipRect(const SkRect& clip, SkClipOp op, ClipEdgeStyle style) override { SkCanvas::onClipRect(clip, op, style); fTarget->clipRect(clip, op, style); } void onClipRRect(const SkRRect& clip, SkClipOp op, ClipEdgeStyle style) override { SkCanvas::onClipRRect(clip, op, style); fTarget->clipRRect(clip, op, style); } void onClipPath(const SkPath& clip, SkClipOp op, ClipEdgeStyle style) override { SkCanvas::onClipPath(clip, op, style); fTarget->clipPath(clip, op, style); } void onClipRegion(const SkRegion& clip, SkClipOp op) override { SkCanvas::onClipRegion(clip, op); fTarget->clipRegion(clip, op); } void onDrawAnnotation(const SkRect& rect, const char* key, SkData* val) override { fTarget->drawAnnotation(rect, key, val); } sk_sp<SkSurface> onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props) override { return fTarget->makeSurface(info, &props); } SkISize getBaseLayerSize() const override { return fTarget->getBaseLayerSize(); } SkRect onGetLocalClipBounds() const override { return fTarget->getLocalClipBounds(); } SkIRect onGetDeviceClipBounds() const override { return fTarget->getDeviceClipBounds(); } bool isClipEmpty() const override { return fTarget->isClipEmpty(); } bool isClipRect() const override { return fTarget->isClipRect(); } bool onPeekPixels(SkPixmap* pixmap) override { return fTarget->peekPixels(pixmap); } bool onAccessTopLayerPixels(SkPixmap* pixmap) override { SkImageInfo info; size_t rowBytes; SkIPoint* origin = nullptr; void* addr = fTarget->accessTopLayerPixels(&info, &rowBytes, origin); if (addr) { *pixmap = SkPixmap(info, addr, rowBytes); return true; } return false; } bool onGetProps(SkSurfaceProps* props) const override { return fTarget->getProps(props); } void onFlush() override { return fTarget->flush(); } private: SkCanvas* fTarget; std::unique_ptr<SkColorSpaceXformer> fXformer; }; std::unique_ptr<SkCanvas> SkCreateColorSpaceXformCanvas(SkCanvas* target, sk_sp<SkColorSpace> targetCS) { std::unique_ptr<SkColorSpaceXformer> xformer = SkColorSpaceXformer::Make(std::move(targetCS)); if (!xformer) { return nullptr; } return skstd::make_unique<SkColorSpaceXformCanvas>(target, std::move(xformer)); } <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /* COPYING CONDITIONS NOTICE: This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation, and provided that the following conditions are met: * Redistributions of source code must retain this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below). * Redistributions in binary form must reproduce this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below) in the documentation and/or other materials provided with the distribution. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. COPYRIGHT NOTICE: TokuDB, Tokutek Fractal Tree Indexing Library. Copyright (C) 2007-2013 Tokutek, Inc. DISCLAIMER: This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. UNIVERSITY PATENT NOTICE: The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it. PATENT MARKING NOTICE: This software is covered by US Patent No. 8,185,551. This software is covered by US Patent No. 8,489,638. PATENT RIGHTS GRANT: "THIS IMPLEMENTATION" means the copyrightable works distributed by Tokutek as part of the Fractal Tree project. "PATENT CLAIMS" means the claims of patents that are owned or licensable by Tokutek, both currently or in the future; and that in the absence of this license would be infringed by THIS IMPLEMENTATION or by using or running THIS IMPLEMENTATION. "PATENT CHALLENGE" shall mean a challenge to the validity, patentability, enforceability and/or non-infringement of any of the PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS. Tokutek hereby grants to you, for the term and geographical scope of the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer, and otherwise run, modify, and propagate the contents of THIS IMPLEMENTATION, where such license applies only to the PATENT CLAIMS. This grant does not include claims that would be infringed only as a consequence of further modifications of THIS IMPLEMENTATION. If you or your agent or licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that THIS IMPLEMENTATION constitutes direct or contributory patent infringement, or inducement of patent infringement, then any rights granted to you under this License shall terminate as of the date such litigation is filed. If you or your agent or exclusive licensee institute or order or agree to the institution of a PATENT CHALLENGE, then Tokutek may terminate any rights granted to you under this License. */ #ident "Copyright (c) 2007-2013 Tokutek Inc. All rights reserved." #ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it." // Create a lot of dirty nodes, kick off a checkpoint, and close the environment. // Measure the time it takes to close the environment since we are speeding up that // function. #include "test.h" #include <endian.h> #include <toku_time.h> // Insert max_rows key/val pairs into the db static void do_inserts(DB_ENV *env, DB *db, uint64_t max_rows, size_t val_size) { char val_data[val_size]; memset(val_data, 0, val_size); int r; DB_TXN *txn = nullptr; r = env->txn_begin(env, nullptr, &txn, 0); CKERR(r); for (uint64_t i = 1; i <= max_rows; i++) { // pick a sequential key but it does not matter for this test. uint64_t k[2] = { htobe64(i), random64(), }; DBT key = { .data = k, .size = sizeof k }; DBT val = { .data = val_data, .size = (uint32_t) val_size }; r = db->put(db, txn, &key, &val, 0); CKERR(r); if ((i % 1000) == 0) { if (verbose) fprintf(stderr, "put %" PRIu64 "\n", i); r = txn->commit(txn, 0); CKERR(r); r = env->txn_begin(env, nullptr, &txn, 0); CKERR(r); } } r = txn->commit(txn, 0); CKERR(r); } // Create a cache with a lot of dirty nodes, kick off a checkpoint, and measure the time to // close the environment. static void big_shutdown(void) { int r; DB_ENV *env = nullptr; r = db_env_create(&env, 0); CKERR(r); r = env->set_cachesize(env, 8, 0, 1); CKERR(r); r = env->open(env, TOKU_TEST_FILENAME, DB_INIT_MPOOL|DB_CREATE|DB_THREAD |DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_PRIVATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); DB *db = nullptr; r = db_create(&db, env, 0); CKERR(r); r = db->open(db, nullptr, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); do_inserts(env, db, 1000000, 1024); // kick the checkpoint thread if (verbose) fprintf(stderr, "env->checkpointing_set_period\n"); r = env->checkpointing_set_period(env, 2); CKERR(r); sleep(3); if (verbose) fprintf(stderr, "db->close\n"); r = db->close(db, 0); CKERR(r); // measure the shutdown time uint64_t tstart = toku_current_time_microsec(); if (verbose) fprintf(stderr, "env->close\n"); r = env->close(env, 0); CKERR(r); uint64_t tend = toku_current_time_microsec(); if (verbose) fprintf(stderr, "env->close complete %" PRIu64 " sec\n", (tend - tstart)/1000000); } int test_main (int argc, char *const argv[]) { default_parse_args(argc, argv); // init the env directory toku_os_recursive_delete(TOKU_TEST_FILENAME); int r = toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); // run the test big_shutdown(); return 0; } <commit_msg>FT-312 fix centos compile<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /* COPYING CONDITIONS NOTICE: This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation, and provided that the following conditions are met: * Redistributions of source code must retain this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below). * Redistributions in binary form must reproduce this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below) in the documentation and/or other materials provided with the distribution. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. COPYRIGHT NOTICE: TokuDB, Tokutek Fractal Tree Indexing Library. Copyright (C) 2007-2013 Tokutek, Inc. DISCLAIMER: This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. UNIVERSITY PATENT NOTICE: The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it. PATENT MARKING NOTICE: This software is covered by US Patent No. 8,185,551. This software is covered by US Patent No. 8,489,638. PATENT RIGHTS GRANT: "THIS IMPLEMENTATION" means the copyrightable works distributed by Tokutek as part of the Fractal Tree project. "PATENT CLAIMS" means the claims of patents that are owned or licensable by Tokutek, both currently or in the future; and that in the absence of this license would be infringed by THIS IMPLEMENTATION or by using or running THIS IMPLEMENTATION. "PATENT CHALLENGE" shall mean a challenge to the validity, patentability, enforceability and/or non-infringement of any of the PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS. Tokutek hereby grants to you, for the term and geographical scope of the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer, and otherwise run, modify, and propagate the contents of THIS IMPLEMENTATION, where such license applies only to the PATENT CLAIMS. This grant does not include claims that would be infringed only as a consequence of further modifications of THIS IMPLEMENTATION. If you or your agent or licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that THIS IMPLEMENTATION constitutes direct or contributory patent infringement, or inducement of patent infringement, then any rights granted to you under this License shall terminate as of the date such litigation is filed. If you or your agent or exclusive licensee institute or order or agree to the institution of a PATENT CHALLENGE, then Tokutek may terminate any rights granted to you under this License. */ #ident "Copyright (c) 2007-2013 Tokutek Inc. All rights reserved." #ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it." // Create a lot of dirty nodes, kick off a checkpoint, and close the environment. // Measure the time it takes to close the environment since we are speeding up that // function. #include "test.h" #include <endian.h> #include <toku_time.h> #ifndef htobe64 #define htobe64(x) __bswap_64(x) #endif // Insert max_rows key/val pairs into the db static void do_inserts(DB_ENV *env, DB *db, uint64_t max_rows, size_t val_size) { char val_data[val_size]; memset(val_data, 0, val_size); int r; DB_TXN *txn = nullptr; r = env->txn_begin(env, nullptr, &txn, 0); CKERR(r); for (uint64_t i = 1; i <= max_rows; i++) { // pick a sequential key but it does not matter for this test. uint64_t k[2] = { htobe64(i), random64(), }; DBT key = { .data = k, .size = sizeof k }; DBT val = { .data = val_data, .size = (uint32_t) val_size }; r = db->put(db, txn, &key, &val, 0); CKERR(r); if ((i % 1000) == 0) { if (verbose) fprintf(stderr, "put %" PRIu64 "\n", i); r = txn->commit(txn, 0); CKERR(r); r = env->txn_begin(env, nullptr, &txn, 0); CKERR(r); } } r = txn->commit(txn, 0); CKERR(r); } // Create a cache with a lot of dirty nodes, kick off a checkpoint, and measure the time to // close the environment. static void big_shutdown(void) { int r; DB_ENV *env = nullptr; r = db_env_create(&env, 0); CKERR(r); r = env->set_cachesize(env, 8, 0, 1); CKERR(r); r = env->open(env, TOKU_TEST_FILENAME, DB_INIT_MPOOL|DB_CREATE|DB_THREAD |DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_PRIVATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); DB *db = nullptr; r = db_create(&db, env, 0); CKERR(r); r = db->open(db, nullptr, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); do_inserts(env, db, 1000000, 1024); // kick the checkpoint thread if (verbose) fprintf(stderr, "env->checkpointing_set_period\n"); r = env->checkpointing_set_period(env, 2); CKERR(r); sleep(3); if (verbose) fprintf(stderr, "db->close\n"); r = db->close(db, 0); CKERR(r); // measure the shutdown time uint64_t tstart = toku_current_time_microsec(); if (verbose) fprintf(stderr, "env->close\n"); r = env->close(env, 0); CKERR(r); uint64_t tend = toku_current_time_microsec(); if (verbose) fprintf(stderr, "env->close complete %" PRIu64 " sec\n", (tend - tstart)/1000000); } int test_main (int argc, char *const argv[]) { default_parse_args(argc, argv); // init the env directory toku_os_recursive_delete(TOKU_TEST_FILENAME); int r = toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); // run the test big_shutdown(); return 0; } <|endoftext|>
<commit_before>#include <osgText/Text> #include <osgText/Font> #include <iostream> #include <string> #include <osg/Vec3> #include <osg/Vec4> #include <osg/io_utils> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osgDB/ParameterOutput> bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr); bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw); osgDB::RegisterDotOsgWrapperProxy Text_Proxy ( new osgText::Text, "Text", "Object Drawable Text", Text_readLocalData, Text_writeLocalData ); bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr) { osgText::Text &text = static_cast<osgText::Text &>(obj); bool itAdvanced = false; if (fr.matchSequence("font %w")) { text.setFont(fr[1].getStr()); fr += 2; itAdvanced = true; } if (fr[0].matchWord("fontResolution") || fr[0].matchWord("fontSize")) { unsigned int width; unsigned int height; if (fr[1].getUInt(width) && fr[2].getUInt(height)) { text.setFontResolution(width,height); fr += 3; itAdvanced = true; } } if (fr[0].matchWord("characterSize")) { float height; float aspectRatio; if (fr[1].getFloat(height) && fr[2].getFloat(aspectRatio)) { text.setCharacterSize(height,aspectRatio); fr += 3; itAdvanced = true; } } if (fr.matchSequence("characterSizeMode %w")) { std::string str = fr[1].getStr(); if (str=="OBJECT_COORDS") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS); else if (str=="SCREEN_COORDS") text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS); else if (str=="OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT); } // maximum dimentsions of text box. if (fr[0].matchWord("maximumWidth")) { float width; if (fr[1].getFloat(width)) { text.setMaximumWidth(width); fr += 2; itAdvanced = true; } } if (fr[0].matchWord("maximumHeight")) { float height; if (fr[1].getFloat(height)) { text.setMaximumHeight(height); fr += 2; itAdvanced = true; } } if (fr.matchSequence("alignment %w")) { std::string str = fr[1].getStr(); if (str=="LEFT_TOP") text.setAlignment(osgText::Text::LEFT_TOP); else if (str=="LEFT_CENTER") text.setAlignment(osgText::Text::LEFT_CENTER); else if (str=="LEFT_BOTTOM") text.setAlignment(osgText::Text::LEFT_BOTTOM); else if (str=="CENTER_TOP") text.setAlignment(osgText::Text::CENTER_TOP); else if (str=="CENTER_CENTER") text.setAlignment(osgText::Text::CENTER_CENTER); else if (str=="CENTER_BOTTOM") text.setAlignment(osgText::Text::CENTER_BOTTOM); else if (str=="RIGHT_TOP") text.setAlignment(osgText::Text::RIGHT_TOP); else if (str=="RIGHT_CENTER") text.setAlignment(osgText::Text::RIGHT_CENTER); else if (str=="RIGHT_BOTTOM") text.setAlignment(osgText::Text::RIGHT_BOTTOM); else if (str=="LEFT_BASE_LINE") text.setAlignment(osgText::Text::LEFT_BASE_LINE); else if (str=="CENTER_BASE_LINE") text.setAlignment(osgText::Text::CENTER_BASE_LINE); else if (str=="RIGHT_BASE_LINE") text.setAlignment(osgText::Text::RIGHT_BASE_LINE); else if (str=="BASE_LINE") text.setAlignment(osgText::Text::BASE_LINE); fr += 2; itAdvanced = true; } if (fr.matchSequence("axisAlignment %w")) { std::string str = fr[1].getStr(); if (str=="XY_PLANE") text.setAxisAlignment(osgText::Text::XY_PLANE); else if (str=="REVERSED_XY_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_XY_PLANE); else if (str=="XZ_PLANE") text.setAxisAlignment(osgText::Text::XZ_PLANE); else if (str=="REVERSED_XZ_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_XZ_PLANE); else if (str=="YZ_PLANE") text.setAxisAlignment(osgText::Text::YZ_PLANE); else if (str=="REVERSED_YZ_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_YZ_PLANE); else if (str=="SCREEN") text.setAxisAlignment(osgText::Text::SCREEN); fr += 2; itAdvanced = true; } if (fr.matchSequence("rotation")) { osg::Vec4 rotation; if (fr[1].getFloat(rotation.x()) && fr[2].getFloat(rotation.y()) && fr[3].getFloat(rotation.z()) && fr[4].getFloat(rotation.w())) { text.setRotation(rotation); fr += 4; itAdvanced = true; } } if (fr.matchSequence("autoRotateToScreen TRUE")) { text.setAutoRotateToScreen(true); fr += 2; itAdvanced = true; } if (fr.matchSequence("autoScaleToLimitScreenSizeToFontResolution TRUE")) { text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS); fr += 2; itAdvanced = true; } if (fr.matchSequence("layout %w") && fr[1].getStr()) { std::string str = fr[1].getStr(); if (str=="LEFT_TO_RIGHT") text.setLayout(osgText::Text::LEFT_TO_RIGHT); else if (str=="RIGHT_TO_LEFT") text.setLayout(osgText::Text::RIGHT_TO_LEFT); else if (str=="VERTICAL") text.setLayout(osgText::Text::VERTICAL); fr += 2; itAdvanced = true; } // position if (fr[0].matchWord("position")) { osg::Vec3 p; if (fr[1].getFloat(p.x()) && fr[2].getFloat(p.y()) && fr[3].getFloat(p.z())) { text.setPosition(p); fr += 4; itAdvanced = true; } } // color if (fr[0].matchWord("color")) { osg::Vec4 c; if (fr[1].getFloat(c.x()) && fr[2].getFloat(c.y()) && fr[3].getFloat(c.z()) && fr[4].getFloat(c.w())) { text.setColor(c); fr += 4; itAdvanced = true; } } // draw mode if (fr[0].matchWord("drawMode")) { int i; if (fr[1].getInt(i)) { text.setDrawMode(i); fr += 2; itAdvanced = true; } } // text if (fr.matchSequence("text %s") && fr[1].getStr()) { text.setText(std::string(fr[1].getStr())); fr += 2; itAdvanced = true; } if (fr.matchSequence("text %i {")) { // pre 0.9.3 releases.. int entry = fr[0].getNoNestedBrackets(); int capacity; fr[1].getInt(capacity); osgText::String str; str.reserve(capacity); fr += 3; while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int c; if (fr[0].getUInt(c)) { ++fr; str.push_back(c); } else { ++fr; } } text.setText(str); itAdvanced = true; ++fr; } return itAdvanced; } bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw) { const osgText::Text &text = static_cast<const osgText::Text &>(obj); if (text.getFont()) { fw.indent() << "font " << text.getFont()->getFileName() << std::endl; } // font resolution fw.indent() << "fontResolution " << text.getFontWidth() << " " << text.getFontHeight() << std::endl; // charater size. fw.indent() << "characterSize " << text.getCharacterHeight() << " " << text.getCharacterAspectRatio() << std::endl; fw.indent() << "characterSizeMode "; switch(text.getCharacterSizeMode()) { case osgText::Text::OBJECT_COORDS : fw<<"OBJECT_COORDS"<<std::endl; break; case osgText::Text::SCREEN_COORDS : fw<<"SCREEN_COORDS"<<std::endl; break; case osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT: fw<<"OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT"<<std::endl; break; } // maximum dimension of text box. if (text.getMaximumWidth()>0.0f) { fw.indent() << "maximumWidth " << text.getMaximumWidth() << std::endl; } if (text.getMaximumHeight()>0.0f) { fw.indent() << "maximumHeight " << text.getMaximumHeight() << std::endl; } // alignment fw.indent() << "alignment "; switch(text.getAlignment()) { case osgText::Text::LEFT_TOP: fw << "LEFT_TOP" << std::endl; break; case osgText::Text::LEFT_CENTER : fw << "LEFT_CENTER" << std::endl; break; case osgText::Text::LEFT_BOTTOM : fw << "LEFT_BOTTOM" << std::endl; break; case osgText::Text::CENTER_TOP: fw << "CENTER_TOP" << std::endl; break; case osgText::Text::CENTER_CENTER: fw << "CENTER_CENTER" << std::endl; break; case osgText::Text::CENTER_BOTTOM: fw << "CENTER_BOTTOM" << std::endl; break; case osgText::Text::RIGHT_TOP: fw << "RIGHT_TOP" << std::endl; break; case osgText::Text::RIGHT_CENTER: fw << "RIGHT_CENTER" << std::endl; break; case osgText::Text::RIGHT_BOTTOM: fw << "RIGHT_BOTTOM" << std::endl; break; case osgText::Text::LEFT_BASE_LINE: fw << "LEFT_BASE_LINE" << std::endl; break; case osgText::Text::CENTER_BASE_LINE:fw << "CENTER_BASE_LINE" << std::endl; break; case osgText::Text::RIGHT_BASE_LINE: fw << "RIGHT_BASE_LINE" << std::endl; break; }; if (!text.getRotation().zeroRotation()) { fw.indent() << "rotation " << text.getRotation() << std::endl; } if (text.getAutoRotateToScreen()) { fw.indent() << "autoRotateToScreen TRUE"<< std::endl; } // layout fw.indent() << "layout "; switch(text.getLayout()) { case osgText::Text::LEFT_TO_RIGHT: fw << "LEFT_TO_RIGHT" << std::endl; break; case osgText::Text::RIGHT_TO_LEFT: fw << "RIGHT_TO_LEFT" << std::endl; break; case osgText::Text::VERTICAL: fw << "VERTICAL" << std::endl; break; }; // position osg::Vec3 p = text.getPosition(); fw.indent() << "position " << p.x() << " " << p.y() << " " << p.z() << std::endl; // color osg::Vec4 c = text.getColor(); fw.indent() << "color " << c.x() << " " << c.y() << " " << c.z() << " " << c.w() << std::endl; // draw mode fw.indent() << "drawMode " << text.getDrawMode() << std::endl; // text const osgText::String& textstring = text.getText(); bool isACString = true; osgText::String::const_iterator itr; for(itr=textstring.begin(); itr!=textstring.end() && isACString; ++itr) { if (*itr==0 || *itr>256) isACString=false; } if (isACString) { std::string str; for(itr=textstring.begin(); itr!=textstring.end(); ++itr) { str += (char)(*itr); } //std::copy(textstring.begin(),textstring.end(),std::back_inserter(str)); fw.indent() << "text " << fw.wrapString(str) << std::endl; } else { // do it the hardway...output each character as an int fw.indent() << "text "<<textstring.size()<<std::endl;; osgDB::writeArray(fw,textstring.begin(),textstring.end()); } return true; } <commit_msg>Added .osg suppot for new alignment modes<commit_after>#include <osgText/Text> #include <osgText/Font> #include <iostream> #include <string> #include <osg/Vec3> #include <osg/Vec4> #include <osg/io_utils> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osgDB/ParameterOutput> bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr); bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw); osgDB::RegisterDotOsgWrapperProxy Text_Proxy ( new osgText::Text, "Text", "Object Drawable Text", Text_readLocalData, Text_writeLocalData ); bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr) { osgText::Text &text = static_cast<osgText::Text &>(obj); bool itAdvanced = false; if (fr.matchSequence("font %w")) { text.setFont(fr[1].getStr()); fr += 2; itAdvanced = true; } if (fr[0].matchWord("fontResolution") || fr[0].matchWord("fontSize")) { unsigned int width; unsigned int height; if (fr[1].getUInt(width) && fr[2].getUInt(height)) { text.setFontResolution(width,height); fr += 3; itAdvanced = true; } } if (fr[0].matchWord("characterSize")) { float height; float aspectRatio; if (fr[1].getFloat(height) && fr[2].getFloat(aspectRatio)) { text.setCharacterSize(height,aspectRatio); fr += 3; itAdvanced = true; } } if (fr.matchSequence("characterSizeMode %w")) { std::string str = fr[1].getStr(); if (str=="OBJECT_COORDS") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS); else if (str=="SCREEN_COORDS") text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS); else if (str=="OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT); } // maximum dimentsions of text box. if (fr[0].matchWord("maximumWidth")) { float width; if (fr[1].getFloat(width)) { text.setMaximumWidth(width); fr += 2; itAdvanced = true; } } if (fr[0].matchWord("maximumHeight")) { float height; if (fr[1].getFloat(height)) { text.setMaximumHeight(height); fr += 2; itAdvanced = true; } } if (fr.matchSequence("alignment %w")) { std::string str = fr[1].getStr(); if (str=="LEFT_TOP") text.setAlignment(osgText::Text::LEFT_TOP); else if (str=="LEFT_CENTER") text.setAlignment(osgText::Text::LEFT_CENTER); else if (str=="LEFT_BOTTOM") text.setAlignment(osgText::Text::LEFT_BOTTOM); else if (str=="CENTER_TOP") text.setAlignment(osgText::Text::CENTER_TOP); else if (str=="CENTER_CENTER") text.setAlignment(osgText::Text::CENTER_CENTER); else if (str=="CENTER_BOTTOM") text.setAlignment(osgText::Text::CENTER_BOTTOM); else if (str=="RIGHT_TOP") text.setAlignment(osgText::Text::RIGHT_TOP); else if (str=="RIGHT_CENTER") text.setAlignment(osgText::Text::RIGHT_CENTER); else if (str=="RIGHT_BOTTOM") text.setAlignment(osgText::Text::RIGHT_BOTTOM); else if (str=="LEFT_BASE_LINE") text.setAlignment(osgText::Text::LEFT_BASE_LINE); else if (str=="CENTER_BASE_LINE") text.setAlignment(osgText::Text::CENTER_BASE_LINE); else if (str=="RIGHT_BASE_LINE") text.setAlignment(osgText::Text::RIGHT_BASE_LINE); else if (str=="LEFT_BOTTOM_BASE_LINE") text.setAlignment(osgText::Text::LEFT_BOTTOM_BASE_LINE); else if (str=="CENTER_BOTTOM_BASE_LINE") text.setAlignment(osgText::Text::CENTER_BOTTOM_BASE_LINE); else if (str=="RIGHT_BOTTOM_BASE_LINE") text.setAlignment(osgText::Text::RIGHT_BOTTOM_BASE_LINE); else if (str=="BASE_LINE") text.setAlignment(osgText::Text::BASE_LINE); fr += 2; itAdvanced = true; } if (fr.matchSequence("axisAlignment %w")) { std::string str = fr[1].getStr(); if (str=="XY_PLANE") text.setAxisAlignment(osgText::Text::XY_PLANE); else if (str=="REVERSED_XY_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_XY_PLANE); else if (str=="XZ_PLANE") text.setAxisAlignment(osgText::Text::XZ_PLANE); else if (str=="REVERSED_XZ_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_XZ_PLANE); else if (str=="YZ_PLANE") text.setAxisAlignment(osgText::Text::YZ_PLANE); else if (str=="REVERSED_YZ_PLANE") text.setAxisAlignment(osgText::Text::REVERSED_YZ_PLANE); else if (str=="SCREEN") text.setAxisAlignment(osgText::Text::SCREEN); fr += 2; itAdvanced = true; } if (fr.matchSequence("rotation")) { osg::Vec4 rotation; if (fr[1].getFloat(rotation.x()) && fr[2].getFloat(rotation.y()) && fr[3].getFloat(rotation.z()) && fr[4].getFloat(rotation.w())) { text.setRotation(rotation); fr += 4; itAdvanced = true; } } if (fr.matchSequence("autoRotateToScreen TRUE")) { text.setAutoRotateToScreen(true); fr += 2; itAdvanced = true; } if (fr.matchSequence("autoScaleToLimitScreenSizeToFontResolution TRUE")) { text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS); fr += 2; itAdvanced = true; } if (fr.matchSequence("layout %w") && fr[1].getStr()) { std::string str = fr[1].getStr(); if (str=="LEFT_TO_RIGHT") text.setLayout(osgText::Text::LEFT_TO_RIGHT); else if (str=="RIGHT_TO_LEFT") text.setLayout(osgText::Text::RIGHT_TO_LEFT); else if (str=="VERTICAL") text.setLayout(osgText::Text::VERTICAL); fr += 2; itAdvanced = true; } // position if (fr[0].matchWord("position")) { osg::Vec3 p; if (fr[1].getFloat(p.x()) && fr[2].getFloat(p.y()) && fr[3].getFloat(p.z())) { text.setPosition(p); fr += 4; itAdvanced = true; } } // color if (fr[0].matchWord("color")) { osg::Vec4 c; if (fr[1].getFloat(c.x()) && fr[2].getFloat(c.y()) && fr[3].getFloat(c.z()) && fr[4].getFloat(c.w())) { text.setColor(c); fr += 4; itAdvanced = true; } } // draw mode if (fr[0].matchWord("drawMode")) { int i; if (fr[1].getInt(i)) { text.setDrawMode(i); fr += 2; itAdvanced = true; } } // text if (fr.matchSequence("text %s") && fr[1].getStr()) { text.setText(std::string(fr[1].getStr())); fr += 2; itAdvanced = true; } if (fr.matchSequence("text %i {")) { // pre 0.9.3 releases.. int entry = fr[0].getNoNestedBrackets(); int capacity; fr[1].getInt(capacity); osgText::String str; str.reserve(capacity); fr += 3; while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { unsigned int c; if (fr[0].getUInt(c)) { ++fr; str.push_back(c); } else { ++fr; } } text.setText(str); itAdvanced = true; ++fr; } return itAdvanced; } bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw) { const osgText::Text &text = static_cast<const osgText::Text &>(obj); if (text.getFont()) { fw.indent() << "font " << text.getFont()->getFileName() << std::endl; } // font resolution fw.indent() << "fontResolution " << text.getFontWidth() << " " << text.getFontHeight() << std::endl; // charater size. fw.indent() << "characterSize " << text.getCharacterHeight() << " " << text.getCharacterAspectRatio() << std::endl; fw.indent() << "characterSizeMode "; switch(text.getCharacterSizeMode()) { case osgText::Text::OBJECT_COORDS : fw<<"OBJECT_COORDS"<<std::endl; break; case osgText::Text::SCREEN_COORDS : fw<<"SCREEN_COORDS"<<std::endl; break; case osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT: fw<<"OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT"<<std::endl; break; } // maximum dimension of text box. if (text.getMaximumWidth()>0.0f) { fw.indent() << "maximumWidth " << text.getMaximumWidth() << std::endl; } if (text.getMaximumHeight()>0.0f) { fw.indent() << "maximumHeight " << text.getMaximumHeight() << std::endl; } // alignment fw.indent() << "alignment "; switch(text.getAlignment()) { case osgText::Text::LEFT_TOP: fw << "LEFT_TOP" << std::endl; break; case osgText::Text::LEFT_CENTER : fw << "LEFT_CENTER" << std::endl; break; case osgText::Text::LEFT_BOTTOM : fw << "LEFT_BOTTOM" << std::endl; break; case osgText::Text::CENTER_TOP: fw << "CENTER_TOP" << std::endl; break; case osgText::Text::CENTER_CENTER: fw << "CENTER_CENTER" << std::endl; break; case osgText::Text::CENTER_BOTTOM: fw << "CENTER_BOTTOM" << std::endl; break; case osgText::Text::RIGHT_TOP: fw << "RIGHT_TOP" << std::endl; break; case osgText::Text::RIGHT_CENTER: fw << "RIGHT_CENTER" << std::endl; break; case osgText::Text::RIGHT_BOTTOM: fw << "RIGHT_BOTTOM" << std::endl; break; case osgText::Text::LEFT_BASE_LINE: fw << "LEFT_BASE_LINE" << std::endl; break; case osgText::Text::CENTER_BASE_LINE:fw << "CENTER_BASE_LINE" << std::endl; break; case osgText::Text::RIGHT_BASE_LINE: fw << "RIGHT_BASE_LINE" << std::endl; break; case osgText::Text::LEFT_BOTTOM_BASE_LINE: fw << "LEFT_BOTTOM_BASE_LINE" << std::endl; break; case osgText::Text::CENTER_BOTTOM_BASE_LINE:fw << "CENTER_BOTTOM_BASE_LINE" << std::endl; break; case osgText::Text::RIGHT_BOTTOM_BASE_LINE: fw << "RIGHT_BOTTOM_BASE_LINE" << std::endl; break; }; if (!text.getRotation().zeroRotation()) { fw.indent() << "rotation " << text.getRotation() << std::endl; } if (text.getAutoRotateToScreen()) { fw.indent() << "autoRotateToScreen TRUE"<< std::endl; } // layout fw.indent() << "layout "; switch(text.getLayout()) { case osgText::Text::LEFT_TO_RIGHT: fw << "LEFT_TO_RIGHT" << std::endl; break; case osgText::Text::RIGHT_TO_LEFT: fw << "RIGHT_TO_LEFT" << std::endl; break; case osgText::Text::VERTICAL: fw << "VERTICAL" << std::endl; break; }; // position osg::Vec3 p = text.getPosition(); fw.indent() << "position " << p.x() << " " << p.y() << " " << p.z() << std::endl; // color osg::Vec4 c = text.getColor(); fw.indent() << "color " << c.x() << " " << c.y() << " " << c.z() << " " << c.w() << std::endl; // draw mode fw.indent() << "drawMode " << text.getDrawMode() << std::endl; // text const osgText::String& textstring = text.getText(); bool isACString = true; osgText::String::const_iterator itr; for(itr=textstring.begin(); itr!=textstring.end() && isACString; ++itr) { if (*itr==0 || *itr>256) isACString=false; } if (isACString) { std::string str; for(itr=textstring.begin(); itr!=textstring.end(); ++itr) { str += (char)(*itr); } //std::copy(textstring.begin(),textstring.end(),std::back_inserter(str)); fw.indent() << "text " << fw.wrapString(str) << std::endl; } else { // do it the hardway...output each character as an int fw.indent() << "text "<<textstring.size()<<std::endl;; osgDB::writeArray(fw,textstring.begin(),textstring.end()); } return true; } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/ApplicationUsage> #include <osg/Timer> #include <osg/Notify> #include <osgUtil/DisplayRequirementsVisitor> #include <osgDB/FileUtils> #include <osgProducer/OsgCameraGroup> using namespace Producer; using namespace osgProducer; class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback { public: RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler): _cameraGroup(cameraGroup), _sceneHandler(sceneHandler) {} virtual void operator()( const Producer::RenderSurface & rs) { osg::Timer timer; osg::Timer_t start_t = timer.tick(); if (_cameraGroup->getRealizeCallback()) { (*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs); } else if (_sceneHandler) _sceneHandler->init(); osg::Timer_t end_t = timer.tick(); double time = timer.delta_m(start_t,end_t); osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl; } OsgCameraGroup* _cameraGroup; OsgSceneHandler* _sceneHandler; }; std::string findCameraConfigFile(const std::string& configFile) { std::string foundFile = osgDB::findDataFile(configFile); if (foundFile.empty()) return ""; else return foundFile; } std::string extractCameraConfigFile(osg::ArgumentParser& arguments) { // report the usage options. if (arguments.getApplicationUsage()) { arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file"); } std::string filename; if (arguments.read("-c",filename)) return findCameraConfigFile(filename); char *ptr; if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) ) { osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl; return findCameraConfigFile(ptr); } return ""; } OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup() { _init(); _applicationUsage = osg::ApplicationUsage::instance(); } OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg): Producer::CameraGroup(cfg) { _init(); _applicationUsage = osg::ApplicationUsage::instance(); } OsgCameraGroup::OsgCameraGroup(const std::string& configFile): Producer::CameraGroup(findCameraConfigFile(configFile)) { _init(); _applicationUsage = osg::ApplicationUsage::instance(); } OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments): Producer::CameraGroup(extractCameraConfigFile(arguments)) { _init(); _applicationUsage = arguments.getApplicationUsage(); } void OsgCameraGroup::_init() { _thread_model = ThreadPerCamera; _scene_data = NULL; _global_stateset = NULL; _background_color.set( 0.2f, 0.2f, 0.4f, 1.0f ); _LODScale = 1.0f; _fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE; _fusionDistanceValue = 1.0f; _initialized = false; if (!_frameStamp) _frameStamp = new osg::FrameStamp; // set up the maximum number of graphics contexts, before loading the scene graph // to ensure that texture objects and display buffers are configured to the correct size. osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() ); } void OsgCameraGroup::setSceneData( osg::Node *scene ) { if (_scene_data==scene) return; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->removeChild(_scene_data.get()); } _scene_data = scene; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->addChild(scene); } setUpSceneViewsWithData(); } void OsgCameraGroup::setSceneDecorator( osg::Group* decorator) { if (_scene_decorator==decorator) return; _scene_decorator = decorator; if (_scene_data.valid() && decorator) { decorator->addChild(_scene_data.get()); } setUpSceneViewsWithData(); } void OsgCameraGroup::setUpSceneViewsWithData() { for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ ) { if (_scene_decorator.valid()) { (*p)->setSceneData( _scene_decorator.get() ); } else if (_scene_data.valid()) { (*p)->setSceneData( _scene_data.get() ); } else { (*p)->setSceneData( 0 ); } (*p)->setFrameStamp( _frameStamp.get() ); (*p)->setGlobalStateSet( _global_stateset.get() ); (*p)->setBackgroundColor( _background_color ); (*p)->setLODScale( _LODScale ); (*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue ); (*p)->getState()->reset(); } } void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs ) { _frameStamp = fs; setUpSceneViewsWithData(); } void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset ) { _global_stateset = sset; setUpSceneViewsWithData(); } void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor ) { _background_color = backgroundColor; setUpSceneViewsWithData(); } void OsgCameraGroup::setLODScale( float scale ) { // need to set a local variable? _LODScale = scale; setUpSceneViewsWithData(); } void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value) { // need to set a local variable? _fusionDistanceMode = mode; _fusionDistanceValue = value; setUpSceneViewsWithData(); } void OsgCameraGroup::advance() { if( !_initialized ) return; CameraGroup::advance(); } bool OsgCameraGroup::realize( ThreadingModel thread_model ) { if( _realized ) return _realized; _thread_model = thread_model; return realize(); } // small visitor to check for the existance of particle systems, // which currently arn't thread safe, so we would need to disable // multithreading of cull and draw. class SearchForParticleNodes : public osg::NodeVisitor { public: SearchForParticleNodes(): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _foundParticles(false) { } virtual void apply(osg::Node& node) { if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true; if (!_foundParticles) traverse(node); } bool _foundParticles; }; bool OsgCameraGroup::realize() { if( _initialized ) return _realized; if (!_ds) _ds = osg::DisplaySettings::instance(); _ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() ); _shvec.clear(); osg::Node* node = getTopMostSceneData(); if (node) { // traverse the scene graphs gathering the requirements of the OpenGL buffers. osgUtil::DisplayRequirementsVisitor drv; drv.setDisplaySettings(_ds.get()); node->accept(drv); } unsigned int numMultiSamples = 0; #ifdef __sgi // switch on anti-aliasing by default, just in case we have an Onyx :-) numMultiSamples = 4; #endif // set up each render stage to clear the appropriate buffers. GLbitfield clear_mask=0; if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT; if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT; if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT; for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ ) { Producer::Camera *cam = _cfg->getCamera(i); // create the scene handler. osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get()); sh->setDefaults(); sh->getState()->setContextID(i); _shvec.push_back( sh ); cam->setSceneHandler( sh ); // set up the clear mask. osgUtil::RenderStage *stage = sh->getRenderStage(); if (stage) stage->setClearMask(clear_mask); // set the realize callback. Producer::RenderSurface* rs = cam->getRenderSurface(); rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh)); // set up the visual chooser. if (_ds.valid() || numMultiSamples!=0) { Producer::VisualChooser* rs_vc = rs->getVisualChooser(); if (!rs_vc) { rs_vc = new Producer::VisualChooser; rs_vc->setSimpleConfiguration(); rs->setVisualChooser(rs_vc); } if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo(); if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits()); if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits()); rs_vc->setDepthSize(24); if (numMultiSamples) { #if defined( GLX_SAMPLES_SGIS ) rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples); #endif #if defined( GLX_SAMPLES_BUFFER_SGIS ) rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1); #endif } } } if( _global_stateset == NULL && _shvec.size() > 0 ) { SceneHandlerList::iterator p = _shvec.begin(); _global_stateset = (*p)->getGlobalStateSet(); } setUpSceneViewsWithData(); if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded) { SearchForParticleNodes sfpn; getTopMostSceneData()->accept(sfpn); if (sfpn._foundParticles) { osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl; osg::notify(osg::INFO)<<" to avoid threading problems in osgParticle."<<std::endl; _thread_model = Producer::CameraGroup::SingleThreaded; } } _initialized = CameraGroup::realize(); return _initialized; } osg::Node* OsgCameraGroup::getTopMostSceneData() { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } const osg::Node* OsgCameraGroup::getTopMostSceneData() const { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } void OsgCameraGroup::setView(const osg::Matrix& matrix) { Producer::Matrix pm(matrix.ptr()); CameraGroup::setView(pm); } const osg::Matrix OsgCameraGroup::getViewMatrix() const { osg::Matrix matrix; if (_cfg && _cfg->getNumberOfCameras()>=1) { Producer::Camera *cam = _cfg->getCamera(0); matrix.set(cam->getViewMatrix()); } return matrix; } void OsgCameraGroup::frame() { osg::Node* node = getTopMostSceneData(); if (node) node->getBound(); CameraGroup::frame(); _frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 ); } <commit_msg>Added a setting of OsgCameraGroup::_applicateUsage to ApplicationUsage::instance() by default.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/ApplicationUsage> #include <osg/Timer> #include <osg/Notify> #include <osgUtil/DisplayRequirementsVisitor> #include <osgDB/FileUtils> #include <osgProducer/OsgCameraGroup> using namespace Producer; using namespace osgProducer; class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback { public: RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler): _cameraGroup(cameraGroup), _sceneHandler(sceneHandler) {} virtual void operator()( const Producer::RenderSurface & rs) { osg::Timer timer; osg::Timer_t start_t = timer.tick(); if (_cameraGroup->getRealizeCallback()) { (*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs); } else if (_sceneHandler) _sceneHandler->init(); osg::Timer_t end_t = timer.tick(); double time = timer.delta_m(start_t,end_t); osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl; } OsgCameraGroup* _cameraGroup; OsgSceneHandler* _sceneHandler; }; std::string findCameraConfigFile(const std::string& configFile) { std::string foundFile = osgDB::findDataFile(configFile); if (foundFile.empty()) return ""; else return foundFile; } std::string extractCameraConfigFile(osg::ArgumentParser& arguments) { // report the usage options. if (arguments.getApplicationUsage()) { arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file"); } std::string filename; if (arguments.read("-c",filename)) return findCameraConfigFile(filename); char *ptr; if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) ) { osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl; return findCameraConfigFile(ptr); } return ""; } OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup() { _init(); } OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg): Producer::CameraGroup(cfg) { _init(); } OsgCameraGroup::OsgCameraGroup(const std::string& configFile): Producer::CameraGroup(findCameraConfigFile(configFile)) { _init(); } OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments): Producer::CameraGroup(extractCameraConfigFile(arguments)) { _init(); _applicationUsage = arguments.getApplicationUsage(); } void OsgCameraGroup::_init() { _thread_model = ThreadPerCamera; _scene_data = NULL; _global_stateset = NULL; _background_color.set( 0.2f, 0.2f, 0.4f, 1.0f ); _LODScale = 1.0f; _fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE; _fusionDistanceValue = 1.0f; _initialized = false; if (!_frameStamp) _frameStamp = new osg::FrameStamp; // set up the maximum number of graphics contexts, before loading the scene graph // to ensure that texture objects and display buffers are configured to the correct size. osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() ); _applicationUsage = osg::ApplicationUsage::instance(); } void OsgCameraGroup::setSceneData( osg::Node *scene ) { if (_scene_data==scene) return; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->removeChild(_scene_data.get()); } _scene_data = scene; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->addChild(scene); } setUpSceneViewsWithData(); } void OsgCameraGroup::setSceneDecorator( osg::Group* decorator) { if (_scene_decorator==decorator) return; _scene_decorator = decorator; if (_scene_data.valid() && decorator) { decorator->addChild(_scene_data.get()); } setUpSceneViewsWithData(); } void OsgCameraGroup::setUpSceneViewsWithData() { for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ ) { if (_scene_decorator.valid()) { (*p)->setSceneData( _scene_decorator.get() ); } else if (_scene_data.valid()) { (*p)->setSceneData( _scene_data.get() ); } else { (*p)->setSceneData( 0 ); } (*p)->setFrameStamp( _frameStamp.get() ); (*p)->setGlobalStateSet( _global_stateset.get() ); (*p)->setBackgroundColor( _background_color ); (*p)->setLODScale( _LODScale ); (*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue ); (*p)->getState()->reset(); } } void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs ) { _frameStamp = fs; setUpSceneViewsWithData(); } void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset ) { _global_stateset = sset; setUpSceneViewsWithData(); } void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor ) { _background_color = backgroundColor; setUpSceneViewsWithData(); } void OsgCameraGroup::setLODScale( float scale ) { // need to set a local variable? _LODScale = scale; setUpSceneViewsWithData(); } void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value) { // need to set a local variable? _fusionDistanceMode = mode; _fusionDistanceValue = value; setUpSceneViewsWithData(); } void OsgCameraGroup::advance() { if( !_initialized ) return; CameraGroup::advance(); } bool OsgCameraGroup::realize( ThreadingModel thread_model ) { if( _realized ) return _realized; _thread_model = thread_model; return realize(); } // small visitor to check for the existance of particle systems, // which currently arn't thread safe, so we would need to disable // multithreading of cull and draw. class SearchForParticleNodes : public osg::NodeVisitor { public: SearchForParticleNodes(): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _foundParticles(false) { } virtual void apply(osg::Node& node) { if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true; if (!_foundParticles) traverse(node); } bool _foundParticles; }; bool OsgCameraGroup::realize() { if( _initialized ) return _realized; if (!_ds) _ds = osg::DisplaySettings::instance(); _ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() ); _shvec.clear(); osg::Node* node = getTopMostSceneData(); if (node) { // traverse the scene graphs gathering the requirements of the OpenGL buffers. osgUtil::DisplayRequirementsVisitor drv; drv.setDisplaySettings(_ds.get()); node->accept(drv); } unsigned int numMultiSamples = 0; #ifdef __sgi // switch on anti-aliasing by default, just in case we have an Onyx :-) numMultiSamples = 4; #endif // set up each render stage to clear the appropriate buffers. GLbitfield clear_mask=0; if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT; if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT; if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT; for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ ) { Producer::Camera *cam = _cfg->getCamera(i); // create the scene handler. osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get()); sh->setDefaults(); sh->getState()->setContextID(i); _shvec.push_back( sh ); cam->setSceneHandler( sh ); // set up the clear mask. osgUtil::RenderStage *stage = sh->getRenderStage(); if (stage) stage->setClearMask(clear_mask); // set the realize callback. Producer::RenderSurface* rs = cam->getRenderSurface(); rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh)); // set up the visual chooser. if (_ds.valid() || numMultiSamples!=0) { Producer::VisualChooser* rs_vc = rs->getVisualChooser(); if (!rs_vc) { rs_vc = new Producer::VisualChooser; rs_vc->setSimpleConfiguration(); rs->setVisualChooser(rs_vc); } if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo(); if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits()); if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits()); rs_vc->setDepthSize(24); if (numMultiSamples) { #if defined( GLX_SAMPLES_SGIS ) rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples); #endif #if defined( GLX_SAMPLES_BUFFER_SGIS ) rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1); #endif } } } if( _global_stateset == NULL && _shvec.size() > 0 ) { SceneHandlerList::iterator p = _shvec.begin(); _global_stateset = (*p)->getGlobalStateSet(); } setUpSceneViewsWithData(); if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded) { SearchForParticleNodes sfpn; getTopMostSceneData()->accept(sfpn); if (sfpn._foundParticles) { osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl; osg::notify(osg::INFO)<<" to avoid threading problems in osgParticle."<<std::endl; _thread_model = Producer::CameraGroup::SingleThreaded; } } _initialized = CameraGroup::realize(); return _initialized; } osg::Node* OsgCameraGroup::getTopMostSceneData() { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } const osg::Node* OsgCameraGroup::getTopMostSceneData() const { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } void OsgCameraGroup::setView(const osg::Matrix& matrix) { Producer::Matrix pm(matrix.ptr()); CameraGroup::setView(pm); } const osg::Matrix OsgCameraGroup::getViewMatrix() const { osg::Matrix matrix; if (_cfg && _cfg->getNumberOfCameras()>=1) { Producer::Camera *cam = _cfg->getCamera(0); matrix.set(cam->getViewMatrix()); } return matrix; } void OsgCameraGroup::frame() { osg::Node* node = getTopMostSceneData(); if (node) node->getBound(); CameraGroup::frame(); _frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 ); } <|endoftext|>
<commit_before> #include "ui_sc_editor.h" #include <Scintilla.h> namespace ImGui { /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FillRect(ImVec2 pos, ImVec2 size, unsigned int color) { ImGuiWindow* window = GetCurrentWindow(); ImVec2 currentPos = window->Pos + pos; window->DrawList->AddRectFilled(currentPos, currentPos + size, color, 0.0); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float GetTextWidth(const char* textStart, const char* textEnd) { ImVec2 size = CalcTextSize(textStart, textEnd); return size.x; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ImVec2 GetRelativeMousePos() { const ImGuiState* g = GImGui; ImGuiWindow* window = GetCurrentWindow(); ImVec2 pos = g->IO.MousePos - window->Pos; ImVec2 zero = ImVec2(0.0f, 0.0f); return ImClamp(pos, zero, window->Size); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool IsFocusWindowKeyDown(int key, bool repeat) { if (!GetWindowIsFocused()) return false; //ImGuiState& g = GImGui; //ImGuiWindow* window = GetCurrentWindow(); // Only send keyboard events to selected window //if (g.FocusedWindow != window) // return false; return IsKeyPressed(key, repeat); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GetWindowRect(ImGuiWindow* window, ImVec2* pos, ImVec2* size) { *pos = window->Pos; *size = window->Size; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void SetWindowRect(ImGuiWindow* window, const ImVec2 pos, const ImVec2 size) { window->PosFloat = pos; window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); window->Size = size; window->SizeFull = size; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool IsActiveWindow(ImGuiWindow* window) { const ImGuiState* g = GImGui; return g->FocusedWindow == window; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ImScEditor* ScInputText(const char* label, float xSize, float ySize, void (*callback)(void*), void* userData) { ImGuiWindow* window = GetCurrentWindow(); const ImGuiID id = window->GetID(label); (void)callback; (void)userData; ImGui::BeginChild("Log"); ImGuiStorage* storage = GetStateStorage(); ScEditor* editor = (ScEditor*)storage->GetVoidPtr(id); if (!editor) { (void)xSize; (void)ySize; editor = ScEditor_create((int)xSize, (int)ySize); storage->SetVoidPtr(id, (void*)editor); } ImScEditor* editorInterface = ScEditor_getInterface(editor); //float textSize = ImGui::GetTextLineHeightWithSpacing() - 1; // TODO: Remove hardcoded value, ask scintilla float textSize = 26; ScEditor_resize(editor, 0, 0, (int)window->Size.x - 20, (int)window->Size.y); int lineCount = (int)editorInterface->SendCommand(SCI_GETLINECOUNT, 0, 0); editorInterface->HandleInput(); ImGuiListClipper clipper(lineCount, textSize); //ImVec2 pos = window->DC.CursorPos; ScEditor_setDrawList(GetWindowDrawList()); ScEditor_setFont(GetWindowFont()); ScEditor_setPos(0.0f, 0.0f); //int currentPos = (int)editorInterface->SendCommand(SCN_GETTOPLINE, 0, 0); //float scrollPos = ImGui::GetScrollPosY(); //int iPos = (int)(((int)ImGui::GetScrollPosY()) / (int)(textSize)); //if (currentPos != iPos) //{ editorInterface->ScrollTo(clipper.DisplayStart); //} //printf("current pos in scintilla %d - pos sent %d\n", newPos, iPos); clipper.End(); ImGui::EndChild(); return editorInterface; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } <commit_msg>Removed usage of GetWindowIsFocused (deprecated)<commit_after> #include "ui_sc_editor.h" #include <Scintilla.h> namespace ImGui { /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FillRect(ImVec2 pos, ImVec2 size, unsigned int color) { ImGuiWindow* window = GetCurrentWindow(); ImVec2 currentPos = window->Pos + pos; window->DrawList->AddRectFilled(currentPos, currentPos + size, color, 0.0); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float GetTextWidth(const char* textStart, const char* textEnd) { ImVec2 size = CalcTextSize(textStart, textEnd); return size.x; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ImVec2 GetRelativeMousePos() { const ImGuiState* g = GImGui; ImGuiWindow* window = GetCurrentWindow(); ImVec2 pos = g->IO.MousePos - window->Pos; ImVec2 zero = ImVec2(0.0f, 0.0f); return ImClamp(pos, zero, window->Size); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool IsFocusWindowKeyDown(int key, bool repeat) { if (!IsWindowFocused()) return false; //if (!GetWindowIsFocused()) // return false; //ImGuiState& g = GImGui; //ImGuiWindow* window = GetCurrentWindow(); // Only send keyboard events to selected window //if (g.FocusedWindow != window) // return false; return IsKeyPressed(key, repeat); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GetWindowRect(ImGuiWindow* window, ImVec2* pos, ImVec2* size) { *pos = window->Pos; *size = window->Size; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void SetWindowRect(ImGuiWindow* window, const ImVec2 pos, const ImVec2 size) { window->PosFloat = pos; window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); window->Size = size; window->SizeFull = size; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool IsActiveWindow(ImGuiWindow* window) { const ImGuiState* g = GImGui; return g->FocusedWindow == window; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ImScEditor* ScInputText(const char* label, float xSize, float ySize, void (*callback)(void*), void* userData) { ImGuiWindow* window = GetCurrentWindow(); const ImGuiID id = window->GetID(label); (void)callback; (void)userData; //ImGui::BeginChild("Log"); ImGuiStorage* storage = GetStateStorage(); ScEditor* editor = (ScEditor*)storage->GetVoidPtr(id); if (!editor) { (void)xSize; (void)ySize; editor = ScEditor_create((int)xSize, (int)ySize); storage->SetVoidPtr(id, (void*)editor); } ImScEditor* editorInterface = ScEditor_getInterface(editor); //float textSize = ImGui::GetTextLineHeightWithSpacing() - 1; // TODO: Remove hardcoded value, ask scintilla float textSize = 26; ScEditor_resize(editor, 0, 0, (int)window->Size.x - 20, (int)window->Size.y); int lineCount = (int)editorInterface->SendCommand(SCI_GETLINECOUNT, 0, 0); editorInterface->HandleInput(); ImGuiListClipper clipper(lineCount, textSize); //ImVec2 pos = window->DC.CursorPos; ScEditor_setDrawList(GetWindowDrawList()); ScEditor_setFont(GetWindowFont()); ScEditor_setPos(0.0f, 14.0f); //int currentPos = (int)editorInterface->SendCommand(SCN_GETTOPLINE, 0, 0); //float scrollPos = ImGui::GetScrollPosY(); //int iPos = (int)(((int)ImGui::GetScrollPosY()) / (int)(textSize)); //if (currentPos != iPos) //{ editorInterface->ScrollTo(clipper.DisplayStart); //} //printf("current pos in scintilla %d - pos sent %d\n", newPos, iPos); clipper.End(); //ImGui::EndChild(); return editorInterface; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } <|endoftext|>
<commit_before>/** * projectM -- Milkdrop-esque visualisation SDK * Copyright (C)2003-2007 projectM Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ /** * $Id$ * * Beat detection class. Takes decompressed sound buffers and returns * various characteristics * * $Log$ * */ #ifndef _BEAT_DETECT_H #define _BEAT_DETECT_H #include "PCM.hpp" class BeatDetect { public: /** Vars */ float beat_buffer[32][80], beat_instant[32], beat_history[32]; float beat_val[32], beat_att[32], beat_variance[32]; int beat_buffer_pos; float vol_buffer[80], vol_instant, vol_history; float treb ; float mid ; float bass ; float vol_old ; float beat_sensitivity; float treb_att ; float mid_att ; float bass_att ; float vol; PCM *pcm; /** Methods */ DLLEXPORT BeatDetect(PCM *pcm); DLLEXPORT ~BeatDetect(); void initBeatDetect(); void reset(); void detectFromSamples(); void getBeatVals ( float *vdataL, float *vdataR ); }; #endif /** !_BEAT_DETECT_H */ <commit_msg>removed DLLEXPORT from beatdetect (was it necessary?)<commit_after>/** * projectM -- Milkdrop-esque visualisation SDK * Copyright (C)2003-2007 projectM Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ /** * $Id$ * * Beat detection class. Takes decompressed sound buffers and returns * various characteristics * * $Log$ * */ #ifndef _BEAT_DETECT_H #define _BEAT_DETECT_H #include "PCM.hpp" class BeatDetect { public: /** Vars */ float beat_buffer[32][80], beat_instant[32], beat_history[32]; float beat_val[32], beat_att[32], beat_variance[32]; int beat_buffer_pos; float vol_buffer[80], vol_instant, vol_history; float treb ; float mid ; float bass ; float vol_old ; float beat_sensitivity; float treb_att ; float mid_att ; float bass_att ; float vol; PCM *pcm; /** Methods */ BeatDetect(PCM *pcm); ~BeatDetect(); void initBeatDetect(); void reset(); void detectFromSamples(); void getBeatVals ( float *vdataL, float *vdataR ); }; #endif /** !_BEAT_DETECT_H */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: exprnode.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: hr $ $Date: 2006-06-19 17:41:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #define _NTSDK // wg. HUGE_VAL MH #define HUGE_VAL HUGE #include <math.h> #include <rtl/math.hxx> #include "sbcomp.hxx" #include "expr.hxx" ////////////////////////////////////////////////////////////////////////// SbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, SbiToken t, SbiExprNode* r ) { BaseInit( p ); pLeft = l; pRight = r; eTok = t; nVal = 0; eType = SbxVARIANT; // Nodes sind immer Variant eNodeType = SbxNODE; bComposite= TRUE; } SbiExprNode::SbiExprNode( SbiParser* p, double n, SbxDataType t ) { BaseInit( p ); eType = t; eNodeType = SbxNUMVAL; nVal = n; } SbiExprNode::SbiExprNode( SbiParser* p, const String& rVal ) { BaseInit( p ); eType = SbxSTRING; eNodeType = SbxSTRVAL; aStrVal = rVal; } SbiExprNode::SbiExprNode( SbiParser* p, const SbiSymDef& r, SbxDataType t, SbiExprList* l ) { BaseInit( p ); eType = ( t == SbxVARIANT ) ? r.GetType() : t; eNodeType = SbxVARVAL; aVar.pDef = (SbiSymDef*) &r; aVar.pPar = l; aVar.pNext= NULL; // Funktionsergebnisse sind nie starr bComposite= BOOL( aVar.pDef->GetProcDef() != NULL ); } // #120061 TypeOf SbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, USHORT nId ) { BaseInit( p ); pLeft = l; eType = SbxBOOL; eNodeType = SbxTYPEOF; nTypeStrId = nId; } // AB: 17.12.95, Hilfsfunktion fuer Ctor fuer einheitliche Initialisierung void SbiExprNode::BaseInit( SbiParser* p ) { pGen = &p->aGen; eTok = NIL; pLeft = NULL; pRight = NULL; pWithParent = NULL; bComposite = FALSE; bError = FALSE; } SbiExprNode::~SbiExprNode() { delete pLeft; delete pRight; if( IsVariable() ) { delete aVar.pPar; delete aVar.pNext; } } SbiSymDef* SbiExprNode::GetVar() { if( eNodeType == SbxVARVAL ) return aVar.pDef; else return NULL; } SbiSymDef* SbiExprNode::GetRealVar() { SbiExprNode* p = GetRealNode(); if( p ) return p->GetVar(); else return NULL; } // AB: 18.12.95 SbiExprNode* SbiExprNode::GetRealNode() { if( eNodeType == SbxVARVAL ) { SbiExprNode* p = this; while( p->aVar.pNext ) p = p->aVar.pNext; return p; } else return NULL; } // Diese Methode setzt den Typ um, falls er in den Integer-Bereich hineinpasst BOOL SbiExprNode::IsIntConst() { if( eNodeType == SbxNUMVAL ) { if( eType >= SbxINTEGER && eType <= SbxDOUBLE ) { double n; if( nVal >= SbxMININT && nVal <= SbxMAXINT && modf( nVal, &n ) == 0 ) { nVal = (double) (short) nVal; eType = SbxINTEGER; return TRUE; } } } return FALSE; } BOOL SbiExprNode::IsNumber() { return BOOL( eNodeType == SbxNUMVAL ); } BOOL SbiExprNode::IsString() { return BOOL( eNodeType == SbxSTRVAL ); } BOOL SbiExprNode::IsVariable() { return BOOL( eNodeType == SbxVARVAL ); } BOOL SbiExprNode::IsLvalue() { return IsVariable(); } // Ermitteln der Tiefe eines Baumes short SbiExprNode::GetDepth() { if( IsOperand() ) return 0; else { short d1 = pLeft->GetDepth(); short d2 = pRight->GetDepth(); return( (d1 < d2 ) ? d2 : d1 ) + 1; } } // Abgleich eines Baumes: // 1. Constant Folding // 2. Typabgleich // 3. Umwandlung der Operanden in Strings // 4. Hochziehen der Composite- und Error-Bits void SbiExprNode::Optimize() { FoldConstants(); CollectBits(); } // Hochziehen der Composite- und Fehlerbits void SbiExprNode::CollectBits() { if( pLeft ) { pLeft->CollectBits(); bError |= pLeft->bError; bComposite |= pLeft->bComposite; } if( pRight ) { pRight->CollectBits(); bError |= pRight->bError; bComposite |= pRight->bComposite; } } // Kann ein Zweig umgeformt werden, wird TRUE zurueckgeliefert. In diesem // Fall ist das Ergebnis im linken Zweig. void SbiExprNode::FoldConstants() { if( IsOperand() ) return; pLeft->FoldConstants(); if( pRight ) { pRight->FoldConstants(); if( pLeft->IsConstant() && pRight->IsConstant() && pLeft->eNodeType == pRight->eNodeType ) { CollectBits(); if( eTok == CAT ) // CAT verbindet auch zwei Zahlen miteinander! eType = SbxSTRING; if( pLeft->eType == SbxSTRING ) // Kein Type Mismatch! eType = SbxSTRING; if( eType == SbxSTRING ) { String rl( pLeft->GetString() ); String rr( pRight->GetString() ); delete pLeft; pLeft = NULL; delete pRight; pRight = NULL; bComposite = FALSE; if( eTok == PLUS || eTok == CAT ) { eTok = CAT; // Verkettung: aStrVal = rl; aStrVal += rr; eType = SbxSTRING; eNodeType = SbxSTRVAL; } else { eType = SbxDOUBLE; eNodeType = SbxNUMVAL; StringCompare eRes = rr.CompareTo( rl ); switch( eTok ) { case EQ: nVal = ( eRes == COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE; break; case NE: nVal = ( eRes != COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE; break; case LT: nVal = ( eRes == COMPARE_LESS ) ? SbxTRUE : SbxFALSE; break; case GT: nVal = ( eRes == COMPARE_GREATER ) ? SbxTRUE : SbxFALSE; break; case LE: nVal = ( eRes != COMPARE_GREATER ) ? SbxTRUE : SbxFALSE; break; case GE: nVal = ( eRes != COMPARE_LESS ) ? SbxTRUE : SbxFALSE; break; default: pGen->GetParser()->Error( SbERR_CONVERSION ); bError = TRUE; } } } else { double nl = pLeft->nVal; double nr = pRight->nVal; long ll = 0, lr = 0; long llMod = 0, lrMod = 0; if( ( eTok >= AND && eTok <= IMP ) || eTok == IDIV || eTok == MOD ) { // Integer-Operationen BOOL err = FALSE; if( nl > SbxMAXLNG ) err = TRUE, nl = SbxMAXLNG; else if( nl < SbxMINLNG ) err = TRUE, nl = SbxMINLNG; if( nr > SbxMAXLNG ) err = TRUE, nr = SbxMAXLNG; else if( nr < SbxMINLNG ) err = TRUE, nr = SbxMINLNG; ll = (long) nl; lr = (long) nr; llMod = (long) (nl < 0 ? nl - 0.5 : nl + 0.5); lrMod = (long) (nr < 0 ? nr - 0.5 : nr + 0.5); if( err ) { pGen->GetParser()->Error( SbERR_MATH_OVERFLOW ); bError = TRUE; } } BOOL bBothInt = BOOL( pLeft->eType < SbxSINGLE && pRight->eType < SbxSINGLE ); delete pLeft; pLeft = NULL; delete pRight; pRight = NULL; nVal = 0; eType = SbxDOUBLE; eNodeType = SbxNUMVAL; bComposite = FALSE; BOOL bCheckType = FALSE; switch( eTok ) { case EXPON: nVal = pow( nl, nr ); break; case MUL: bCheckType = TRUE; nVal = nl * nr; break; case DIV: if( !nr ) { pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL; bError = TRUE; } else nVal = nl / nr; break; case PLUS: bCheckType = TRUE; nVal = nl + nr; break; case MINUS: bCheckType = TRUE; nVal = nl - nr; break; case EQ: nVal = ( nl == nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case NE: nVal = ( nl != nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case LT: nVal = ( nl < nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case GT: nVal = ( nl > nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case LE: nVal = ( nl <= nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case GE: nVal = ( nl >= nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case IDIV: if( !lr ) { pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL; bError = TRUE; } else nVal = ll / lr; eType = SbxLONG; break; case MOD: if( !lr ) { pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL; bError = TRUE; } else nVal = llMod % lrMod; eType = SbxLONG; break; case AND: nVal = (double) ( ll & lr ); eType = SbxLONG; break; case OR: nVal = (double) ( ll | lr ); eType = SbxLONG; break; case XOR: nVal = (double) ( ll ^ lr ); eType = SbxLONG; break; case EQV: nVal = (double) ( ~ll ^ lr ); eType = SbxLONG; break; case IMP: nVal = (double) ( ~ll | lr ); eType = SbxLONG; break; default: break; } if( !::rtl::math::isFinite( nVal ) ) pGen->GetParser()->Error( SbERR_MATH_OVERFLOW ); // Den Datentyp wiederherstellen, um Rundungsfehler // zu killen if( bCheckType && bBothInt && nVal >= SbxMINLNG && nVal <= SbxMAXLNG ) { // NK-Stellen weg long n = (long) nVal; nVal = n; eType = ( n >= SbxMININT && n <= SbxMAXINT ) ? SbxINTEGER : SbxLONG; } } } } else if( pLeft->IsNumber() ) { nVal = pLeft->nVal; delete pLeft; pLeft = NULL; eType = SbxDOUBLE; eNodeType = SbxNUMVAL; bComposite = FALSE; switch( eTok ) { case NEG: nVal = -nVal; break; case NOT: { // Integer-Operation! BOOL err = FALSE; if( nVal > SbxMAXLNG ) err = TRUE, nVal = SbxMAXLNG; else if( nVal < SbxMINLNG ) err = TRUE, nVal = SbxMINLNG; if( err ) { pGen->GetParser()->Error( SbERR_MATH_OVERFLOW ); bError = TRUE; } nVal = (double) ~((long) nVal); eType = SbxLONG; } break; default: break; } } if( eNodeType == SbxNUMVAL ) { // Evtl auf INTEGER falten (wg. besserem Opcode)? if( eType == SbxSINGLE || eType == SbxDOUBLE ) { double x; if( nVal >= SbxMINLNG && nVal <= SbxMAXLNG && !modf( nVal, &x ) ) eType = SbxLONG; } if( eType == SbxLONG && nVal >= SbxMININT && nVal <= SbxMAXINT ) eType = SbxINTEGER; } } <commit_msg>INTEGRATION: CWS pchfix02 (1.14.24); FILE MERGED 2006/09/01 17:17:02 kaib 1.14.24.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: exprnode.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: obo $ $Date: 2006-09-17 10:02:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basic.hxx" #define _NTSDK // wg. HUGE_VAL MH #define HUGE_VAL HUGE #include <math.h> #include <rtl/math.hxx> #include "sbcomp.hxx" #include "expr.hxx" ////////////////////////////////////////////////////////////////////////// SbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, SbiToken t, SbiExprNode* r ) { BaseInit( p ); pLeft = l; pRight = r; eTok = t; nVal = 0; eType = SbxVARIANT; // Nodes sind immer Variant eNodeType = SbxNODE; bComposite= TRUE; } SbiExprNode::SbiExprNode( SbiParser* p, double n, SbxDataType t ) { BaseInit( p ); eType = t; eNodeType = SbxNUMVAL; nVal = n; } SbiExprNode::SbiExprNode( SbiParser* p, const String& rVal ) { BaseInit( p ); eType = SbxSTRING; eNodeType = SbxSTRVAL; aStrVal = rVal; } SbiExprNode::SbiExprNode( SbiParser* p, const SbiSymDef& r, SbxDataType t, SbiExprList* l ) { BaseInit( p ); eType = ( t == SbxVARIANT ) ? r.GetType() : t; eNodeType = SbxVARVAL; aVar.pDef = (SbiSymDef*) &r; aVar.pPar = l; aVar.pNext= NULL; // Funktionsergebnisse sind nie starr bComposite= BOOL( aVar.pDef->GetProcDef() != NULL ); } // #120061 TypeOf SbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, USHORT nId ) { BaseInit( p ); pLeft = l; eType = SbxBOOL; eNodeType = SbxTYPEOF; nTypeStrId = nId; } // AB: 17.12.95, Hilfsfunktion fuer Ctor fuer einheitliche Initialisierung void SbiExprNode::BaseInit( SbiParser* p ) { pGen = &p->aGen; eTok = NIL; pLeft = NULL; pRight = NULL; pWithParent = NULL; bComposite = FALSE; bError = FALSE; } SbiExprNode::~SbiExprNode() { delete pLeft; delete pRight; if( IsVariable() ) { delete aVar.pPar; delete aVar.pNext; } } SbiSymDef* SbiExprNode::GetVar() { if( eNodeType == SbxVARVAL ) return aVar.pDef; else return NULL; } SbiSymDef* SbiExprNode::GetRealVar() { SbiExprNode* p = GetRealNode(); if( p ) return p->GetVar(); else return NULL; } // AB: 18.12.95 SbiExprNode* SbiExprNode::GetRealNode() { if( eNodeType == SbxVARVAL ) { SbiExprNode* p = this; while( p->aVar.pNext ) p = p->aVar.pNext; return p; } else return NULL; } // Diese Methode setzt den Typ um, falls er in den Integer-Bereich hineinpasst BOOL SbiExprNode::IsIntConst() { if( eNodeType == SbxNUMVAL ) { if( eType >= SbxINTEGER && eType <= SbxDOUBLE ) { double n; if( nVal >= SbxMININT && nVal <= SbxMAXINT && modf( nVal, &n ) == 0 ) { nVal = (double) (short) nVal; eType = SbxINTEGER; return TRUE; } } } return FALSE; } BOOL SbiExprNode::IsNumber() { return BOOL( eNodeType == SbxNUMVAL ); } BOOL SbiExprNode::IsString() { return BOOL( eNodeType == SbxSTRVAL ); } BOOL SbiExprNode::IsVariable() { return BOOL( eNodeType == SbxVARVAL ); } BOOL SbiExprNode::IsLvalue() { return IsVariable(); } // Ermitteln der Tiefe eines Baumes short SbiExprNode::GetDepth() { if( IsOperand() ) return 0; else { short d1 = pLeft->GetDepth(); short d2 = pRight->GetDepth(); return( (d1 < d2 ) ? d2 : d1 ) + 1; } } // Abgleich eines Baumes: // 1. Constant Folding // 2. Typabgleich // 3. Umwandlung der Operanden in Strings // 4. Hochziehen der Composite- und Error-Bits void SbiExprNode::Optimize() { FoldConstants(); CollectBits(); } // Hochziehen der Composite- und Fehlerbits void SbiExprNode::CollectBits() { if( pLeft ) { pLeft->CollectBits(); bError |= pLeft->bError; bComposite |= pLeft->bComposite; } if( pRight ) { pRight->CollectBits(); bError |= pRight->bError; bComposite |= pRight->bComposite; } } // Kann ein Zweig umgeformt werden, wird TRUE zurueckgeliefert. In diesem // Fall ist das Ergebnis im linken Zweig. void SbiExprNode::FoldConstants() { if( IsOperand() ) return; pLeft->FoldConstants(); if( pRight ) { pRight->FoldConstants(); if( pLeft->IsConstant() && pRight->IsConstant() && pLeft->eNodeType == pRight->eNodeType ) { CollectBits(); if( eTok == CAT ) // CAT verbindet auch zwei Zahlen miteinander! eType = SbxSTRING; if( pLeft->eType == SbxSTRING ) // Kein Type Mismatch! eType = SbxSTRING; if( eType == SbxSTRING ) { String rl( pLeft->GetString() ); String rr( pRight->GetString() ); delete pLeft; pLeft = NULL; delete pRight; pRight = NULL; bComposite = FALSE; if( eTok == PLUS || eTok == CAT ) { eTok = CAT; // Verkettung: aStrVal = rl; aStrVal += rr; eType = SbxSTRING; eNodeType = SbxSTRVAL; } else { eType = SbxDOUBLE; eNodeType = SbxNUMVAL; StringCompare eRes = rr.CompareTo( rl ); switch( eTok ) { case EQ: nVal = ( eRes == COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE; break; case NE: nVal = ( eRes != COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE; break; case LT: nVal = ( eRes == COMPARE_LESS ) ? SbxTRUE : SbxFALSE; break; case GT: nVal = ( eRes == COMPARE_GREATER ) ? SbxTRUE : SbxFALSE; break; case LE: nVal = ( eRes != COMPARE_GREATER ) ? SbxTRUE : SbxFALSE; break; case GE: nVal = ( eRes != COMPARE_LESS ) ? SbxTRUE : SbxFALSE; break; default: pGen->GetParser()->Error( SbERR_CONVERSION ); bError = TRUE; } } } else { double nl = pLeft->nVal; double nr = pRight->nVal; long ll = 0, lr = 0; long llMod = 0, lrMod = 0; if( ( eTok >= AND && eTok <= IMP ) || eTok == IDIV || eTok == MOD ) { // Integer-Operationen BOOL err = FALSE; if( nl > SbxMAXLNG ) err = TRUE, nl = SbxMAXLNG; else if( nl < SbxMINLNG ) err = TRUE, nl = SbxMINLNG; if( nr > SbxMAXLNG ) err = TRUE, nr = SbxMAXLNG; else if( nr < SbxMINLNG ) err = TRUE, nr = SbxMINLNG; ll = (long) nl; lr = (long) nr; llMod = (long) (nl < 0 ? nl - 0.5 : nl + 0.5); lrMod = (long) (nr < 0 ? nr - 0.5 : nr + 0.5); if( err ) { pGen->GetParser()->Error( SbERR_MATH_OVERFLOW ); bError = TRUE; } } BOOL bBothInt = BOOL( pLeft->eType < SbxSINGLE && pRight->eType < SbxSINGLE ); delete pLeft; pLeft = NULL; delete pRight; pRight = NULL; nVal = 0; eType = SbxDOUBLE; eNodeType = SbxNUMVAL; bComposite = FALSE; BOOL bCheckType = FALSE; switch( eTok ) { case EXPON: nVal = pow( nl, nr ); break; case MUL: bCheckType = TRUE; nVal = nl * nr; break; case DIV: if( !nr ) { pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL; bError = TRUE; } else nVal = nl / nr; break; case PLUS: bCheckType = TRUE; nVal = nl + nr; break; case MINUS: bCheckType = TRUE; nVal = nl - nr; break; case EQ: nVal = ( nl == nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case NE: nVal = ( nl != nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case LT: nVal = ( nl < nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case GT: nVal = ( nl > nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case LE: nVal = ( nl <= nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case GE: nVal = ( nl >= nr ) ? SbxTRUE : SbxFALSE; eType = SbxINTEGER; break; case IDIV: if( !lr ) { pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL; bError = TRUE; } else nVal = ll / lr; eType = SbxLONG; break; case MOD: if( !lr ) { pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL; bError = TRUE; } else nVal = llMod % lrMod; eType = SbxLONG; break; case AND: nVal = (double) ( ll & lr ); eType = SbxLONG; break; case OR: nVal = (double) ( ll | lr ); eType = SbxLONG; break; case XOR: nVal = (double) ( ll ^ lr ); eType = SbxLONG; break; case EQV: nVal = (double) ( ~ll ^ lr ); eType = SbxLONG; break; case IMP: nVal = (double) ( ~ll | lr ); eType = SbxLONG; break; default: break; } if( !::rtl::math::isFinite( nVal ) ) pGen->GetParser()->Error( SbERR_MATH_OVERFLOW ); // Den Datentyp wiederherstellen, um Rundungsfehler // zu killen if( bCheckType && bBothInt && nVal >= SbxMINLNG && nVal <= SbxMAXLNG ) { // NK-Stellen weg long n = (long) nVal; nVal = n; eType = ( n >= SbxMININT && n <= SbxMAXINT ) ? SbxINTEGER : SbxLONG; } } } } else if( pLeft->IsNumber() ) { nVal = pLeft->nVal; delete pLeft; pLeft = NULL; eType = SbxDOUBLE; eNodeType = SbxNUMVAL; bComposite = FALSE; switch( eTok ) { case NEG: nVal = -nVal; break; case NOT: { // Integer-Operation! BOOL err = FALSE; if( nVal > SbxMAXLNG ) err = TRUE, nVal = SbxMAXLNG; else if( nVal < SbxMINLNG ) err = TRUE, nVal = SbxMINLNG; if( err ) { pGen->GetParser()->Error( SbERR_MATH_OVERFLOW ); bError = TRUE; } nVal = (double) ~((long) nVal); eType = SbxLONG; } break; default: break; } } if( eNodeType == SbxNUMVAL ) { // Evtl auf INTEGER falten (wg. besserem Opcode)? if( eType == SbxSINGLE || eType == SbxDOUBLE ) { double x; if( nVal >= SbxMINLNG && nVal <= SbxMAXLNG && !modf( nVal, &x ) ) eType = SbxLONG; } if( eType == SbxLONG && nVal >= SbxMININT && nVal <= SbxMAXINT ) eType = SbxINTEGER; } } <|endoftext|>
<commit_before>/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * Copyright Projet JRL-Japan, 2009 *+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * File: CoMFreezer.cpp * Project: SOT * Author: Pierre Gergondet * * Version control * =============== * * $Id$ * * Description * ============ * * * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ #include <sot-core/com-freezer.h> #include <sot-core/debug.h> #include <dynamic-graph/factory.h> using namespace dynamicgraph; using namespace sot; DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CoMFreezer, "CoMFreezer"); CoMFreezer::CoMFreezer(const std::string & name) : Entity(name) , m_lastCoM(3) , m_previousPGInProcess(false) , m_lastStopTime(-1) , CoMRefSIN(NULL, "CoMFreezer("+name+")::input(vector)::CoMRef") , PGInProcessSIN(NULL, "CoMFreezer("+name+")::input(bool)::PGInProcess") , freezedCoMSOUT(boost::bind(&CoMFreezer::computeFreezedCoM, this, _1, _2), CoMRefSIN << PGInProcessSIN, "CoMFreezer("+name+")::output(vector)::freezedCoM") { sotDEBUGIN(5); signalRegistration( CoMRefSIN << PGInProcessSIN << freezedCoMSOUT ); sotDEBUGOUT(5); } CoMFreezer::~CoMFreezer(void) { sotDEBUGIN(5); sotDEBUGOUT(5); return; } ml::Vector & CoMFreezer::computeFreezedCoM(ml::Vector & freezedCoM, const int & time) { sotDEBUGIN(15); unsigned PGInProcess = PGInProcessSIN(time); if(PGInProcess) /* CoM unfreezed */ { m_lastCoM = CoMRefSIN(time); m_previousPGInProcess = PGInProcess; } else { if(m_previousPGInProcess) /* pg.inprocess switch from 1 to 0 */ { m_lastStopTime = time; m_lastCoM = CoMRefSIN(time); m_previousPGInProcess = PGInProcess; } else if(time < m_lastStopTime + 200) /* keep updating for 1s */ { m_lastCoM = CoMRefSIN(time); } } freezedCoM = m_lastCoM; sotDEBUGOUT(15); if(m_lastStopTime < 0) { m_lastCoM = CoMRefSIN(time); m_lastStopTime = time; freezedCoM = m_lastCoM; return freezedCoM; } return m_lastCoM; } void CoMFreezer::display(std::ostream & os) const { os << "CoMFreezer " << getName() << "." << std::endl; } <commit_msg>Remove warnings (during conversion unsigned -> bool)<commit_after>/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * Copyright Projet JRL-Japan, 2009 *+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * File: CoMFreezer.cpp * Project: SOT * Author: Pierre Gergondet * * Version control * =============== * * $Id$ * * Description * ============ * * * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ #include <sot-core/com-freezer.h> #include <sot-core/debug.h> #include <dynamic-graph/factory.h> using namespace dynamicgraph; using namespace sot; DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CoMFreezer, "CoMFreezer"); CoMFreezer::CoMFreezer(const std::string & name) : Entity(name) , m_lastCoM(3) , m_previousPGInProcess(false) , m_lastStopTime(-1) , CoMRefSIN(NULL, "CoMFreezer("+name+")::input(vector)::CoMRef") , PGInProcessSIN(NULL, "CoMFreezer("+name+")::input(bool)::PGInProcess") , freezedCoMSOUT(boost::bind(&CoMFreezer::computeFreezedCoM, this, _1, _2), CoMRefSIN << PGInProcessSIN, "CoMFreezer("+name+")::output(vector)::freezedCoM") { sotDEBUGIN(5); signalRegistration( CoMRefSIN << PGInProcessSIN << freezedCoMSOUT ); sotDEBUGOUT(5); } CoMFreezer::~CoMFreezer(void) { sotDEBUGIN(5); sotDEBUGOUT(5); return; } ml::Vector & CoMFreezer::computeFreezedCoM(ml::Vector & freezedCoM, const int & time) { sotDEBUGIN(15); unsigned PGInProcess = PGInProcessSIN(time); if(PGInProcess) /* CoM unfreezed */ { m_lastCoM = CoMRefSIN(time); m_previousPGInProcess = (PGInProcess == 0); } else { if(m_previousPGInProcess) /* pg.inprocess switch from 1 to 0 */ { m_lastStopTime = time; m_lastCoM = CoMRefSIN(time); m_previousPGInProcess = (PGInProcess == 0); } else if(time < m_lastStopTime + 200) /* keep updating for 1s */ { m_lastCoM = CoMRefSIN(time); } } freezedCoM = m_lastCoM; sotDEBUGOUT(15); if(m_lastStopTime < 0) { m_lastCoM = CoMRefSIN(time); m_lastStopTime = time; freezedCoM = m_lastCoM; return freezedCoM; } return m_lastCoM; } void CoMFreezer::display(std::ostream & os) const { os << "CoMFreezer " << getName() << "." << std::endl; } <|endoftext|>
<commit_before>/* * Copyright 2009 The VOTCA Development Team (http://www.votca.org) * * 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 <votca/tools/spline.h> #include <votca/tools/cubicspline.h> #include <votca/tools/akimaspline.h> #include <votca/tools/linspline.h> #include <votca/tools/table.h> #include <votca/tools/tokenizer.h> #include <boost/program_options.hpp> #include <iostream> #include "version.h" using namespace std; namespace po = boost::program_options; using namespace votca::csg; using namespace votca::tools; void help_text() { votca::csg::HelpTextHeader("csg_resample"); cout << "Change grid + interval of any sort of table files.\n" "Mainly called internally by inverse script, can also be\n" "used to manually prepare input files for coarse-grained\n" "simulations.\n\n"; } void check_option(po::options_description &desc, po::variables_map &vm, const string &option) { if(!vm.count(option)) { cout << "csg_resample \n\n"; cout << desc << endl << "parameter " << option << " is not specified\n"; exit(1); } } int main(int argc, char** argv) { string in_file, out_file, grid, fitgrid, comment, type, boundaries; Spline *spline; Table in, out, der; // program options po::options_description desc("Allowed options"); desc.add_options() ("in", po::value<string>(&in_file), "table to read") ("out", po::value<string>(&out_file), "table to write") ("derivative", po::value<string>(), "table to write") ("grid", po::value<string>(&grid), "new grid spacing (min:step:max). If 'grid' is specified only, interpolation is performed.") ("type", po::value<string>(&type)->default_value("akima"), "[cubic|akima|linear]. If option is not specified, the default type 'akima' is assumed.") ("fitgrid", po::value<string>(&fitgrid), "specify fit grid (min:step:max). If 'grid' and 'fitgrid' are specified, a fit is performed.") ("nocut", "Option for fitgrid: Normally, values out of fitgrid boundaries are cut off. If they shouldn't, choose --nocut.") ("comment", po::value<string>(&comment), "store a comment in the output table") ("boundaries", po::value<string>(&boundaries), "(natural|periodic|derivativezero) sets boundary conditions") ("help", "options file for coarse graining"); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch(po::error err) { cout << "error parsing command line: " << err.what() << endl; return -1; } // does the user want help? if (vm.count("help")) { help_text(); cout << desc << endl; return 0; } check_option(desc, vm, "in"); check_option(desc, vm, "out"); if(!(vm.count("grid") || vm.count("fitgrid"))) { cout << "Need grid for interpolation or fitgrid for fit.\n"; return 1; } if((!vm.count("grid")) && vm.count("fitgrid")) { cout << "Need a grid for fitting as well.\n"; return 1; } double min, max, step; { Tokenizer tok(grid, ":"); vector<string> toks; tok.ToVector(toks); if(toks.size()!=3) { cout << "wrong range format, use min:step:max\n"; return 1; } min = boost::lexical_cast<double>(toks[0]); step = boost::lexical_cast<double>(toks[1]); max = boost::lexical_cast<double>(toks[2]); } in.Load(in_file); if (vm.count("type")) { if(type=="cubic") { spline = new CubicSpline(); } else if(type=="akima") { spline = new AkimaSpline(); } else if(type=="linear") { spline = new LinSpline(); } else { throw std::runtime_error("unknown type"); } } spline->setBC(Spline::splineNormal); if (vm.count("boundaries")) { if(boundaries=="periodic") { spline->setBC(Spline::splinePeriodic); } if(boundaries=="derivativezero") { spline->setBC(Spline::splineDerivativeZero); } //default: normal } // in case fit is specified if (vm.count("fitgrid")) { Tokenizer tok(fitgrid, ":"); vector<string> toks; tok.ToVector(toks); if(toks.size()!=3) { cout << "wrong range format in fitgrid, use min:step:max\n"; return 1; } double sp_min, sp_max, sp_step; sp_min = boost::lexical_cast<double>(toks[0]); sp_step = boost::lexical_cast<double>(toks[1]); sp_max = boost::lexical_cast<double>(toks[2]); cout << "doing " << type << " fit " << sp_min << ":" << sp_step << ":" << sp_max << endl; // cut off any values out of fitgrid boundaries (exception: do nothing in case of --nocut) ub::vector<double> x_copy; ub::vector<double> y_copy; if (!vm.count("nocut")) { // determine vector size int minindex=-1, maxindex; for (int i=0; i<in.x().size(); i++) { if(in.x(i)<sp_min) { minindex = i; } if(in.x(i)<sp_max) { maxindex = i; } } // copy data values in [sp_min,sp_max] into new vectors minindex++; x_copy = ub::zero_vector<double>(maxindex-minindex+1); y_copy = ub::zero_vector<double>(maxindex-minindex+1); for (int i=minindex; i<=maxindex; i++) { x_copy(i-minindex) = in.x(i); y_copy(i-minindex) = in.y(i); } } // fitting spline->GenerateGrid(sp_min, sp_max, sp_step); if (vm.count("nocut")) { spline->Fit(in.x(), in.y()); } else { spline->Fit(x_copy, y_copy); } } else { // otherwise do interpolation (default = cubic) spline->Interpolate(in.x(), in.y()); } out.GenerateGridSpacing(min, max, step); spline->Calculate(out.x(), out.y()); //store a comment line if (vm.count("comment")){ out.set_comment(comment); } out.y() = out.y(); out.flags() = ub::scalar_vector<double>(out.flags().size(), 'o'); int i=0; for(i=0; out.x(i) < in.x(0) && i<out.size(); ++i); int j=0; for(;i < out.size(); ++i) { for(; j < in.size(); ++j) if(in.x(j) >= out.x(i) || fabs(in.x(j)-out.x(i) ) < 1e-12) // fix for precison errors break; if(in.size() == j) break; out.flags(i) = in.flags(j); } out.Save(out_file); if (vm.count("derivative")) { der.GenerateGridSpacing(min, max, step); der.flags() = ub::scalar_vector<double>(der.flags().size(), 'o'); spline->CalculateDerivative(der.x(), der.y()); der.Save(vm["derivative"].as<string>()); } delete spline; return 0; } <commit_msg>error handling in csg_resample<commit_after>/* * Copyright 2009 The VOTCA Development Team (http://www.votca.org) * * 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 <votca/tools/spline.h> #include <votca/tools/cubicspline.h> #include <votca/tools/akimaspline.h> #include <votca/tools/linspline.h> #include <votca/tools/table.h> #include <votca/tools/tokenizer.h> #include <boost/program_options.hpp> #include <iostream> #include "version.h" using namespace std; namespace po = boost::program_options; using namespace votca::csg; using namespace votca::tools; void help_text() { votca::csg::HelpTextHeader("csg_resample"); cout << "Change grid + interval of any sort of table files.\n" "Mainly called internally by inverse script, can also be\n" "used to manually prepare input files for coarse-grained\n" "simulations.\n\n"; } void check_option(po::options_description &desc, po::variables_map &vm, const string &option) { if(!vm.count(option)) { cout << "csg_resample \n\n"; cout << desc << endl << "parameter " << option << " is not specified\n"; exit(1); } } int main(int argc, char** argv) { string in_file, out_file, grid, fitgrid, comment, type, boundaries; Spline *spline; Table in, out, der; // program options po::options_description desc("Allowed options"); desc.add_options() ("in", po::value<string>(&in_file), "table to read") ("out", po::value<string>(&out_file), "table to write") ("derivative", po::value<string>(), "table to write") ("grid", po::value<string>(&grid), "new grid spacing (min:step:max). If 'grid' is specified only, interpolation is performed.") ("type", po::value<string>(&type)->default_value("akima"), "[cubic|akima|linear]. If option is not specified, the default type 'akima' is assumed.") ("fitgrid", po::value<string>(&fitgrid), "specify fit grid (min:step:max). If 'grid' and 'fitgrid' are specified, a fit is performed.") ("nocut", "Option for fitgrid: Normally, values out of fitgrid boundaries are cut off. If they shouldn't, choose --nocut.") ("comment", po::value<string>(&comment), "store a comment in the output table") ("boundaries", po::value<string>(&boundaries), "(natural|periodic|derivativezero) sets boundary conditions") ("help", "options file for coarse graining"); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch(po::error err) { cout << "error parsing command line: " << err.what() << endl; return -1; } // does the user want help? if (vm.count("help")) { help_text(); cout << desc << endl; return 0; } check_option(desc, vm, "in"); check_option(desc, vm, "out"); if(!(vm.count("grid") || vm.count("fitgrid"))) { cout << "Need grid for interpolation or fitgrid for fit.\n"; return 1; } if((!vm.count("grid")) && vm.count("fitgrid")) { cout << "Need a grid for fitting as well.\n"; return 1; } double min, max, step; { Tokenizer tok(grid, ":"); vector<string> toks; tok.ToVector(toks); if(toks.size()!=3) { cout << "wrong range format, use min:step:max\n"; return 1; } min = boost::lexical_cast<double>(toks[0]); step = boost::lexical_cast<double>(toks[1]); max = boost::lexical_cast<double>(toks[2]); } in.Load(in_file); if (vm.count("type")) { if(type=="cubic") { spline = new CubicSpline(); } else if(type=="akima") { spline = new AkimaSpline(); } else if(type=="linear") { spline = new LinSpline(); } else { throw std::runtime_error("unknown type"); } } spline->setBC(Spline::splineNormal); if (vm.count("boundaries")) { if(boundaries=="periodic") { spline->setBC(Spline::splinePeriodic); } if(boundaries=="derivativezero") { spline->setBC(Spline::splineDerivativeZero); } //default: normal } // in case fit is specified if (vm.count("fitgrid")) { Tokenizer tok(fitgrid, ":"); vector<string> toks; tok.ToVector(toks); if(toks.size()!=3) { cout << "wrong range format in fitgrid, use min:step:max\n"; return 1; } double sp_min, sp_max, sp_step; sp_min = boost::lexical_cast<double>(toks[0]); sp_step = boost::lexical_cast<double>(toks[1]); sp_max = boost::lexical_cast<double>(toks[2]); cout << "doing " << type << " fit " << sp_min << ":" << sp_step << ":" << sp_max << endl; // cut off any values out of fitgrid boundaries (exception: do nothing in case of --nocut) ub::vector<double> x_copy; ub::vector<double> y_copy; if (!vm.count("nocut")) { // determine vector size int minindex=-1, maxindex; for (int i=0; i<in.x().size(); i++) { if(in.x(i)<sp_min) { minindex = i; } if(in.x(i)<sp_max) { maxindex = i; } } // copy data values in [sp_min,sp_max] into new vectors minindex++; x_copy = ub::zero_vector<double>(maxindex-minindex+1); y_copy = ub::zero_vector<double>(maxindex-minindex+1); for (int i=minindex; i<=maxindex; i++) { x_copy(i-minindex) = in.x(i); y_copy(i-minindex) = in.y(i); } } // fitting spline->GenerateGrid(sp_min, sp_max, sp_step); try { if (vm.count("nocut")) { spline->Fit(in.x(), in.y()); } else { spline->Fit(x_copy, y_copy); } } catch (const char* message) { if(message="qrsolve_zero_column_in_matrix") { throw std::runtime_error("error in Linalg::linalg_qrsolve : Not enough data for fit, please adjust grid (zero row in fit matrix)"); } else if(message="constrained_qrsolve_zero_column_in_matrix") { throw std::runtime_error("error in Linalg::linalg_constrained_qrsolve : Not enough data for fit, please adjust grid (zero row in fit matrix)"); } else throw std::runtime_error("Unknown error in csg_resample while fitting."); } } else { // otherwise do interpolation (default = cubic) try { spline->Interpolate(in.x(), in.y()); } catch (const char* message) { if(message="qrsolve_zero_column_in_matrix") { throw std::runtime_error("error in Linalg::linalg_qrsolve : Not enough data, please adjust grid (zero row in fit matrix)"); } else if(message="constrained_qrsolve_zero_column_in_matrix") { throw std::runtime_error("error in Linalg::linalg_constrained_qrsolve : Not enough data, please adjust grid (zero row in fit matrix)"); } else throw std::runtime_error("Unknown error in csg_resample while interpolating."); } } out.GenerateGridSpacing(min, max, step); spline->Calculate(out.x(), out.y()); //store a comment line if (vm.count("comment")){ out.set_comment(comment); } out.y() = out.y(); out.flags() = ub::scalar_vector<double>(out.flags().size(), 'o'); int i=0; for(i=0; out.x(i) < in.x(0) && i<out.size(); ++i); int j=0; for(;i < out.size(); ++i) { for(; j < in.size(); ++j) if(in.x(j) >= out.x(i) || fabs(in.x(j)-out.x(i) ) < 1e-12) // fix for precison errors break; if(in.size() == j) break; out.flags(i) = in.flags(j); } out.Save(out_file); if (vm.count("derivative")) { der.GenerateGridSpacing(min, max, step); der.flags() = ub::scalar_vector<double>(der.flags().size(), 'o'); spline->CalculateDerivative(der.x(), der.y()); der.Save(vm["derivative"].as<string>()); } delete spline; return 0; } <|endoftext|>
<commit_before>#ifndef TURBO_TOOLSET_INTRINSIC_HPP #define TURBO_TOOLSET_INTRINSIC_HPP #include <cstdint> #include <limits> namespace turbo { namespace toolset { constexpr int uint32_digits() { return std::numeric_limits<std::uint32_t>::digits; } constexpr int uint64_digits() { return std::numeric_limits<std::uint64_t>::digits; } constexpr std::uint32_t pow_2_to_31() { return 1U << 31; } inline std::uint32_t count_leading_zero(std::uint32_t input) { #if defined( _WIN32) && defined(_MSC_VER) std::uint32_t result = 0U; return (_BitScanReverse(result&, input) == 0) ? uint32_digits() : uint32_digits() - result + 1U; #elif defined(__GNUC__) || defined(__clang__) return (input == 0U) ? uint32_digits() : __builtin_clz(input); #else std::uint32_t count = 0U; while (count < uint32_digits() && (input & pow_2_to_31()) != pow_2_to_31()) { input = input << 1; ++count; } return count; #endif } inline std::uint64_t count_leading_zero(std::uint64_t input) { #if defined( _WIN32) && defined(_MSC_VER) std::uint64_t result = 0U; return (_BitScanReverse64(result&, input) == 0) ? uint64_digits() : uint64_digits() - result + 1U; #else std::uint32_t high_result = count_leading_zero(static_cast<std::uint32_t>((input & 0xFFFFFFFF00000000) >> uint32_digits())); return (high_result != uint32_digits()) ? high_result : count_leading_zero(static_cast<std::uint32_t>(input & 0x00000000FFFFFFFF)) + uint32_digits(); #endif } } // namespace toolset } // namespace turbo #endif <commit_msg>overloading count_leading_zero for std::uint8_t and std::uint16_t<commit_after>#ifndef TURBO_TOOLSET_INTRINSIC_HPP #define TURBO_TOOLSET_INTRINSIC_HPP #include <cstdint> #include <limits> namespace turbo { namespace toolset { constexpr int uint32_digits() { return std::numeric_limits<std::uint32_t>::digits; } constexpr int uint64_digits() { return std::numeric_limits<std::uint64_t>::digits; } constexpr std::uint32_t pow_2_to_31() { return 1U << 31; } inline std::uint32_t count_leading_zero(std::uint32_t input) { #if defined( _WIN32) && defined(_MSC_VER) std::uint32_t result = 0U; return (_BitScanReverse(result&, input) == 0) ? uint32_digits() : uint32_digits() - result + 1U; #elif defined(__GNUC__) || defined(__clang__) return (input == 0U) ? uint32_digits() : __builtin_clz(input); #else std::uint32_t count = 0U; while (count < uint32_digits() && (input & pow_2_to_31()) != pow_2_to_31()) { input = input << 1; ++count; } return count; #endif } inline std::uint64_t count_leading_zero(std::uint64_t input) { #if defined( _WIN32) && defined(_MSC_VER) std::uint64_t result = 0U; return (_BitScanReverse64(result&, input) == 0) ? uint64_digits() : uint64_digits() - result + 1U; #else std::uint32_t high_result = count_leading_zero(static_cast<std::uint32_t>((input & 0xFFFFFFFF00000000) >> uint32_digits())); return (high_result != uint32_digits()) ? high_result : count_leading_zero(static_cast<std::uint32_t>(input & 0x00000000FFFFFFFF)) + uint32_digits(); #endif } inline std::uint32_t count_leading_zero(std::uint8_t input) { return count_leading_zero(static_cast<std::uint32_t>(input)) + std::numeric_limits<std::uint8_t>::digits - std::numeric_limits<std::uint32_t>::digits; } inline std::uint32_t count_leading_zero(std::uint16_t input) { return count_leading_zero(static_cast<std::uint32_t>(input)) + std::numeric_limits<std::uint16_t>::digits - std::numeric_limits<std::uint32_t>::digits; } } // namespace toolset } // namespace turbo #endif <|endoftext|>
<commit_before><commit_msg>include DYLD_LIBRARY_PATH on macOS for run/dbg<commit_after><|endoftext|>
<commit_before>#include "common/Clock.h" #include "rgw_log.h" #include "rgw_acl.h" #include "rgw_access.h" #define DOUT_SUBSYS rgw static rgw_bucket log_bucket(RGW_LOG_POOL_NAME); static void set_param_str(struct req_state *s, const char *name, string& str) { const char *p = s->env->get(name); if (p) str = p; } string render_log_object_name(const string& format, struct tm *dt, int64_t bucket_id, const string& bucket_name) { string o; for (unsigned i=0; i<format.size(); i++) { if (format[i] == '%' && i+1 < format.size()) { i++; char buf[32]; switch (format[i]) { case '%': strcpy(buf, "%"); break; case 'Y': sprintf(buf, "%.4d", dt->tm_year + 1900); break; case 'y': sprintf(buf, "%.2d", dt->tm_year % 100); break; case 'm': sprintf(buf, "%.2d", dt->tm_mon + 1); break; case 'd': sprintf(buf, "%.2d", dt->tm_mday); break; case 'H': sprintf(buf, "%.2d", dt->tm_hour); break; case 'I': sprintf(buf, "%.2d", (dt->tm_hour % 12) + 1); break; case 'k': sprintf(buf, "%d", dt->tm_hour); break; case 'l': sprintf(buf, "%d", (dt->tm_hour % 12) + 1); break; case 'M': sprintf(buf, "%.2d", dt->tm_min); break; case 'i': sprintf(buf, "%lld", (long long)bucket_id); break; case 'n': o += bucket_name; continue; default: // unknown code sprintf(buf, "%%%c", format[i]); break; } o += buf; continue; } o += format[i]; } return o; } int rgw_log_op(struct req_state *s) { struct rgw_log_entry entry; uint64_t bucket_id; if (!s->should_log) return 0; if (!s->bucket_name) { dout(0) << "nothing to log for operation" << dendl; return -EINVAL; } if (s->err.ret == -ERR_NO_SUCH_BUCKET) { if (!g_conf->rgw_log_nonexistent_bucket) { dout(0) << "bucket " << s->bucket << " doesn't exist, not logging" << dendl; return 0; } bucket_id = 0; } else { bucket_id = s->bucket.bucket_id; } entry.bucket = s->bucket_name; if (s->object) entry.obj = s->object; else entry.obj = "-"; entry.obj_size = s->obj_size; if (g_conf->rgw_remote_addr_param.length()) set_param_str(s, g_conf->rgw_remote_addr_param.c_str(), entry.remote_addr); else set_param_str(s, "REMOTE_ADDR", entry.remote_addr); set_param_str(s, "HTTP_USER_AGENT", entry.user_agent); set_param_str(s, "HTTP_REFERRER", entry.referrer); set_param_str(s, "REQUEST_URI", entry.uri); set_param_str(s, "REQUEST_METHOD", entry.op); entry.user = s->user.user_id; if (s->acl) entry.object_owner = s->acl->get_owner().get_id(); entry.bucket_owner = s->bucket_owner; entry.time = s->time; entry.total_time = ceph_clock_now(g_ceph_context) - s->time; entry.bytes_sent = s->bytes_sent; entry.bytes_received = s->bytes_received; if (s->err.http_ret) { char buf[16]; snprintf(buf, sizeof(buf), "%d", s->err.http_ret); entry.http_status = buf; } else entry.http_status = "200"; // default entry.error_code = s->err.s3_code; entry.bucket_id = bucket_id; bufferlist bl; ::encode(entry, bl); struct tm bdt; time_t t = entry.time.sec(); if (g_conf->rgw_log_object_name_utc) gmtime_r(&t, &bdt); else localtime_r(&t, &bdt); string oid = render_log_object_name(g_conf->rgw_log_object_name, &bdt, s->bucket.bucket_id, entry.bucket.c_str()); rgw_obj obj(log_bucket, oid); int ret = rgwstore->append_async(obj, bl.length(), bl); if (ret == -ENOENT) { string id; map<std::string, bufferlist> attrs; ret = rgwstore->create_bucket(id, log_bucket, attrs, true); if (ret < 0) goto done; // retry ret = rgwstore->append_async(obj, bl.length(), bl); } done: if (ret < 0) dout(0) << "failed to log entry" << dendl; return ret; } int rgw_log_intent(struct req_state *s, rgw_obj& obj, RGWIntentEvent intent) { rgw_bucket intent_log_bucket(RGW_INTENT_LOG_POOL_NAME); rgw_intent_log_entry entry; entry.obj = obj; entry.intent = (uint32_t)intent; entry.op_time = s->time; struct tm bdt; time_t t = entry.op_time.sec(); if (g_conf->rgw_intent_log_object_name_utc) gmtime_r(&t, &bdt); else localtime_r(&t, &bdt); char buf[obj.bucket.name.size() + 16]; sprintf(buf, "%.4d-%.2d-%.2d-%lld-%s", (bdt.tm_year+1900), (bdt.tm_mon+1), bdt.tm_mday, (long long)s->bucket.bucket_id, obj.bucket.name.c_str()); string oid(buf); rgw_obj log_obj(intent_log_bucket, oid); bufferlist bl; ::encode(entry, bl); int ret = rgwstore->append_async(log_obj, bl.length(), bl); if (ret == -ENOENT) { string id; map<std::string, bufferlist> attrs; ret = rgwstore->create_bucket(id, intent_log_bucket, attrs, true); if (ret < 0) goto done; ret = rgwstore->append_async(log_obj, bl.length(), bl); } done: return ret; } <commit_msg>rgw: don't log entries with bad utf8<commit_after>#include "common/Clock.h" #include "common/utf8.h" #include "rgw_log.h" #include "rgw_acl.h" #include "rgw_access.h" #define DOUT_SUBSYS rgw static rgw_bucket log_bucket(RGW_LOG_POOL_NAME); static void set_param_str(struct req_state *s, const char *name, string& str) { const char *p = s->env->get(name); if (p) str = p; } string render_log_object_name(const string& format, struct tm *dt, int64_t bucket_id, const string& bucket_name) { string o; for (unsigned i=0; i<format.size(); i++) { if (format[i] == '%' && i+1 < format.size()) { i++; char buf[32]; switch (format[i]) { case '%': strcpy(buf, "%"); break; case 'Y': sprintf(buf, "%.4d", dt->tm_year + 1900); break; case 'y': sprintf(buf, "%.2d", dt->tm_year % 100); break; case 'm': sprintf(buf, "%.2d", dt->tm_mon + 1); break; case 'd': sprintf(buf, "%.2d", dt->tm_mday); break; case 'H': sprintf(buf, "%.2d", dt->tm_hour); break; case 'I': sprintf(buf, "%.2d", (dt->tm_hour % 12) + 1); break; case 'k': sprintf(buf, "%d", dt->tm_hour); break; case 'l': sprintf(buf, "%d", (dt->tm_hour % 12) + 1); break; case 'M': sprintf(buf, "%.2d", dt->tm_min); break; case 'i': sprintf(buf, "%lld", (long long)bucket_id); break; case 'n': o += bucket_name; continue; default: // unknown code sprintf(buf, "%%%c", format[i]); break; } o += buf; continue; } o += format[i]; } return o; } int rgw_log_op(struct req_state *s) { struct rgw_log_entry entry; uint64_t bucket_id; if (!s->should_log) return 0; if (!s->bucket_name) { dout(0) << "nothing to log for operation" << dendl; return -EINVAL; } if (s->err.ret == -ERR_NO_SUCH_BUCKET) { if (!g_conf->rgw_log_nonexistent_bucket) { dout(0) << "bucket " << s->bucket << " doesn't exist, not logging" << dendl; return 0; } bucket_id = 0; } else { bucket_id = s->bucket.bucket_id; } entry.bucket = s->bucket_name; if (check_utf8(s->bucket_name, entry.bucket.size()) != 0) { dout(0) << "not logging op on bucket with non-utf8 name" << dendl; return 0; } if (s->object) entry.obj = s->object; else entry.obj = "-"; entry.obj_size = s->obj_size; if (g_conf->rgw_remote_addr_param.length()) set_param_str(s, g_conf->rgw_remote_addr_param.c_str(), entry.remote_addr); else set_param_str(s, "REMOTE_ADDR", entry.remote_addr); set_param_str(s, "HTTP_USER_AGENT", entry.user_agent); set_param_str(s, "HTTP_REFERRER", entry.referrer); set_param_str(s, "REQUEST_URI", entry.uri); set_param_str(s, "REQUEST_METHOD", entry.op); entry.user = s->user.user_id; if (s->acl) entry.object_owner = s->acl->get_owner().get_id(); entry.bucket_owner = s->bucket_owner; entry.time = s->time; entry.total_time = ceph_clock_now(g_ceph_context) - s->time; entry.bytes_sent = s->bytes_sent; entry.bytes_received = s->bytes_received; if (s->err.http_ret) { char buf[16]; snprintf(buf, sizeof(buf), "%d", s->err.http_ret); entry.http_status = buf; } else entry.http_status = "200"; // default entry.error_code = s->err.s3_code; entry.bucket_id = bucket_id; bufferlist bl; ::encode(entry, bl); struct tm bdt; time_t t = entry.time.sec(); if (g_conf->rgw_log_object_name_utc) gmtime_r(&t, &bdt); else localtime_r(&t, &bdt); string oid = render_log_object_name(g_conf->rgw_log_object_name, &bdt, s->bucket.bucket_id, entry.bucket.c_str()); rgw_obj obj(log_bucket, oid); int ret = rgwstore->append_async(obj, bl.length(), bl); if (ret == -ENOENT) { string id; map<std::string, bufferlist> attrs; ret = rgwstore->create_bucket(id, log_bucket, attrs, true); if (ret < 0) goto done; // retry ret = rgwstore->append_async(obj, bl.length(), bl); } done: if (ret < 0) dout(0) << "failed to log entry" << dendl; return ret; } int rgw_log_intent(struct req_state *s, rgw_obj& obj, RGWIntentEvent intent) { rgw_bucket intent_log_bucket(RGW_INTENT_LOG_POOL_NAME); rgw_intent_log_entry entry; entry.obj = obj; entry.intent = (uint32_t)intent; entry.op_time = s->time; struct tm bdt; time_t t = entry.op_time.sec(); if (g_conf->rgw_intent_log_object_name_utc) gmtime_r(&t, &bdt); else localtime_r(&t, &bdt); char buf[obj.bucket.name.size() + 16]; sprintf(buf, "%.4d-%.2d-%.2d-%lld-%s", (bdt.tm_year+1900), (bdt.tm_mon+1), bdt.tm_mday, (long long)s->bucket.bucket_id, obj.bucket.name.c_str()); string oid(buf); rgw_obj log_obj(intent_log_bucket, oid); bufferlist bl; ::encode(entry, bl); int ret = rgwstore->append_async(log_obj, bl.length(), bl); if (ret == -ENOENT) { string id; map<std::string, bufferlist> attrs; ret = rgwstore->create_bucket(id, intent_log_bucket, attrs, true); if (ret < 0) goto done; ret = rgwstore->append_async(log_obj, bl.length(), bl); } done: return ret; } <|endoftext|>
<commit_before>/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Filter.hxx" #include "CompletionHandler.hxx" #include "lib/openssl/Name.hxx" #include "lib/openssl/UniqueX509.hxx" #include "FifoBufferBio.hxx" #include "fs/ThreadSocketFilter.hxx" #include "memory/fb_pool.hxx" #include "memory/SliceFifoBuffer.hxx" #include "util/AllocatedArray.hxx" #include "util/AllocatedString.hxx" #include <openssl/ssl.h> #include <openssl/err.h> #include <assert.h> #include <string.h> class SslFilter final : public ThreadSocketFilterHandler, SslCompletionHandler { /** * Buffers which can be accessed from within the thread without * holding locks. These will be copied to/from the according * #thread_socket_filter buffers. */ SliceFifoBuffer encrypted_input, decrypted_input, plain_output, encrypted_output; const UniqueSSL ssl; bool handshaking = true; AllocatedArray<unsigned char> alpn_selected; public: AllocatedString peer_subject, peer_issuer_subject; SslFilter(UniqueSSL &&_ssl) :ssl(std::move(_ssl)) { SSL_set_bio(ssl.get(), NewFifoBufferBio(encrypted_input), NewFifoBufferBio(encrypted_output)); SetSslCompletionHandler(*ssl, *this); } std::span<const unsigned char> GetAlpnSelected() const noexcept { return {alpn_selected.data(), alpn_selected.size()}; } private: /** * Called from inside Run() right after the handshake has * completed. This is used to collect some data for our * public getters. */ void PostHandshake() noexcept; void Encrypt(); /* virtual methods from class ThreadSocketFilterHandler */ void PreRun(ThreadSocketFilterInternal &f) noexcept override; void Run(ThreadSocketFilterInternal &f) override; void PostRun(ThreadSocketFilterInternal &f) noexcept override; void CancelRun(ThreadSocketFilterInternal &f) noexcept override; /* virtual methods from class SslCompletionHandler */ void OnSslCompletion() noexcept override { ScheduleRun(); } }; static std::runtime_error MakeSslError() { unsigned long error = ERR_get_error(); char buffer[120]; return std::runtime_error(ERR_error_string(error, buffer)); } static AllocatedString format_subject_name(X509 *cert) { return ToString(X509_get_subject_name(cert)); } static AllocatedString format_issuer_subject_name(X509 *cert) { return ToString(X509_get_issuer_name(cert)); } [[gnu::pure]] static bool is_ssl_error(SSL *ssl, int ret) { if (ret == 0) /* this is always an error according to the documentation of SSL_read(), SSL_write() and SSL_do_handshake() */ return true; switch (SSL_get_error(ssl, ret)) { case SSL_ERROR_NONE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: case SSL_ERROR_WANT_X509_LOOKUP: return false; default: return true; } } static void CheckThrowSslError(SSL *ssl, int result) { if (is_ssl_error(ssl, result)) throw MakeSslError(); } inline void SslFilter::PostHandshake() noexcept { const unsigned char *alpn_data; unsigned int alpn_length; SSL_get0_alpn_selected(ssl.get(), &alpn_data, &alpn_length); if (alpn_length > 0) alpn_selected = ConstBuffer<unsigned char>(alpn_data, alpn_length); UniqueX509 cert(SSL_get_peer_certificate(ssl.get())); if (cert != nullptr) { peer_subject = format_subject_name(cert.get()); peer_issuer_subject = format_issuer_subject_name(cert.get()); } } enum class SslDecryptResult { SUCCESS, /** * More encrypted_input data is required. */ MORE, CLOSE_NOTIFY_ALERT, }; static SslDecryptResult ssl_decrypt(SSL *ssl, ForeignFifoBuffer<std::byte> &buffer) { /* SSL_read() must be called repeatedly until there is no more data (or until the buffer is full) */ while (true) { auto w = buffer.Write(); if (w.empty()) return SslDecryptResult::SUCCESS; int result = SSL_read(ssl, w.data(), w.size()); if (result < 0 && SSL_get_error(ssl, result) == SSL_ERROR_WANT_READ) return SslDecryptResult::MORE; if (result <= 0) { if (SSL_get_error(ssl, result) == SSL_ERROR_ZERO_RETURN) /* got a "close notify" alert from the peer */ return SslDecryptResult::CLOSE_NOTIFY_ALERT; CheckThrowSslError(ssl, result); return SslDecryptResult::SUCCESS; } buffer.Append(result); } } static void ssl_encrypt(SSL *ssl, ForeignFifoBuffer<std::byte> &buffer) { /* SSL_write() must be called repeatedly until there is no more data; with SSL_MODE_ENABLE_PARTIAL_WRITE, SSL_write() finishes only the current incomplete record, and additional data which has been submitted more recently will only be considered in the next SSL_write() call */ while (true) { auto r = buffer.Read(); if (r.empty()) return; int result = SSL_write(ssl, r.data(), r.size()); if (result <= 0) { CheckThrowSslError(ssl, result); return; } buffer.Consume(result); } } inline void SslFilter::Encrypt() { ssl_encrypt(ssl.get(), plain_output); } /* * thread_socket_filter_handler * */ void SslFilter::PreRun(ThreadSocketFilterInternal &f) noexcept { if (f.IsIdle()) { decrypted_input.AllocateIfNull(fb_pool_get()); encrypted_output.AllocateIfNull(fb_pool_get()); } } void SslFilter::Run(ThreadSocketFilterInternal &f) { /* copy input (and output to make room for more output) */ { std::unique_lock<std::mutex> lock(f.mutex); if (f.decrypted_input.IsNull() || f.encrypted_output.IsNull()) { /* retry, let PreRun() allocate the missing buffer */ f.again = true; return; } f.decrypted_input.MoveFromAllowNull(decrypted_input); plain_output.MoveFromAllowNull(f.plain_output); encrypted_input.MoveFromAllowSrcNull(f.encrypted_input); f.encrypted_output.MoveFromAllowNull(encrypted_output); if (decrypted_input.IsNull() || encrypted_output.IsNull()) { /* retry, let PreRun() allocate the missing buffer */ f.again = true; return; } } /* let OpenSSL work */ ERR_clear_error(); if (handshaking) [[unlikely]] { int result = SSL_do_handshake(ssl.get()); if (result == 1) { handshaking = false; PostHandshake(); } else { try { CheckThrowSslError(ssl.get(), result); /* flush the encrypted_output buffer, because it may contain a "TLS alert" */ } catch (...) { const std::lock_guard<std::mutex> lock(f.mutex); f.encrypted_output.MoveFromAllowNull(encrypted_output); throw; } } } if (!handshaking) [[likely]] { Encrypt(); switch (ssl_decrypt(ssl.get(), decrypted_input)) { case SslDecryptResult::SUCCESS: break; case SslDecryptResult::MORE: if (encrypted_input.IsDefinedAndFull()) throw std::runtime_error("SSL encrypted_input buffer is full"); break; case SslDecryptResult::CLOSE_NOTIFY_ALERT: { std::unique_lock<std::mutex> lock(f.mutex); f.input_eof = true; } break; } } /* copy output */ { std::unique_lock<std::mutex> lock(f.mutex); f.decrypted_input.MoveFromAllowNull(decrypted_input); f.encrypted_output.MoveFromAllowNull(encrypted_output); f.drained = plain_output.empty() && encrypted_output.empty(); if (!decrypted_input.IsDefinedAndFull() && !f.encrypted_input.empty()) /* there's more data to be decrypted and we still have room in the destination buffer, so let's run again */ f.again = true; if (!f.plain_output.empty() && !plain_output.IsDefinedAndFull() && !encrypted_output.IsDefinedAndFull()) /* there's more data, and we're ready to handle it: try again */ f.again = true; f.handshaking = handshaking; } } void SslFilter::PostRun(ThreadSocketFilterInternal &f) noexcept { if (f.IsIdle()) { plain_output.FreeIfEmpty(); encrypted_input.FreeIfEmpty(); decrypted_input.FreeIfEmpty(); encrypted_output.FreeIfEmpty(); } } void SslFilter::CancelRun(ThreadSocketFilterInternal &) noexcept { if (cancel_ptr) /* cancel the CertCache::Apply() call */ cancel_ptr.Cancel(); } /* * constructor * */ std::unique_ptr<ThreadSocketFilterHandler> ssl_filter_new(UniqueSSL &&ssl) noexcept { return std::make_unique<SslFilter>(std::move(ssl)); } SslFilter & ssl_filter_cast_from(ThreadSocketFilterHandler &tsfh) noexcept { return static_cast<SslFilter &>(tsfh); } const SslFilter * ssl_filter_cast_from(const SocketFilter *socket_filter) noexcept { const auto *tsf = dynamic_cast<const ThreadSocketFilter *>(socket_filter); if (tsf == nullptr) return nullptr; return dynamic_cast<const SslFilter *>(&tsf->GetHandler()); } std::span<const unsigned char> ssl_filter_get_alpn_selected(const SslFilter &ssl) noexcept { return ssl.GetAlpnSelected(); } const char * ssl_filter_get_peer_subject(const SslFilter &ssl) noexcept { return ssl.peer_subject.c_str(); } const char * ssl_filter_get_peer_issuer_subject(const SslFilter &ssl) noexcept { return ssl.peer_issuer_subject.c_str(); } <commit_msg>ssl/Filter: use std::span<commit_after>/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Filter.hxx" #include "CompletionHandler.hxx" #include "lib/openssl/Name.hxx" #include "lib/openssl/UniqueX509.hxx" #include "FifoBufferBio.hxx" #include "fs/ThreadSocketFilter.hxx" #include "memory/fb_pool.hxx" #include "memory/SliceFifoBuffer.hxx" #include "util/AllocatedArray.hxx" #include "util/AllocatedString.hxx" #include <openssl/ssl.h> #include <openssl/err.h> #include <assert.h> #include <string.h> class SslFilter final : public ThreadSocketFilterHandler, SslCompletionHandler { /** * Buffers which can be accessed from within the thread without * holding locks. These will be copied to/from the according * #thread_socket_filter buffers. */ SliceFifoBuffer encrypted_input, decrypted_input, plain_output, encrypted_output; const UniqueSSL ssl; bool handshaking = true; AllocatedArray<unsigned char> alpn_selected; public: AllocatedString peer_subject, peer_issuer_subject; SslFilter(UniqueSSL &&_ssl) :ssl(std::move(_ssl)) { SSL_set_bio(ssl.get(), NewFifoBufferBio(encrypted_input), NewFifoBufferBio(encrypted_output)); SetSslCompletionHandler(*ssl, *this); } std::span<const unsigned char> GetAlpnSelected() const noexcept { return {alpn_selected.data(), alpn_selected.size()}; } private: /** * Called from inside Run() right after the handshake has * completed. This is used to collect some data for our * public getters. */ void PostHandshake() noexcept; void Encrypt(); /* virtual methods from class ThreadSocketFilterHandler */ void PreRun(ThreadSocketFilterInternal &f) noexcept override; void Run(ThreadSocketFilterInternal &f) override; void PostRun(ThreadSocketFilterInternal &f) noexcept override; void CancelRun(ThreadSocketFilterInternal &f) noexcept override; /* virtual methods from class SslCompletionHandler */ void OnSslCompletion() noexcept override { ScheduleRun(); } }; static std::runtime_error MakeSslError() { unsigned long error = ERR_get_error(); char buffer[120]; return std::runtime_error(ERR_error_string(error, buffer)); } static AllocatedString format_subject_name(X509 *cert) { return ToString(X509_get_subject_name(cert)); } static AllocatedString format_issuer_subject_name(X509 *cert) { return ToString(X509_get_issuer_name(cert)); } [[gnu::pure]] static bool is_ssl_error(SSL *ssl, int ret) { if (ret == 0) /* this is always an error according to the documentation of SSL_read(), SSL_write() and SSL_do_handshake() */ return true; switch (SSL_get_error(ssl, ret)) { case SSL_ERROR_NONE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: case SSL_ERROR_WANT_X509_LOOKUP: return false; default: return true; } } static void CheckThrowSslError(SSL *ssl, int result) { if (is_ssl_error(ssl, result)) throw MakeSslError(); } inline void SslFilter::PostHandshake() noexcept { const unsigned char *alpn_data; unsigned int alpn_length; SSL_get0_alpn_selected(ssl.get(), &alpn_data, &alpn_length); if (alpn_length > 0) alpn_selected = std::span<const unsigned char>(alpn_data, alpn_length); UniqueX509 cert(SSL_get_peer_certificate(ssl.get())); if (cert != nullptr) { peer_subject = format_subject_name(cert.get()); peer_issuer_subject = format_issuer_subject_name(cert.get()); } } enum class SslDecryptResult { SUCCESS, /** * More encrypted_input data is required. */ MORE, CLOSE_NOTIFY_ALERT, }; static SslDecryptResult ssl_decrypt(SSL *ssl, ForeignFifoBuffer<std::byte> &buffer) { /* SSL_read() must be called repeatedly until there is no more data (or until the buffer is full) */ while (true) { auto w = buffer.Write(); if (w.empty()) return SslDecryptResult::SUCCESS; int result = SSL_read(ssl, w.data(), w.size()); if (result < 0 && SSL_get_error(ssl, result) == SSL_ERROR_WANT_READ) return SslDecryptResult::MORE; if (result <= 0) { if (SSL_get_error(ssl, result) == SSL_ERROR_ZERO_RETURN) /* got a "close notify" alert from the peer */ return SslDecryptResult::CLOSE_NOTIFY_ALERT; CheckThrowSslError(ssl, result); return SslDecryptResult::SUCCESS; } buffer.Append(result); } } static void ssl_encrypt(SSL *ssl, ForeignFifoBuffer<std::byte> &buffer) { /* SSL_write() must be called repeatedly until there is no more data; with SSL_MODE_ENABLE_PARTIAL_WRITE, SSL_write() finishes only the current incomplete record, and additional data which has been submitted more recently will only be considered in the next SSL_write() call */ while (true) { auto r = buffer.Read(); if (r.empty()) return; int result = SSL_write(ssl, r.data(), r.size()); if (result <= 0) { CheckThrowSslError(ssl, result); return; } buffer.Consume(result); } } inline void SslFilter::Encrypt() { ssl_encrypt(ssl.get(), plain_output); } /* * thread_socket_filter_handler * */ void SslFilter::PreRun(ThreadSocketFilterInternal &f) noexcept { if (f.IsIdle()) { decrypted_input.AllocateIfNull(fb_pool_get()); encrypted_output.AllocateIfNull(fb_pool_get()); } } void SslFilter::Run(ThreadSocketFilterInternal &f) { /* copy input (and output to make room for more output) */ { std::unique_lock<std::mutex> lock(f.mutex); if (f.decrypted_input.IsNull() || f.encrypted_output.IsNull()) { /* retry, let PreRun() allocate the missing buffer */ f.again = true; return; } f.decrypted_input.MoveFromAllowNull(decrypted_input); plain_output.MoveFromAllowNull(f.plain_output); encrypted_input.MoveFromAllowSrcNull(f.encrypted_input); f.encrypted_output.MoveFromAllowNull(encrypted_output); if (decrypted_input.IsNull() || encrypted_output.IsNull()) { /* retry, let PreRun() allocate the missing buffer */ f.again = true; return; } } /* let OpenSSL work */ ERR_clear_error(); if (handshaking) [[unlikely]] { int result = SSL_do_handshake(ssl.get()); if (result == 1) { handshaking = false; PostHandshake(); } else { try { CheckThrowSslError(ssl.get(), result); /* flush the encrypted_output buffer, because it may contain a "TLS alert" */ } catch (...) { const std::lock_guard<std::mutex> lock(f.mutex); f.encrypted_output.MoveFromAllowNull(encrypted_output); throw; } } } if (!handshaking) [[likely]] { Encrypt(); switch (ssl_decrypt(ssl.get(), decrypted_input)) { case SslDecryptResult::SUCCESS: break; case SslDecryptResult::MORE: if (encrypted_input.IsDefinedAndFull()) throw std::runtime_error("SSL encrypted_input buffer is full"); break; case SslDecryptResult::CLOSE_NOTIFY_ALERT: { std::unique_lock<std::mutex> lock(f.mutex); f.input_eof = true; } break; } } /* copy output */ { std::unique_lock<std::mutex> lock(f.mutex); f.decrypted_input.MoveFromAllowNull(decrypted_input); f.encrypted_output.MoveFromAllowNull(encrypted_output); f.drained = plain_output.empty() && encrypted_output.empty(); if (!decrypted_input.IsDefinedAndFull() && !f.encrypted_input.empty()) /* there's more data to be decrypted and we still have room in the destination buffer, so let's run again */ f.again = true; if (!f.plain_output.empty() && !plain_output.IsDefinedAndFull() && !encrypted_output.IsDefinedAndFull()) /* there's more data, and we're ready to handle it: try again */ f.again = true; f.handshaking = handshaking; } } void SslFilter::PostRun(ThreadSocketFilterInternal &f) noexcept { if (f.IsIdle()) { plain_output.FreeIfEmpty(); encrypted_input.FreeIfEmpty(); decrypted_input.FreeIfEmpty(); encrypted_output.FreeIfEmpty(); } } void SslFilter::CancelRun(ThreadSocketFilterInternal &) noexcept { if (cancel_ptr) /* cancel the CertCache::Apply() call */ cancel_ptr.Cancel(); } /* * constructor * */ std::unique_ptr<ThreadSocketFilterHandler> ssl_filter_new(UniqueSSL &&ssl) noexcept { return std::make_unique<SslFilter>(std::move(ssl)); } SslFilter & ssl_filter_cast_from(ThreadSocketFilterHandler &tsfh) noexcept { return static_cast<SslFilter &>(tsfh); } const SslFilter * ssl_filter_cast_from(const SocketFilter *socket_filter) noexcept { const auto *tsf = dynamic_cast<const ThreadSocketFilter *>(socket_filter); if (tsf == nullptr) return nullptr; return dynamic_cast<const SslFilter *>(&tsf->GetHandler()); } std::span<const unsigned char> ssl_filter_get_alpn_selected(const SslFilter &ssl) noexcept { return ssl.GetAlpnSelected(); } const char * ssl_filter_get_peer_subject(const SslFilter &ssl) noexcept { return ssl.peer_subject.c_str(); } const char * ssl_filter_get_peer_issuer_subject(const SslFilter &ssl) noexcept { return ssl.peer_issuer_subject.c_str(); } <|endoftext|>
<commit_before>/* * bacteria-core, core for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #include "Model.hpp" typedef void (Implementation::Model::*OneArgMethod) ( const Abstract::Point& coordinates ); typedef void (Implementation::Model::*TwoArgsMethod) ( const Abstract::Point& coordinates, int change ); typedef void (Implementation::Model::*MultiArgsMethod) ( const Abstract::Point& coordinates, int mass, int direction, int team, int instruction ); template<typename Func> void checkModelMethodForThrow( Implementation::Model* model, Func model_method, int arg1, int arg2 ) { BOOST_REQUIRE_THROW( ((*model).*model_method)(arg1, arg2), Exception ); } template<> void checkModelMethodForThrow<OneArgMethod>( Implementation::Model* model, OneArgMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates), Exception ); } template<> void checkModelMethodForThrow<TwoArgsMethod>( Implementation::Model* model, TwoArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates, 0), Exception ); } template<> void checkModelMethodForThrow<MultiArgsMethod>( Implementation::Model* model, MultiArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)( coordinates, DEFAULT_MASS, 0, 0, 0 ), Exception ); } // "dead" test: attempt to do something with dead bacterium template<typename Func> static void deadTest( Implementation::Model* model, Func model_method ) { model->kill(0, 0); checkModelMethodForThrow( model, model_method, 0, 0 ); } template<typename Func> static void checkErrorHandling( Implementation::Model* model, Func model_method, bool dead_test ) { // Range errors: test all combinations of // "wrong" (outside of correct range) arguments. // This solution works for coordinates and non-coordinates // methods of Model. (< 0, = 0, > MAX) int wrong_args[] = {-1, 0, MIN_WIDTH}; BOOST_FOREACH (int arg1, wrong_args) { BOOST_FOREACH (int arg2, wrong_args) { if ((arg1 != 0) || (arg2 != 0)) { // (0, 0) is correct checkModelMethodForThrow( model, model_method, arg1, arg2 ); } } } if (dead_test) { // "dead" error // (attempt to do something with dead bacterium) deadTest(model, model_method); } } static Abstract::Point createInBaseCoordinates( Implementation::Model* model ) { Abstract::Point coordinates(0, 0); model->createNewByCoordinates( coordinates, DEFAULT_MASS, 0, 0, 0 ); return coordinates; } static Implementation::Model* createBaseModel( int bacteria = 0, int teams = 1 ) { Implementation::Model* model = Abstract::makeModel<Implementation::Model>( MIN_WIDTH, MIN_HEIGHT, bacteria, teams ); return model; } BOOST_AUTO_TEST_CASE (bacteria_number_test) { Implementation::Model* model = createBaseModel(); int bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 0); createInBaseCoordinates(model); bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 1); // range errors BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception); BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception); delete model; } BOOST_AUTO_TEST_CASE (get_instruction_test) { Implementation::Model* model = createBaseModel(1, 1); int instruction = model->getInstruction(0, 0); BOOST_REQUIRE(instruction == 0); checkErrorHandling( model, &Implementation::Model::getInstruction, true ); delete model; } BOOST_AUTO_TEST_CASE (get_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::Point derived_coordinates = model->getCoordinates(0, 0); BOOST_REQUIRE(derived_coordinates == coordinates); checkErrorHandling( model, &Implementation::Model::getCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (get_direction_test) { Implementation::Model* model = createBaseModel(); createInBaseCoordinates(model); int direction = model->getDirection(0, 0); BOOST_REQUIRE(direction == Abstract::LEFT); checkErrorHandling( model, &Implementation::Model::getDirection, true ); delete model; } BOOST_AUTO_TEST_CASE (get_mass_test) { Implementation::Model* model = createBaseModel(1, 1); int mass = model->getMass(0, 0); BOOST_REQUIRE(mass == DEFAULT_MASS); checkErrorHandling( model, &Implementation::Model::getMass, true ); delete model; } BOOST_AUTO_TEST_CASE (height_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT); delete model; } BOOST_AUTO_TEST_CASE (width_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getWidth() == MIN_WIDTH); delete model; } BOOST_AUTO_TEST_CASE (kill_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->kill(0, 0); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); // error handling checks createInBaseCoordinates(model); // FIXME test doesn't work correctly without this function call. // The solution is to use set instead of vector in model. model->clearBeforeMove(0); checkErrorHandling( model, &Implementation::Model::kill, true ); delete model; } BOOST_AUTO_TEST_CASE (create_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::BACTERIUM); checkErrorHandling<MultiArgsMethod>( model, &Implementation::Model::createNewByCoordinates, false ); delete model; } BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); int test_val = 1; model->changeMassByCoordinates(coordinates, test_val); int new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val)); model->changeMassByCoordinates(coordinates, -test_val); new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == DEFAULT_MASS); checkErrorHandling<TwoArgsMethod>( model, &Implementation::Model::changeMassByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (kill_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->killByCoordinates(coordinates); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); checkErrorHandling<OneArgMethod>( model, &Implementation::Model::killByCoordinates, false ); delete model; } <commit_msg>Model tests: add isAlive() check to kill_test<commit_after>/* * bacteria-core, core for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #include "Model.hpp" typedef void (Implementation::Model::*OneArgMethod) ( const Abstract::Point& coordinates ); typedef void (Implementation::Model::*TwoArgsMethod) ( const Abstract::Point& coordinates, int change ); typedef void (Implementation::Model::*MultiArgsMethod) ( const Abstract::Point& coordinates, int mass, int direction, int team, int instruction ); template<typename Func> void checkModelMethodForThrow( Implementation::Model* model, Func model_method, int arg1, int arg2 ) { BOOST_REQUIRE_THROW( ((*model).*model_method)(arg1, arg2), Exception ); } template<> void checkModelMethodForThrow<OneArgMethod>( Implementation::Model* model, OneArgMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates), Exception ); } template<> void checkModelMethodForThrow<TwoArgsMethod>( Implementation::Model* model, TwoArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates, 0), Exception ); } template<> void checkModelMethodForThrow<MultiArgsMethod>( Implementation::Model* model, MultiArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)( coordinates, DEFAULT_MASS, 0, 0, 0 ), Exception ); } // "dead" test: attempt to do something with dead bacterium template<typename Func> static void deadTest( Implementation::Model* model, Func model_method ) { model->kill(0, 0); checkModelMethodForThrow( model, model_method, 0, 0 ); } template<typename Func> static void checkErrorHandling( Implementation::Model* model, Func model_method, bool dead_test ) { // Range errors: test all combinations of // "wrong" (outside of correct range) arguments. // This solution works for coordinates and non-coordinates // methods of Model. (< 0, = 0, > MAX) int wrong_args[] = {-1, 0, MIN_WIDTH}; BOOST_FOREACH (int arg1, wrong_args) { BOOST_FOREACH (int arg2, wrong_args) { if ((arg1 != 0) || (arg2 != 0)) { // (0, 0) is correct checkModelMethodForThrow( model, model_method, arg1, arg2 ); } } } if (dead_test) { // "dead" error // (attempt to do something with dead bacterium) deadTest(model, model_method); } } static Abstract::Point createInBaseCoordinates( Implementation::Model* model ) { Abstract::Point coordinates(0, 0); model->createNewByCoordinates( coordinates, DEFAULT_MASS, 0, 0, 0 ); return coordinates; } static Implementation::Model* createBaseModel( int bacteria = 0, int teams = 1 ) { Implementation::Model* model = Abstract::makeModel<Implementation::Model>( MIN_WIDTH, MIN_HEIGHT, bacteria, teams ); return model; } BOOST_AUTO_TEST_CASE (bacteria_number_test) { Implementation::Model* model = createBaseModel(); int bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 0); createInBaseCoordinates(model); bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 1); // range errors BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception); BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception); delete model; } BOOST_AUTO_TEST_CASE (get_instruction_test) { Implementation::Model* model = createBaseModel(1, 1); int instruction = model->getInstruction(0, 0); BOOST_REQUIRE(instruction == 0); checkErrorHandling( model, &Implementation::Model::getInstruction, true ); delete model; } BOOST_AUTO_TEST_CASE (get_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::Point derived_coordinates = model->getCoordinates(0, 0); BOOST_REQUIRE(derived_coordinates == coordinates); checkErrorHandling( model, &Implementation::Model::getCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (get_direction_test) { Implementation::Model* model = createBaseModel(); createInBaseCoordinates(model); int direction = model->getDirection(0, 0); BOOST_REQUIRE(direction == Abstract::LEFT); checkErrorHandling( model, &Implementation::Model::getDirection, true ); delete model; } BOOST_AUTO_TEST_CASE (get_mass_test) { Implementation::Model* model = createBaseModel(1, 1); int mass = model->getMass(0, 0); BOOST_REQUIRE(mass == DEFAULT_MASS); checkErrorHandling( model, &Implementation::Model::getMass, true ); delete model; } BOOST_AUTO_TEST_CASE (height_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT); delete model; } BOOST_AUTO_TEST_CASE (width_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getWidth() == MIN_WIDTH); delete model; } BOOST_AUTO_TEST_CASE (kill_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->kill(0, 0); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); BOOST_REQUIRE(model->isAlive(0, 0) == false); // error handling checks createInBaseCoordinates(model); // FIXME test doesn't work correctly without this function call. // The solution is to use set instead of vector in model. model->clearBeforeMove(0); checkErrorHandling( model, &Implementation::Model::kill, true ); delete model; } BOOST_AUTO_TEST_CASE (create_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::BACTERIUM); checkErrorHandling<MultiArgsMethod>( model, &Implementation::Model::createNewByCoordinates, false ); delete model; } BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); int test_val = 1; model->changeMassByCoordinates(coordinates, test_val); int new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val)); model->changeMassByCoordinates(coordinates, -test_val); new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == DEFAULT_MASS); checkErrorHandling<TwoArgsMethod>( model, &Implementation::Model::changeMassByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (kill_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->killByCoordinates(coordinates); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); checkErrorHandling<OneArgMethod>( model, &Implementation::Model::killByCoordinates, false ); delete model; } <|endoftext|>
<commit_before>/* * This file is part of WinSparkle (http://winsparkle.org) * * Copyright (C) 2009 Vaclav Slavik * * 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. * */ #include "threads.h" #include "error.h" #include <windows.h> #include <process.h> namespace winsparkle { /*--------------------------------------------------------------------------* Helpers *--------------------------------------------------------------------------*/ namespace { // Sets thread's name for the debugger void SetThreadName(DWORD threadId, const char *name) { #ifdef _MSC_VER // This code is copied verbatim from MSDN, see // http://msdn.microsoft.com/en-us/library/xcb2z8hs%28VS.100%29.aspx #define MS_VC_EXCEPTION 0x406D1388 #pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) Sleep(10); THREADNAME_INFO info; info.dwType = 0x1000; info.szName = name; info.dwThreadID = threadId; info.dwFlags = 0; __try { RaiseException ( MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info ); } __except(EXCEPTION_EXECUTE_HANDLER) { } #endif // _MSC_VER } } // anonymous namespace /*--------------------------------------------------------------------------* Thread class *--------------------------------------------------------------------------*/ Thread::Thread(const char *name) : m_handle(NULL), m_id(0), m_signalEvent(NULL) { m_handle = (HANDLE)_beginthreadex ( NULL, // default security 0, // default stack size &Thread::ThreadEntryPoint, this, // arguments CREATE_SUSPENDED, &m_id // thread ID ); if ( !m_handle ) throw Win32Exception(); } Thread::~Thread() { if ( m_handle ) CloseHandle(m_handle); } /*static*/ unsigned __stdcall Thread::ThreadEntryPoint(void *data) { Thread *thread = reinterpret_cast<Thread*>(data); thread->Run(); if ( !thread->IsJoinable() ) delete thread; return 0; } void Thread::Start() { if ( !m_handle ) throw Win32Exception(); m_signalEvent = CreateEvent ( NULL, // default security attributes FALSE, // auto-reset FALSE, // initially non-signaled NULL // anonymous ); if ( !m_signalEvent ) throw Win32Exception(); if ( ResumeThread(m_handle) == (DWORD)-1 ) { CloseHandle(m_signalEvent); m_signalEvent = NULL; throw Win32Exception(); } // Wait until Run() signals that it is fully initialized. WaitForSingleObject(m_signalEvent, INFINITE); CloseHandle(m_signalEvent); m_signalEvent = NULL; } void Thread::SignalReady() { SetEvent(m_signalEvent); } } // namespace winsparkle <commit_msg>Forgot to actually set thread's name in ctor.<commit_after>/* * This file is part of WinSparkle (http://winsparkle.org) * * Copyright (C) 2009 Vaclav Slavik * * 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. * */ #include "threads.h" #include "error.h" #include <windows.h> #include <process.h> namespace winsparkle { /*--------------------------------------------------------------------------* Helpers *--------------------------------------------------------------------------*/ namespace { // Sets thread's name for the debugger void SetThreadName(DWORD threadId, const char *name) { #ifdef _MSC_VER // This code is copied verbatim from MSDN, see // http://msdn.microsoft.com/en-us/library/xcb2z8hs%28VS.100%29.aspx #define MS_VC_EXCEPTION 0x406D1388 #pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) Sleep(10); THREADNAME_INFO info; info.dwType = 0x1000; info.szName = name; info.dwThreadID = threadId; info.dwFlags = 0; __try { RaiseException ( MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info ); } __except(EXCEPTION_EXECUTE_HANDLER) { } #endif // _MSC_VER } } // anonymous namespace /*--------------------------------------------------------------------------* Thread class *--------------------------------------------------------------------------*/ Thread::Thread(const char *name) : m_handle(NULL), m_id(0), m_signalEvent(NULL) { m_handle = (HANDLE)_beginthreadex ( NULL, // default security 0, // default stack size &Thread::ThreadEntryPoint, this, // arguments CREATE_SUSPENDED, &m_id // thread ID ); if ( !m_handle ) throw Win32Exception(); SetThreadName(m_id, name); } Thread::~Thread() { if ( m_handle ) CloseHandle(m_handle); } /*static*/ unsigned __stdcall Thread::ThreadEntryPoint(void *data) { Thread *thread = reinterpret_cast<Thread*>(data); thread->Run(); if ( !thread->IsJoinable() ) delete thread; return 0; } void Thread::Start() { if ( !m_handle ) throw Win32Exception(); m_signalEvent = CreateEvent ( NULL, // default security attributes FALSE, // auto-reset FALSE, // initially non-signaled NULL // anonymous ); if ( !m_signalEvent ) throw Win32Exception(); if ( ResumeThread(m_handle) == (DWORD)-1 ) { CloseHandle(m_signalEvent); m_signalEvent = NULL; throw Win32Exception(); } // Wait until Run() signals that it is fully initialized. WaitForSingleObject(m_signalEvent, INFINITE); CloseHandle(m_signalEvent); m_signalEvent = NULL; } void Thread::SignalReady() { SetEvent(m_signalEvent); } } // namespace winsparkle <|endoftext|>
<commit_before>#include <QtGui> #include <QHeaderView> #include <QDesktopServices> #include <QEvent> #include <QShowEvent> #include <QHideEvent> #include "QtAwesome.h" #include "utils/utils.h" #include "seafile-applet.h" #include "rpc/rpc-client.h" #include "rpc/local-repo.h" #include "download-repo-dialog.h" #include "clone-tasks-dialog.h" #include "cloud-view.h" #include "repo-item.h" #include "repo-item-delegate.h" #include "repo-tree-model.h" #include "repo-tree-view.h" #include "repo-detail-dialog.h" RepoTreeView::RepoTreeView(CloudView *cloud_view, QWidget *parent) : QTreeView(parent), cloud_view_(cloud_view) { header()->hide(); createActions(); // We draw the indicator ourselves setIndentation(0); // We handle the click oursevles setExpandsOnDoubleClick(false); connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(onItemClicked(const QModelIndex&))); connect(this, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(onItemDoubleClicked(const QModelIndex&))); } void RepoTreeView::contextMenuEvent(QContextMenuEvent *event) { QPoint pos = event->pos(); QModelIndex index = indexAt(pos); if (!index.isValid()) { // Not clicked at a repo item return; } QStandardItem *item = getRepoItem(index); if (!item || item->type() != REPO_ITEM_TYPE) { return; } updateRepoActions(); QMenu *menu = prepareContextMenu((RepoItem *)item); pos = viewport()->mapToGlobal(pos); menu->exec(pos); } QMenu* RepoTreeView::prepareContextMenu(const RepoItem *item) { QMenu *menu = new QMenu(this); if (item->localRepo().isValid()) { menu->addAction(open_local_folder_action_); } if (item->repoDownloadable()) { menu->addAction(download_action_); } menu->addAction(view_on_web_action_); if (item->localRepo().isValid()) { menu->addSeparator(); menu->addAction(toggle_auto_sync_action_); menu->addAction(sync_now_action_); menu->addSeparator(); } menu->addAction(show_detail_action_); if (item->cloneTask().isCancelable()) { menu->addAction(cancel_download_action_); } if (item->localRepo().isValid()) { menu->addAction(unsync_action_); } return menu; } void RepoTreeView::updateRepoActions() { RepoItem *item = NULL; QItemSelection selected = selectionModel()->selection(); QModelIndexList indexes = selected.indexes(); if (indexes.size() != 0) { const QModelIndex& index = indexes.at(0); QStandardItem *it = ((RepoTreeModel *)model())->itemFromIndex(index); if (it && it->type() == REPO_ITEM_TYPE) { item = (RepoItem *)it; } } if (!item) { // No repo item is selected download_action_->setEnabled(false); sync_now_action_->setEnabled(false); open_local_folder_action_->setEnabled(false); unsync_action_->setEnabled(false); toggle_auto_sync_action_->setEnabled(false); view_on_web_action_->setEnabled(false); show_detail_action_->setEnabled(false); return; } LocalRepo r; seafApplet->rpcClient()->getLocalRepo(item->repo().id, &r); item->setLocalRepo(r); if (item->localRepo().isValid()) { const LocalRepo& local_repo = item->localRepo(); download_action_->setEnabled(false); sync_now_action_->setEnabled(true); sync_now_action_->setData(QVariant::fromValue(local_repo)); open_local_folder_action_->setData(QVariant::fromValue(local_repo)); open_local_folder_action_->setEnabled(true); unsync_action_->setData(QVariant::fromValue(local_repo)); unsync_action_->setEnabled(true); toggle_auto_sync_action_->setData(QVariant::fromValue(local_repo)); toggle_auto_sync_action_->setEnabled(true); if (local_repo.auto_sync) { toggle_auto_sync_action_->setText(tr("Disable auto sync")); toggle_auto_sync_action_->setToolTip(tr("Disable auto sync")); toggle_auto_sync_action_->setIcon(QIcon(":/images/pause.png")); } else { toggle_auto_sync_action_->setText(tr("Enable auto sync")); toggle_auto_sync_action_->setToolTip(tr("Enable auto sync")); toggle_auto_sync_action_->setIcon(QIcon(":/images/play.png")); } } else { if (item->repoDownloadable()) { download_action_->setEnabled(true); download_action_->setData(QVariant::fromValue(item->repo())); } else { download_action_->setEnabled(false); } sync_now_action_->setEnabled(false); open_local_folder_action_->setEnabled(false); unsync_action_->setEnabled(false); toggle_auto_sync_action_->setEnabled(false); } view_on_web_action_->setEnabled(true); view_on_web_action_->setData(item->repo().id); show_detail_action_->setEnabled(true); show_detail_action_->setData(QVariant::fromValue(item->repo())); if (item->cloneTask().isCancelable()) { cancel_download_action_->setEnabled(true); cancel_download_action_->setData(QVariant::fromValue(item->repo())); } else { cancel_download_action_->setEnabled(false); } } QStandardItem* RepoTreeView::getRepoItem(const QModelIndex &index) const { if (!index.isValid()) { return NULL; } const RepoTreeModel *model = (const RepoTreeModel*)index.model(); QStandardItem *item = model->itemFromIndex(index); if (item->type() != REPO_ITEM_TYPE && item->type() != REPO_CATEGORY_TYPE) { return NULL; } return item; } void RepoTreeView::createActions() { show_detail_action_ = new QAction(tr("&Show details"), this); show_detail_action_->setIcon(QIcon(":/images/info.png")); show_detail_action_->setStatusTip(tr("Download this library")); show_detail_action_->setIconVisibleInMenu(true); connect(show_detail_action_, SIGNAL(triggered()), this, SLOT(showRepoDetail())); download_action_ = new QAction(tr("&Download this library"), this); download_action_->setIcon(QIcon(":/images/download.png")); download_action_->setStatusTip(tr("Download this library")); download_action_->setIconVisibleInMenu(true); connect(download_action_, SIGNAL(triggered()), this, SLOT(downloadRepo())); sync_now_action_ = new QAction(tr("&Sync now"), this); sync_now_action_->setIcon(QIcon(":/images/sync_now.png")); sync_now_action_->setStatusTip(tr("Sync this library immediately")); sync_now_action_->setIconVisibleInMenu(true); connect(sync_now_action_, SIGNAL(triggered()), this, SLOT(syncRepoImmediately())); cancel_download_action_ = new QAction(tr("&Cancel download"), this); cancel_download_action_->setIcon(QIcon(":/images/remove.png")); cancel_download_action_->setStatusTip(tr("Cancel download of this library")); cancel_download_action_->setIconVisibleInMenu(true); connect(cancel_download_action_, SIGNAL(triggered()), this, SLOT(cancelDownload())); open_local_folder_action_ = new QAction(tr("&Open folder"), this); open_local_folder_action_->setIcon(QIcon(":/images/folder-open.png")); open_local_folder_action_->setStatusTip(tr("open local folder")); open_local_folder_action_->setIconVisibleInMenu(true); connect(open_local_folder_action_, SIGNAL(triggered()), this, SLOT(openLocalFolder())); unsync_action_ = new QAction(tr("&Unsync"), this); unsync_action_->setStatusTip(tr("unsync this library")); unsync_action_->setIcon(QIcon(":/images/minus.png")); unsync_action_->setIconVisibleInMenu(true); connect(unsync_action_, SIGNAL(triggered()), this, SLOT(unsyncRepo())); toggle_auto_sync_action_ = new QAction(tr("Enable auto sync"), this); toggle_auto_sync_action_->setStatusTip(tr("Enable auto sync")); toggle_auto_sync_action_->setIconVisibleInMenu(true); connect(toggle_auto_sync_action_, SIGNAL(triggered()), this, SLOT(toggleRepoAutoSync())); view_on_web_action_ = new QAction(tr("&View on cloud"), this); view_on_web_action_->setIcon(QIcon(":/images/cloud.png")); view_on_web_action_->setStatusTip(tr("view this library on seahub")); view_on_web_action_->setIconVisibleInMenu(true); connect(view_on_web_action_, SIGNAL(triggered()), this, SLOT(viewRepoOnWeb())); } void RepoTreeView::downloadRepo() { ServerRepo repo = qvariant_cast<ServerRepo>(download_action_->data()); DownloadRepoDialog dialog(cloud_view_->currentAccount(), repo, this); updateRepoActions(); } void RepoTreeView::showRepoDetail() { ServerRepo repo = qvariant_cast<ServerRepo>(show_detail_action_->data()); RepoDetailDialog dialog(repo, this); dialog.exec(); } void RepoTreeView::openLocalFolder() { LocalRepo repo = qvariant_cast<LocalRepo>(open_local_folder_action_->data()); QDesktopServices::openUrl(QUrl::fromLocalFile(repo.worktree)); } void RepoTreeView::toggleRepoAutoSync() { LocalRepo repo = qvariant_cast<LocalRepo>(toggle_auto_sync_action_->data()); seafApplet->rpcClient()->setRepoAutoSync(repo.id, !repo.auto_sync); updateRepoActions(); } void RepoTreeView::unsyncRepo() { LocalRepo repo = qvariant_cast<LocalRepo>(toggle_auto_sync_action_->data()); QString question = tr("Are you sure to unsync library \"%1\"?").arg(repo.name); if (QMessageBox::question(this, tr(SEAFILE_CLIENT_BRAND), question, QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) != QMessageBox::Ok) { return; } if (seafApplet->rpcClient()->unsync(repo.id) < 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Failed to unsync library \"%1\"").arg(repo.name), QMessageBox::Ok); } updateRepoActions(); } void RepoTreeView::onItemClicked(const QModelIndex& index) { QStandardItem *item = getRepoItem(index); if (!item) { return; } if (item->type() == REPO_ITEM_TYPE) { return; } else { // A repo category item if (isExpanded(index)) { collapse(index); } else { expand(index); } } } void RepoTreeView::onItemDoubleClicked(const QModelIndex& index) { QStandardItem *item = getRepoItem(index); if (!item) { return; } if (item->type() == REPO_ITEM_TYPE) { RepoItem *it = (RepoItem *)item; const LocalRepo& local_repo = it->localRepo(); if (local_repo.isValid()) { QDesktopServices::openUrl(QUrl::fromLocalFile(local_repo.worktree)); } } } void RepoTreeView::viewRepoOnWeb() { QString repo_id = view_on_web_action_->data().toString(); const Account& account = cloud_view_->currentAccount(); if (account.isValid()) { QUrl url = account.serverUrl; url.setPath(url.path() + "/repo/" + repo_id); QDesktopServices::openUrl(url); } } bool RepoTreeView::viewportEvent(QEvent *event) { if (event->type() != QEvent::ToolTip && event->type() != QEvent::WhatsThis) { return QTreeView::viewportEvent(event); } QPoint global_pos = QCursor::pos(); QPoint viewport_pos = viewport()->mapFromGlobal(global_pos); QModelIndex index = indexAt(viewport_pos); if (!index.isValid()) { return true; } QStandardItem *item = getRepoItem(index); if (!item) { return true; } QRect item_rect = visualRect(index); if (item->type() == REPO_ITEM_TYPE) { showRepoItemToolTip((RepoItem *)item, global_pos, item_rect); } else { showRepoCategoryItemToolTip((RepoCategoryItem *)item, global_pos, item_rect); } return true; } void RepoTreeView::showRepoItemToolTip(const RepoItem *item, const QPoint& pos, const QRect& rect) { RepoItemDelegate *delegate = (RepoItemDelegate *)itemDelegate(); delegate->showRepoItemToolTip(item, pos, viewport(), rect); } void RepoTreeView::showRepoCategoryItemToolTip(const RepoCategoryItem *item, const QPoint& pos, const QRect& rect) { QToolTip::showText(pos, item->name(), viewport(), rect); // QToolTip::showText(pos, item->name()); } std::vector<QAction*> RepoTreeView::getToolBarActions() { std::vector<QAction*> actions; actions.push_back(download_action_); actions.push_back(open_local_folder_action_); actions.push_back(view_on_web_action_); actions.push_back(show_detail_action_); return actions; } void RepoTreeView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { updateRepoActions(); } void RepoTreeView::hideEvent(QHideEvent *event) { download_action_->setEnabled(false); open_local_folder_action_->setEnabled(false); unsync_action_->setEnabled(false); toggle_auto_sync_action_->setEnabled(false); view_on_web_action_->setEnabled(false); show_detail_action_->setEnabled(false); } void RepoTreeView::showEvent(QShowEvent *event) { updateRepoActions(); } void RepoTreeView::syncRepoImmediately() { LocalRepo repo = qvariant_cast<LocalRepo>(sync_now_action_->data()); seafApplet->rpcClient()->syncRepoImmediately(repo.id); } void RepoTreeView::cancelDownload() { ServerRepo repo = qvariant_cast<ServerRepo>(cancel_download_action_->data()); QString error; if (seafApplet->rpcClient()->cancelCloneTask(repo.id, &error) < 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Failed to cancel this task:\n\n %1").arg(error), QMessageBox::Ok); } else { QMessageBox::information(this, tr(SEAFILE_CLIENT_BRAND), tr("The download has been canceled"), QMessageBox::Ok); } } <commit_msg>fixed a bug<commit_after>#include <QtGui> #include <QHeaderView> #include <QDesktopServices> #include <QEvent> #include <QShowEvent> #include <QHideEvent> #include "QtAwesome.h" #include "utils/utils.h" #include "seafile-applet.h" #include "rpc/rpc-client.h" #include "rpc/local-repo.h" #include "download-repo-dialog.h" #include "clone-tasks-dialog.h" #include "cloud-view.h" #include "repo-item.h" #include "repo-item-delegate.h" #include "repo-tree-model.h" #include "repo-tree-view.h" #include "repo-detail-dialog.h" RepoTreeView::RepoTreeView(CloudView *cloud_view, QWidget *parent) : QTreeView(parent), cloud_view_(cloud_view) { header()->hide(); createActions(); // We draw the indicator ourselves setIndentation(0); // We handle the click oursevles setExpandsOnDoubleClick(false); connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(onItemClicked(const QModelIndex&))); connect(this, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(onItemDoubleClicked(const QModelIndex&))); } void RepoTreeView::contextMenuEvent(QContextMenuEvent *event) { QPoint pos = event->pos(); QModelIndex index = indexAt(pos); if (!index.isValid()) { // Not clicked at a repo item return; } QStandardItem *item = getRepoItem(index); if (!item || item->type() != REPO_ITEM_TYPE) { return; } updateRepoActions(); QMenu *menu = prepareContextMenu((RepoItem *)item); pos = viewport()->mapToGlobal(pos); menu->exec(pos); } QMenu* RepoTreeView::prepareContextMenu(const RepoItem *item) { QMenu *menu = new QMenu(this); if (item->localRepo().isValid()) { menu->addAction(open_local_folder_action_); } if (item->repoDownloadable()) { menu->addAction(download_action_); } menu->addAction(view_on_web_action_); if (item->localRepo().isValid()) { menu->addSeparator(); menu->addAction(toggle_auto_sync_action_); menu->addAction(sync_now_action_); menu->addSeparator(); } menu->addAction(show_detail_action_); if (item->cloneTask().isCancelable()) { menu->addAction(cancel_download_action_); } if (item->localRepo().isValid()) { menu->addAction(unsync_action_); } return menu; } void RepoTreeView::updateRepoActions() { RepoItem *item = NULL; QItemSelection selected = selectionModel()->selection(); QModelIndexList indexes = selected.indexes(); if (indexes.size() != 0) { const QModelIndex& index = indexes.at(0); QStandardItem *it = ((RepoTreeModel *)model())->itemFromIndex(index); if (it && it->type() == REPO_ITEM_TYPE) { item = (RepoItem *)it; } } if (!item) { // No repo item is selected download_action_->setEnabled(false); sync_now_action_->setEnabled(false); open_local_folder_action_->setEnabled(false); unsync_action_->setEnabled(false); toggle_auto_sync_action_->setEnabled(false); view_on_web_action_->setEnabled(false); show_detail_action_->setEnabled(false); return; } LocalRepo r; seafApplet->rpcClient()->getLocalRepo(item->repo().id, &r); item->setLocalRepo(r); if (item->localRepo().isValid()) { const LocalRepo& local_repo = item->localRepo(); download_action_->setEnabled(false); sync_now_action_->setEnabled(true); sync_now_action_->setData(QVariant::fromValue(local_repo)); open_local_folder_action_->setData(QVariant::fromValue(local_repo)); open_local_folder_action_->setEnabled(true); unsync_action_->setData(QVariant::fromValue(local_repo)); unsync_action_->setEnabled(true); toggle_auto_sync_action_->setData(QVariant::fromValue(local_repo)); toggle_auto_sync_action_->setEnabled(true); if (local_repo.auto_sync) { toggle_auto_sync_action_->setText(tr("Disable auto sync")); toggle_auto_sync_action_->setToolTip(tr("Disable auto sync")); toggle_auto_sync_action_->setIcon(QIcon(":/images/pause.png")); } else { toggle_auto_sync_action_->setText(tr("Enable auto sync")); toggle_auto_sync_action_->setToolTip(tr("Enable auto sync")); toggle_auto_sync_action_->setIcon(QIcon(":/images/play.png")); } } else { if (item->repoDownloadable()) { download_action_->setEnabled(true); download_action_->setData(QVariant::fromValue(item->repo())); } else { download_action_->setEnabled(false); } sync_now_action_->setEnabled(false); open_local_folder_action_->setEnabled(false); unsync_action_->setEnabled(false); toggle_auto_sync_action_->setEnabled(false); } view_on_web_action_->setEnabled(true); view_on_web_action_->setData(item->repo().id); show_detail_action_->setEnabled(true); show_detail_action_->setData(QVariant::fromValue(item->repo())); if (item->cloneTask().isCancelable()) { cancel_download_action_->setEnabled(true); cancel_download_action_->setData(QVariant::fromValue(item->repo())); } else { cancel_download_action_->setEnabled(false); } } QStandardItem* RepoTreeView::getRepoItem(const QModelIndex &index) const { if (!index.isValid()) { return NULL; } const RepoTreeModel *model = (const RepoTreeModel*)index.model(); QStandardItem *item = model->itemFromIndex(index); if (item->type() != REPO_ITEM_TYPE && item->type() != REPO_CATEGORY_TYPE) { return NULL; } return item; } void RepoTreeView::createActions() { show_detail_action_ = new QAction(tr("&Show details"), this); show_detail_action_->setIcon(QIcon(":/images/info.png")); show_detail_action_->setStatusTip(tr("Download this library")); show_detail_action_->setIconVisibleInMenu(true); connect(show_detail_action_, SIGNAL(triggered()), this, SLOT(showRepoDetail())); download_action_ = new QAction(tr("&Download this library"), this); download_action_->setIcon(QIcon(":/images/download.png")); download_action_->setStatusTip(tr("Download this library")); download_action_->setIconVisibleInMenu(true); connect(download_action_, SIGNAL(triggered()), this, SLOT(downloadRepo())); sync_now_action_ = new QAction(tr("&Sync now"), this); sync_now_action_->setIcon(QIcon(":/images/sync_now.png")); sync_now_action_->setStatusTip(tr("Sync this library immediately")); sync_now_action_->setIconVisibleInMenu(true); connect(sync_now_action_, SIGNAL(triggered()), this, SLOT(syncRepoImmediately())); cancel_download_action_ = new QAction(tr("&Cancel download"), this); cancel_download_action_->setIcon(QIcon(":/images/remove.png")); cancel_download_action_->setStatusTip(tr("Cancel download of this library")); cancel_download_action_->setIconVisibleInMenu(true); connect(cancel_download_action_, SIGNAL(triggered()), this, SLOT(cancelDownload())); open_local_folder_action_ = new QAction(tr("&Open folder"), this); open_local_folder_action_->setIcon(QIcon(":/images/folder-open.png")); open_local_folder_action_->setStatusTip(tr("open local folder")); open_local_folder_action_->setIconVisibleInMenu(true); connect(open_local_folder_action_, SIGNAL(triggered()), this, SLOT(openLocalFolder())); unsync_action_ = new QAction(tr("&Unsync"), this); unsync_action_->setStatusTip(tr("unsync this library")); unsync_action_->setIcon(QIcon(":/images/minus.png")); unsync_action_->setIconVisibleInMenu(true); connect(unsync_action_, SIGNAL(triggered()), this, SLOT(unsyncRepo())); toggle_auto_sync_action_ = new QAction(tr("Enable auto sync"), this); toggle_auto_sync_action_->setStatusTip(tr("Enable auto sync")); toggle_auto_sync_action_->setIconVisibleInMenu(true); connect(toggle_auto_sync_action_, SIGNAL(triggered()), this, SLOT(toggleRepoAutoSync())); view_on_web_action_ = new QAction(tr("&View on cloud"), this); view_on_web_action_->setIcon(QIcon(":/images/cloud.png")); view_on_web_action_->setStatusTip(tr("view this library on seahub")); view_on_web_action_->setIconVisibleInMenu(true); connect(view_on_web_action_, SIGNAL(triggered()), this, SLOT(viewRepoOnWeb())); } void RepoTreeView::downloadRepo() { ServerRepo repo = qvariant_cast<ServerRepo>(download_action_->data()); DownloadRepoDialog dialog(cloud_view_->currentAccount(), repo, this); dialog.exec(); updateRepoActions(); } void RepoTreeView::showRepoDetail() { ServerRepo repo = qvariant_cast<ServerRepo>(show_detail_action_->data()); RepoDetailDialog dialog(repo, this); dialog.exec(); } void RepoTreeView::openLocalFolder() { LocalRepo repo = qvariant_cast<LocalRepo>(open_local_folder_action_->data()); QDesktopServices::openUrl(QUrl::fromLocalFile(repo.worktree)); } void RepoTreeView::toggleRepoAutoSync() { LocalRepo repo = qvariant_cast<LocalRepo>(toggle_auto_sync_action_->data()); seafApplet->rpcClient()->setRepoAutoSync(repo.id, !repo.auto_sync); updateRepoActions(); } void RepoTreeView::unsyncRepo() { LocalRepo repo = qvariant_cast<LocalRepo>(toggle_auto_sync_action_->data()); QString question = tr("Are you sure to unsync library \"%1\"?").arg(repo.name); if (QMessageBox::question(this, tr(SEAFILE_CLIENT_BRAND), question, QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) != QMessageBox::Ok) { return; } if (seafApplet->rpcClient()->unsync(repo.id) < 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Failed to unsync library \"%1\"").arg(repo.name), QMessageBox::Ok); } updateRepoActions(); } void RepoTreeView::onItemClicked(const QModelIndex& index) { QStandardItem *item = getRepoItem(index); if (!item) { return; } if (item->type() == REPO_ITEM_TYPE) { return; } else { // A repo category item if (isExpanded(index)) { collapse(index); } else { expand(index); } } } void RepoTreeView::onItemDoubleClicked(const QModelIndex& index) { QStandardItem *item = getRepoItem(index); if (!item) { return; } if (item->type() == REPO_ITEM_TYPE) { RepoItem *it = (RepoItem *)item; const LocalRepo& local_repo = it->localRepo(); if (local_repo.isValid()) { QDesktopServices::openUrl(QUrl::fromLocalFile(local_repo.worktree)); } } } void RepoTreeView::viewRepoOnWeb() { QString repo_id = view_on_web_action_->data().toString(); const Account& account = cloud_view_->currentAccount(); if (account.isValid()) { QUrl url = account.serverUrl; url.setPath(url.path() + "/repo/" + repo_id); QDesktopServices::openUrl(url); } } bool RepoTreeView::viewportEvent(QEvent *event) { if (event->type() != QEvent::ToolTip && event->type() != QEvent::WhatsThis) { return QTreeView::viewportEvent(event); } QPoint global_pos = QCursor::pos(); QPoint viewport_pos = viewport()->mapFromGlobal(global_pos); QModelIndex index = indexAt(viewport_pos); if (!index.isValid()) { return true; } QStandardItem *item = getRepoItem(index); if (!item) { return true; } QRect item_rect = visualRect(index); if (item->type() == REPO_ITEM_TYPE) { showRepoItemToolTip((RepoItem *)item, global_pos, item_rect); } else { showRepoCategoryItemToolTip((RepoCategoryItem *)item, global_pos, item_rect); } return true; } void RepoTreeView::showRepoItemToolTip(const RepoItem *item, const QPoint& pos, const QRect& rect) { RepoItemDelegate *delegate = (RepoItemDelegate *)itemDelegate(); delegate->showRepoItemToolTip(item, pos, viewport(), rect); } void RepoTreeView::showRepoCategoryItemToolTip(const RepoCategoryItem *item, const QPoint& pos, const QRect& rect) { QToolTip::showText(pos, item->name(), viewport(), rect); // QToolTip::showText(pos, item->name()); } std::vector<QAction*> RepoTreeView::getToolBarActions() { std::vector<QAction*> actions; actions.push_back(download_action_); actions.push_back(open_local_folder_action_); actions.push_back(view_on_web_action_); actions.push_back(show_detail_action_); return actions; } void RepoTreeView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { updateRepoActions(); } void RepoTreeView::hideEvent(QHideEvent *event) { download_action_->setEnabled(false); open_local_folder_action_->setEnabled(false); unsync_action_->setEnabled(false); toggle_auto_sync_action_->setEnabled(false); view_on_web_action_->setEnabled(false); show_detail_action_->setEnabled(false); } void RepoTreeView::showEvent(QShowEvent *event) { updateRepoActions(); } void RepoTreeView::syncRepoImmediately() { LocalRepo repo = qvariant_cast<LocalRepo>(sync_now_action_->data()); seafApplet->rpcClient()->syncRepoImmediately(repo.id); } void RepoTreeView::cancelDownload() { ServerRepo repo = qvariant_cast<ServerRepo>(cancel_download_action_->data()); QString error; if (seafApplet->rpcClient()->cancelCloneTask(repo.id, &error) < 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Failed to cancel this task:\n\n %1").arg(error), QMessageBox::Ok); } else { QMessageBox::information(this, tr(SEAFILE_CLIENT_BRAND), tr("The download has been canceled"), QMessageBox::Ok); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2010-2015 Max Kellermann <max@duempel.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TRIVIAL_ARRAY_HXX #define TRIVIAL_ARRAY_HXX #include <array> #include <algorithm> #include <assert.h> /** * An array with a maximum size known at compile time. It keeps track * of the actual length at runtime. The clear() function needs to be * called to initialize the class properly. */ template<class T, unsigned max> class TrivialArray { typedef std::array<T, max> Array; public: typedef unsigned size_type; typedef T value_type; typedef typename Array::iterator iterator; typedef typename Array::const_iterator const_iterator; protected: size_type the_size; Array data; constexpr TrivialArray(size_type _size):the_size(_size) {} public: /** * Non-initialising constructor. */ TrivialArray() = default; TrivialArray(size_type _size, const T &value):the_size(_size) { std::fill(begin(), end(), value); } /** * Initialise the array with values from the iterator range. */ template<typename I> TrivialArray(I _begin, I _end):the_size(0) { for (I i = _begin; i != _end; ++i) push_back(*i); } constexpr size_type capacity() const { return max; } constexpr size_type max_size() const { return max; } /** * Forcibly set the specified size, without initialising or * freeing new/excess elements. */ void resize(size_type new_size) { assert(new_size <= max_size()); the_size = new_size; } /** * Returns the number of allocated elements. */ constexpr size_type size() const { return the_size; } void shrink(size_type _size) { assert(_size <= the_size); the_size = _size; } constexpr bool empty() const { return the_size == 0; } constexpr bool full() const { return the_size == max; } /** * Empties this array, but does not destruct its elements. */ void clear() { the_size = 0; } /** * Returns one element. No bounds checking. */ T &operator[](size_type i) { assert(i < size()); return data[i]; } /** * Returns one constant element. No bounds checking. */ const T &operator[](size_type i) const { assert(i < size()); return data[i]; } iterator begin() { return data.begin(); } constexpr const_iterator begin() const { return data.begin(); } iterator end() { return std::next(data.begin(), the_size); } constexpr const_iterator end() const { return std::next(data.begin(), the_size); } T &last() { assert(the_size > 0); return data[the_size - 1]; } const T &last() const { assert(the_size > 0); return data[the_size - 1]; } bool contains(const T &value) const { return std::find(begin(), end(), value) != end(); } /** * Return address of start of data segment. */ const T* raw() const { return &data[0]; } /** * Append an element at the end of the array, increasing the * length by one. No bounds checking. */ void append(const T &value) { assert(!full()); data[the_size++] = value; } /** * Increase the length by one and return a pointer to the new * element, to be modified by the caller. No bounds checking. */ T &append() { assert(!full()); return data[the_size++]; } /** * Like append(), but checks if the array is already full * (returns false in this case). */ bool checked_append(const T &value) { if (full()) return false; append(value); return true; } /** * Remove the item at the given index. */ void remove(size_type i) { assert(i < size()); std::move(std::next(data.begin(), i + 1), std::next(data.begin(), size()), std::next(data.begin(), i)); --the_size; } /** * Remove an item by copying the last item over it. */ void quick_remove(size_type i) { assert(i < size()); if (i < size() - 1) data[i] = std::move(data[size() - 1]); --the_size; } /* STL API emulation */ void push_back(const T &value) { append(value); } T &front() { assert(the_size > 0); return data.front(); } const T &front() const { assert(the_size > 0); return data.front(); } T &back() { return last(); } const T &back() const { return last(); } }; #endif <commit_msg>util/TrivialArray: add method insert()<commit_after>/* * Copyright (C) 2010-2015 Max Kellermann <max@duempel.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TRIVIAL_ARRAY_HXX #define TRIVIAL_ARRAY_HXX #include <array> #include <algorithm> #include <assert.h> /** * An array with a maximum size known at compile time. It keeps track * of the actual length at runtime. The clear() function needs to be * called to initialize the class properly. */ template<class T, unsigned max> class TrivialArray { typedef std::array<T, max> Array; public: typedef unsigned size_type; typedef T value_type; typedef typename Array::iterator iterator; typedef typename Array::const_iterator const_iterator; protected: size_type the_size; Array data; constexpr TrivialArray(size_type _size):the_size(_size) {} public: /** * Non-initialising constructor. */ TrivialArray() = default; TrivialArray(size_type _size, const T &value):the_size(_size) { std::fill(begin(), end(), value); } /** * Initialise the array with values from the iterator range. */ template<typename I> TrivialArray(I _begin, I _end):the_size(0) { for (I i = _begin; i != _end; ++i) push_back(*i); } constexpr size_type capacity() const { return max; } constexpr size_type max_size() const { return max; } /** * Forcibly set the specified size, without initialising or * freeing new/excess elements. */ void resize(size_type new_size) { assert(new_size <= max_size()); the_size = new_size; } /** * Returns the number of allocated elements. */ constexpr size_type size() const { return the_size; } void shrink(size_type _size) { assert(_size <= the_size); the_size = _size; } constexpr bool empty() const { return the_size == 0; } constexpr bool full() const { return the_size == max; } /** * Empties this array, but does not destruct its elements. */ void clear() { the_size = 0; } /** * Returns one element. No bounds checking. */ T &operator[](size_type i) { assert(i < size()); return data[i]; } /** * Returns one constant element. No bounds checking. */ const T &operator[](size_type i) const { assert(i < size()); return data[i]; } iterator begin() { return data.begin(); } constexpr const_iterator begin() const { return data.begin(); } iterator end() { return std::next(data.begin(), the_size); } constexpr const_iterator end() const { return std::next(data.begin(), the_size); } T &last() { assert(the_size > 0); return data[the_size - 1]; } const T &last() const { assert(the_size > 0); return data[the_size - 1]; } bool contains(const T &value) const { return std::find(begin(), end(), value) != end(); } /** * Return address of start of data segment. */ const T* raw() const { return &data[0]; } /** * Append an element at the end of the array, increasing the * length by one. No bounds checking. */ void append(const T &value) { assert(!full()); data[the_size++] = value; } /** * Increase the length by one and return a pointer to the new * element, to be modified by the caller. No bounds checking. */ T &append() { assert(!full()); return data[the_size++]; } /** * Like append(), but checks if the array is already full * (returns false in this case). */ bool checked_append(const T &value) { if (full()) return false; append(value); return true; } /** * Remove the item at the given index. */ void remove(size_type i) { assert(i < size()); std::move(std::next(data.begin(), i + 1), std::next(data.begin(), size()), std::next(data.begin(), i)); --the_size; } /** * Remove an item by copying the last item over it. */ void quick_remove(size_type i) { assert(i < size()); if (i < size() - 1) data[i] = std::move(data[size() - 1]); --the_size; } template<typename I> void insert(size_type i, I _begin, I _end) { size_type n = std::distance(_begin, _end); assert(the_size + n < capacity()); auto dest_begin = std::next(begin(), i); auto dest_end = end(); the_size += n; std::move_backward(dest_begin, dest_end, end()); std::copy(_begin, _end, dest_begin); } /* STL API emulation */ void push_back(const T &value) { append(value); } T &front() { assert(the_size > 0); return data.front(); } const T &front() const { assert(the_size > 0); return data.front(); } T &back() { return last(); } const T &back() const { return last(); } }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: tabvwsh.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: nn $ $Date: 2000-09-22 18:28:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #if !defined OS2 && !defined WNT //#define _BUTTON_HXX #endif #define _SETBRW_HXX #define _STACK_HXX //#define _STATUS_HXX #define _STDMENU_HXX #define _TABBAR_HXX #define _VCBRW_HXX #define _VCTRLS_HXX #define _VCSBX_HXX #define _VCONT_HXX #define _VDRWOBJ_HXX #define _BASE_DLGS_HXX #define _BIGINT_HXX #define _CACHESTR_HXX #define _CONFIG_HXX #define _CURSOR_HXX #define _CTRLTOOL_HXX #define _DLGCFG_HXX #define _DYNARR_HXX #define _EXTATTR_HXX #define _FILDLG_HXX #define _FONTDLG_HXX #define _FRM3D_HXX #define _INTRO_HXX #define _ISETBWR_HXX #define _NO_SVRTF_PARSER_HXX #define _MACRODLG_HXX #define _MODALDLG_HXX #define _MOREBUTTON_HXX #define _OUTLINER_HXX #define _PASSWD_HXX //#define _PRNDLG_HXX //#define _POLY_HXX #define _PVRWIN_HXX #define _QUEUE_HXX #define _RULER_HXX #define _SCRWIN_HXX #define _STACK_HXX #define _SETBRW_HXX #define _STACK_HXX //#define _STATUS_HXX #define _STDMENU_HXX #define _TABBAR_HXX #define _VCBRW_HXX #define _VCTRLS_HXX #define _VCSBX_HXX #define _VCONT_HXX #define _VDRWOBJ_HXX #define _SVDXOUT_HXX #define _SVDATTR_HXX #define _SVDETC_HXX #define _SVDIO_HXX #define _SVDRAG_HXX #define _SVDLAYER_HXX #define _SFXFILEDLG_HXX #define _SFX_MACRO_HXX #define _SFXMNUITEM_HXX #define _SFXMNUMGR_HXX #define _SFXMSGPOOL_HXX #define _SFXMULTISEL_HXX #define _SFXBASIC_HXX #define _SFXSTBMGR_HXX //#define _SFXTBXCTRL_HXX //#define _SFXTBXMGR_HXX //#define _SFXIMGMGR_HXX #define _SI_DLL_HXX #define _SIDLL_HXX #define _SI_NOITEMS #define _SI_NOOTHERFORMS #define _SI_NOSBXCONTROLS #define _SINOSBXCONTROLS #define _SI_NODRW #define _SI_NOCONTROL #define _SVX_DAILDLL_HXX #define _SVX_HYPHEN_HXX #define _SVX_IMPGRF_HXX #define _SVX_OPTITEMS_HXX #define _SVX_OPTGERL_HXX #define _SVX_OPTSAVE_HXX #define _SVX_OPTSPELL_HXX #define _SVX_OPTPATH_HXX #define _SVX_OPTLINGU_HXX #define _SVX_RULER_HXX #define _SVX_RULRITEM_HXX #define _SVX_SPLWRAP_HXX #define _SVX_SPLDLG_HXX #define _SVX_THESDLG_HXX // INCLUDE --------------------------------------------------------------- #include "scitems.hxx" #include <basctl/idetemp.hxx> #include <svx/imapdlg.hxx> #include <svx/srchitem.hxx> #include <offmgr/sbasltid.hrc> #include <sfx2/templdlg.hxx> #include "tabvwsh.hxx" #include "docsh.hxx" #include "reffact.hxx" #include "scresid.hxx" #include "dwfunctr.hxx" #include "sc.hrc" // -> SID_TOOL_xxx #include "drawattr.hxx" // -> SvxDrawToolItem #define ScTabViewShell #include "scslots.hxx" #define SearchSettings #include <svx/svxslots.hxx> TYPEINIT2(ScTabViewShell,SfxViewShell,SfxListener); SFX_IMPL_INTERFACE(ScTabViewShell,SfxViewShell,ScResId(SCSTR_TABVIEWSHELL)) { SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER, ScResId(RID_OBJECTBAR_TOOLS) ); SFX_CHILDWINDOW_REGISTRATION(FID_INPUTLINE_STATUS); SFX_CHILDWINDOW_REGISTRATION(SfxTemplateDialogWrapper::GetChildWindowId()); SFX_CHILDWINDOW_CONTEXT_REGISTRATION(SID_NAVIGATOR); SFX_CHILDWINDOW_REGISTRATION(ScNameDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSolverDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScPivotLayoutWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScTabOpDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFilterDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSpecialFilterDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScDbNameDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScConsolidateDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScChartDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScPrintAreasDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScCondFormatDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScColRowNameRangesDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(SvxIMapDlgChildWindow::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFunctionChildWindow::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScAcceptChgDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScHighlightChgDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSimpleRefDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(SID_SEARCH_DLG); SFX_CHILDWINDOW_REGISTRATION(SID_HYPERLINK_DIALOG); } SFX_IMPL_VIEWFACTORY( ScTabViewShell, ScResId(STR_NONAME) ) { SFX_VIEW_REGISTRATION(ScDocShell); } //------------------------------------------------------------------ <commit_msg>old include removed<commit_after>/************************************************************************* * * $RCSfile: tabvwsh.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: nn $ $Date: 2000-10-19 18:36:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #if !defined OS2 && !defined WNT //#define _BUTTON_HXX #endif #define _SETBRW_HXX #define _STACK_HXX //#define _STATUS_HXX #define _STDMENU_HXX #define _TABBAR_HXX #define _VCBRW_HXX #define _VCTRLS_HXX #define _VCSBX_HXX #define _VCONT_HXX #define _VDRWOBJ_HXX #define _BASE_DLGS_HXX #define _BIGINT_HXX #define _CACHESTR_HXX #define _CONFIG_HXX #define _CURSOR_HXX #define _CTRLTOOL_HXX #define _DLGCFG_HXX #define _DYNARR_HXX #define _EXTATTR_HXX #define _FILDLG_HXX #define _FONTDLG_HXX #define _FRM3D_HXX #define _INTRO_HXX #define _ISETBWR_HXX #define _NO_SVRTF_PARSER_HXX #define _MACRODLG_HXX #define _MODALDLG_HXX #define _MOREBUTTON_HXX #define _OUTLINER_HXX #define _PASSWD_HXX //#define _PRNDLG_HXX //#define _POLY_HXX #define _PVRWIN_HXX #define _QUEUE_HXX #define _RULER_HXX #define _SCRWIN_HXX #define _STACK_HXX #define _SETBRW_HXX #define _STACK_HXX //#define _STATUS_HXX #define _STDMENU_HXX #define _TABBAR_HXX #define _VCBRW_HXX #define _VCTRLS_HXX #define _VCSBX_HXX #define _VCONT_HXX #define _VDRWOBJ_HXX #define _SVDXOUT_HXX #define _SVDATTR_HXX #define _SVDETC_HXX #define _SVDIO_HXX #define _SVDRAG_HXX #define _SVDLAYER_HXX #define _SFXFILEDLG_HXX #define _SFX_MACRO_HXX #define _SFXMNUITEM_HXX #define _SFXMNUMGR_HXX #define _SFXMSGPOOL_HXX #define _SFXMULTISEL_HXX #define _SFXBASIC_HXX #define _SFXSTBMGR_HXX //#define _SFXTBXCTRL_HXX //#define _SFXTBXMGR_HXX //#define _SFXIMGMGR_HXX #define _SI_DLL_HXX #define _SIDLL_HXX #define _SI_NOITEMS #define _SI_NOOTHERFORMS #define _SI_NOSBXCONTROLS #define _SINOSBXCONTROLS #define _SI_NODRW #define _SI_NOCONTROL #define _SVX_DAILDLL_HXX #define _SVX_HYPHEN_HXX #define _SVX_IMPGRF_HXX #define _SVX_OPTITEMS_HXX #define _SVX_OPTGERL_HXX #define _SVX_OPTSAVE_HXX #define _SVX_OPTSPELL_HXX #define _SVX_OPTPATH_HXX #define _SVX_OPTLINGU_HXX #define _SVX_RULER_HXX #define _SVX_RULRITEM_HXX #define _SVX_SPLWRAP_HXX #define _SVX_SPLDLG_HXX #define _SVX_THESDLG_HXX // INCLUDE --------------------------------------------------------------- #include "scitems.hxx" #include <svx/imapdlg.hxx> #include <svx/srchitem.hxx> #include <offmgr/sbasltid.hrc> #include <sfx2/templdlg.hxx> #include "tabvwsh.hxx" #include "docsh.hxx" #include "reffact.hxx" #include "scresid.hxx" #include "dwfunctr.hxx" #include "sc.hrc" // -> SID_TOOL_xxx #include "drawattr.hxx" // -> SvxDrawToolItem #define ScTabViewShell #include "scslots.hxx" #define SearchSettings #include <svx/svxslots.hxx> TYPEINIT2(ScTabViewShell,SfxViewShell,SfxListener); SFX_IMPL_INTERFACE(ScTabViewShell,SfxViewShell,ScResId(SCSTR_TABVIEWSHELL)) { SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER, ScResId(RID_OBJECTBAR_TOOLS) ); SFX_CHILDWINDOW_REGISTRATION(FID_INPUTLINE_STATUS); SFX_CHILDWINDOW_REGISTRATION(SfxTemplateDialogWrapper::GetChildWindowId()); SFX_CHILDWINDOW_CONTEXT_REGISTRATION(SID_NAVIGATOR); SFX_CHILDWINDOW_REGISTRATION(ScNameDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSolverDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScPivotLayoutWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScTabOpDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFilterDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSpecialFilterDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScDbNameDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScConsolidateDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScChartDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScPrintAreasDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScCondFormatDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScColRowNameRangesDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(SvxIMapDlgChildWindow::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFunctionChildWindow::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScAcceptChgDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScHighlightChgDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSimpleRefDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(SID_SEARCH_DLG); SFX_CHILDWINDOW_REGISTRATION(SID_HYPERLINK_DIALOG); } SFX_IMPL_VIEWFACTORY( ScTabViewShell, ScResId(STR_NONAME) ) { SFX_VIEW_REGISTRATION(ScDocShell); } //------------------------------------------------------------------ <|endoftext|>
<commit_before>/* Copyright (c) 2011 <chrigi_1@fastmail.fm> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "note.h" #include <Akonadi/EntityDisplayAttribute> #include <akonadi/notes/noteutils.h> #include <KMime/Message> Note::Note(QObject *parent) : AbstractPimItem(parent) { //init payload, mimetype, and displayattribute commitData(); } /* Note::Note(const Note &note) : AbstractPimItem(note.getItem()) { m_text = note.m_text; m_title = note.m_title; m_creationDate = note.m_creationDate; }*/ Note::Note(const Akonadi::Item &item, QObject *parent) : AbstractPimItem(item, parent) { fetchData(); } Note::Note(AbstractPimItem &item, QObject* parent) : AbstractPimItem(item, parent) { commitData(); } bool Note::hasValidPayload() { if (m_item.hasPayload<KMime::Message::Ptr>()) { return true; } return false; } void Note::commitData() { m_item.setMimeType(Akonadi::NoteUtils::noteMimeType()); Akonadi::NoteUtils::NoteMessageWrapper messageWrapper; messageWrapper.setTitle(m_title); messageWrapper.setText(m_text, m_textIsRich ? Qt::RichText : Qt::PlainText); messageWrapper.setCreationDate(m_creationDate); messageWrapper.setFrom(QString::fromLatin1( "NoteTaker@kde4" )); //FIXME shouldn't be hardcoded m_item.setPayload(messageWrapper.message()); Akonadi::EntityDisplayAttribute *eda = new Akonadi::EntityDisplayAttribute(); eda->setIconName(getIconName()); eda->setDisplayName(m_title); m_item.addAttribute(eda); } void Note::fetchData() { if (m_dataFetched) { return; } if ( !hasValidPayload()) { kDebug() << "invalid payload"; return; } KMime::Message::Ptr msg = m_item.payload<KMime::Message::Ptr>(); Q_ASSERT(msg.get()); Akonadi::NoteUtils::NoteMessageWrapper messageWrapper(msg); m_textIsRich = messageWrapper.textFormat() == Qt::RichText; m_titleIsRich = false; m_title = messageWrapper.title(); m_text = messageWrapper.text(); m_creationDate = messageWrapper.creationDate(); m_dataFetched = true; } QString Note::mimeType() { Q_ASSERT(AbstractPimItem::mimeType(AbstractPimItem::Note) == Akonadi::NoteUtils::noteMimeType()); return AbstractPimItem::mimeType(AbstractPimItem::Note); } AbstractPimItem::ItemStatus Note::getStatus() const { return AbstractPimItem::Later; } KDateTime Note::getPrimaryDate() { return getLastModifiedDate(); } QString Note::getIconName() { return Akonadi::NoteUtils::noteIconName(); } AbstractPimItem::ItemType Note::itemType() { return AbstractPimItem::Note; } <commit_msg>set correct application name<commit_after>/* Copyright (c) 2011 <chrigi_1@fastmail.fm> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "note.h" #include <Akonadi/EntityDisplayAttribute> #include <akonadi/notes/noteutils.h> #include <KMime/Message> #include <QCoreApplication> Note::Note(QObject *parent) : AbstractPimItem(parent) { //init payload, mimetype, and displayattribute commitData(); } /* Note::Note(const Note &note) : AbstractPimItem(note.getItem()) { m_text = note.m_text; m_title = note.m_title; m_creationDate = note.m_creationDate; }*/ Note::Note(const Akonadi::Item &item, QObject *parent) : AbstractPimItem(item, parent) { fetchData(); } Note::Note(AbstractPimItem &item, QObject* parent) : AbstractPimItem(item, parent) { commitData(); } bool Note::hasValidPayload() { if (m_item.hasPayload<KMime::Message::Ptr>()) { return true; } return false; } void Note::commitData() { m_item.setMimeType(Akonadi::NoteUtils::noteMimeType()); Akonadi::NoteUtils::NoteMessageWrapper messageWrapper; messageWrapper.setTitle(m_title); messageWrapper.setText(m_text, m_textIsRich ? Qt::RichText : Qt::PlainText); messageWrapper.setCreationDate(m_creationDate); messageWrapper.setFrom(QCoreApplication::applicationName()+QCoreApplication::applicationVersion()); m_item.setPayload(messageWrapper.message()); Akonadi::EntityDisplayAttribute *eda = new Akonadi::EntityDisplayAttribute(); eda->setIconName(getIconName()); eda->setDisplayName(m_title); m_item.addAttribute(eda); } void Note::fetchData() { if (m_dataFetched) { return; } if ( !hasValidPayload()) { kDebug() << "invalid payload"; return; } KMime::Message::Ptr msg = m_item.payload<KMime::Message::Ptr>(); Q_ASSERT(msg.get()); Akonadi::NoteUtils::NoteMessageWrapper messageWrapper(msg); m_textIsRich = messageWrapper.textFormat() == Qt::RichText; m_titleIsRich = false; m_title = messageWrapper.title(); m_text = messageWrapper.text(); m_creationDate = messageWrapper.creationDate(); m_dataFetched = true; } QString Note::mimeType() { Q_ASSERT(AbstractPimItem::mimeType(AbstractPimItem::Note) == Akonadi::NoteUtils::noteMimeType()); return AbstractPimItem::mimeType(AbstractPimItem::Note); } AbstractPimItem::ItemStatus Note::getStatus() const { return AbstractPimItem::Later; } KDateTime Note::getPrimaryDate() { return getLastModifiedDate(); } QString Note::getIconName() { return Akonadi::NoteUtils::noteIconName(); } AbstractPimItem::ItemType Note::itemType() { return AbstractPimItem::Note; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. 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 "modules/prediction/prediction.h" #include <cmath> #include "modules/common/adapters/adapter_manager.h" #include "modules/common/time/time.h" #include "modules/common/util/file.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/container/pose/pose_container.h" #include "modules/prediction/evaluator/evaluator_manager.h" #include "modules/prediction/predictor/predictor_manager.h" #include "modules/prediction/proto/prediction_obstacle.pb.h" namespace apollo { namespace prediction { using ::apollo::common::ErrorCode; using ::apollo::common::Status; using ::apollo::common::TrajectoryPoint; using ::apollo::common::adapter::AdapterConfig; using ::apollo::common::adapter::AdapterManager; using ::apollo::common::time::Clock; using ::apollo::localization::LocalizationEstimate; using ::apollo::perception::PerceptionObstacle; using ::apollo::perception::PerceptionObstacles; std::string Prediction::Name() const { return FLAGS_prediction_module_name; } Status Prediction::Init() { // Load prediction conf prediction_conf_.Clear(); if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file, &prediction_conf_)) { return OnError("Unable to load prediction conf file: " + FLAGS_prediction_conf_file); } else { ADEBUG << "Prediction config file is loaded into: " << prediction_conf_.ShortDebugString(); } adapter_conf_.Clear(); if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename, &adapter_conf_)) { return OnError("Unable to load adapter conf file: " + FLAGS_prediction_adapter_config_filename); } else { ADEBUG << "Adapter config file is loaded into: " << adapter_conf_.ShortDebugString(); } // Initialization of all managers AdapterManager::Init(adapter_conf_); ContainerManager::instance()->Init(adapter_conf_); EvaluatorManager::instance()->Init(prediction_conf_); PredictorManager::instance()->Init(prediction_conf_); CHECK(AdapterManager::GetLocalization()) << "Localization is not ready."; CHECK(AdapterManager::GetPerceptionObstacles()) << "Perception is not ready."; // Set perception obstacle callback function AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this); // Set localization callback function AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this); return Status::OK(); } Status Prediction::Start() { return Status::OK(); } void Prediction::Stop() {} void Prediction::OnLocalization(const LocalizationEstimate& localization) { ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>( ContainerManager::instance()->GetContainer( AdapterConfig::PERCEPTION_OBSTACLES)); CHECK_NOTNULL(obstacles_container); PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION)); CHECK_NOTNULL(pose_container); pose_container->Insert(localization); PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle(); if (pose_ptr != nullptr) { obstacles_container->InsertPerceptionObstacle( *(pose_ptr), pose_container->GetTimestamp()); } else { ADEBUG << "Invalid pose found."; } ADEBUG << "Received a localization message [" << localization.ShortDebugString() << "]."; } void Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) { ADEBUG << "Received a perception message [" << perception_obstacles.ShortDebugString() << "]."; double start_timestamp = Clock::NowInSecond(); ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>( ContainerManager::instance()->GetContainer( AdapterConfig::PERCEPTION_OBSTACLES)); CHECK_NOTNULL(obstacles_container); obstacles_container->Insert(perception_obstacles); EvaluatorManager::instance()->Run(perception_obstacles); PredictorManager::instance()->Run(perception_obstacles); auto prediction_obstacles = PredictorManager::instance()->prediction_obstacles(); prediction_obstacles.set_start_timestamp(start_timestamp); prediction_obstacles.set_end_timestamp(Clock::NowInSecond()); Publish(&prediction_obstacles); } Status Prediction::OnError(const std::string& error_msg) { return Status(ErrorCode::PREDICTION_ERROR, error_msg); } bool Prediction::IsValidTrajectoryPoint( const TrajectoryPoint& trajectory_point) { return (!std::isnan(trajectory_point.path_point().x())) && (!std::isnan(trajectory_point.path_point().y())) && (!std::isnan(trajectory_point.path_point().theta())) && (!std::isnan(trajectory_point.v())) && (!std::isnan(trajectory_point.a())) && (!std::isnan(trajectory_point.relative_time())); } } // namespace prediction } // namespace apollo <commit_msg>Prediction: added back trajectory point check<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. 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 "modules/prediction/prediction.h" #include <cmath> #include "modules/common/adapters/adapter_manager.h" #include "modules/common/time/time.h" #include "modules/common/util/file.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/container/pose/pose_container.h" #include "modules/prediction/evaluator/evaluator_manager.h" #include "modules/prediction/predictor/predictor_manager.h" #include "modules/prediction/proto/prediction_obstacle.pb.h" namespace apollo { namespace prediction { using ::apollo::common::ErrorCode; using ::apollo::common::Status; using ::apollo::common::TrajectoryPoint; using ::apollo::common::adapter::AdapterConfig; using ::apollo::common::adapter::AdapterManager; using ::apollo::common::time::Clock; using ::apollo::localization::LocalizationEstimate; using ::apollo::perception::PerceptionObstacle; using ::apollo::perception::PerceptionObstacles; std::string Prediction::Name() const { return FLAGS_prediction_module_name; } Status Prediction::Init() { // Load prediction conf prediction_conf_.Clear(); if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file, &prediction_conf_)) { return OnError("Unable to load prediction conf file: " + FLAGS_prediction_conf_file); } else { ADEBUG << "Prediction config file is loaded into: " << prediction_conf_.ShortDebugString(); } adapter_conf_.Clear(); if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename, &adapter_conf_)) { return OnError("Unable to load adapter conf file: " + FLAGS_prediction_adapter_config_filename); } else { ADEBUG << "Adapter config file is loaded into: " << adapter_conf_.ShortDebugString(); } // Initialization of all managers AdapterManager::Init(adapter_conf_); ContainerManager::instance()->Init(adapter_conf_); EvaluatorManager::instance()->Init(prediction_conf_); PredictorManager::instance()->Init(prediction_conf_); CHECK(AdapterManager::GetLocalization()) << "Localization is not ready."; CHECK(AdapterManager::GetPerceptionObstacles()) << "Perception is not ready."; // Set perception obstacle callback function AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this); // Set localization callback function AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this); return Status::OK(); } Status Prediction::Start() { return Status::OK(); } void Prediction::Stop() {} void Prediction::OnLocalization(const LocalizationEstimate& localization) { ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>( ContainerManager::instance()->GetContainer( AdapterConfig::PERCEPTION_OBSTACLES)); CHECK_NOTNULL(obstacles_container); PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION)); CHECK_NOTNULL(pose_container); pose_container->Insert(localization); PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle(); if (pose_ptr != nullptr) { obstacles_container->InsertPerceptionObstacle( *(pose_ptr), pose_container->GetTimestamp()); } else { ADEBUG << "Invalid pose found."; } ADEBUG << "Received a localization message [" << localization.ShortDebugString() << "]."; } void Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) { ADEBUG << "Received a perception message [" << perception_obstacles.ShortDebugString() << "]."; double start_timestamp = Clock::NowInSecond(); ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>( ContainerManager::instance()->GetContainer( AdapterConfig::PERCEPTION_OBSTACLES)); CHECK_NOTNULL(obstacles_container); obstacles_container->Insert(perception_obstacles); EvaluatorManager::instance()->Run(perception_obstacles); PredictorManager::instance()->Run(perception_obstacles); auto prediction_obstacles = PredictorManager::instance()->prediction_obstacles(); prediction_obstacles.set_start_timestamp(start_timestamp); prediction_obstacles.set_end_timestamp(Clock::NowInSecond()); Publish(&prediction_obstacles); for (auto const& prediction_obstacle : prediction_obstacles.prediction_obstacle()) { for (auto const& trajectory : prediction_obstacle.trajectory()) { for (auto const& trajectory_point : trajectory.trajectory_point()) { CHECK(IsValidTrajectoryPoint(trajectory_point)); } } } ADEBUG << "Received a perception message [" << perception_obstacles.ShortDebugString() << "]."; ADEBUG << "Published a prediction message [" << prediction_obstacles.ShortDebugString() << "]."; } Status Prediction::OnError(const std::string& error_msg) { return Status(ErrorCode::PREDICTION_ERROR, error_msg); } bool Prediction::IsValidTrajectoryPoint( const TrajectoryPoint& trajectory_point) { return trajectory_point.has_path_point() && (!std::isnan(trajectory_point.path_point().x())) && (!std::isnan(trajectory_point.path_point().y())) && (!std::isnan(trajectory_point.path_point().theta())) && (!std::isnan(trajectory_point.v())) && (!std::isnan(trajectory_point.a())) && (!std::isnan(trajectory_point.relative_time())); } } // namespace prediction } // namespace apollo <|endoftext|>
<commit_before>/* * webrtc-echo - A WebRTC echo server * Copyright (C) 2014 Stephan Thamm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "srtp.h" #include <node_buffer.h> #include "helper.h" using namespace v8; v8::Persistent<v8::Function> Srtp::constructor; bool Srtp::initialized = false; static void createSession(srtp_t *session, const char *key, ssrc_type_t direction) { srtp_policy_t policy; memset(&policy, 0, sizeof(policy)); crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp); crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp); policy.ssrc.type = direction; policy.ssrc.value = 0; policy.key = (unsigned char*) key; policy.next = NULL; int res = srtp_create(session, &policy); DEBUG("creating session " << res); } Srtp::Srtp(const char *sendKey, const char *recvKey) { if(!initialized) { DEBUG("initializing srtp"); srtp_init(); initialized = true; } createSession(&_sendSession, sendKey, ssrc_any_outbound); createSession(&_recvSession, recvKey, ssrc_any_inbound); } Srtp::~Srtp() { srtp_dealloc(_sendSession); srtp_dealloc(_recvSession); } void Srtp::init(v8::Handle<v8::Object> exports) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("Srtp")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // protoype NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtp", protectRtp); NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtp", unprotectRtp); NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtcp", protectRtcp); NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtcp", unprotectRtcp); constructor = Persistent<Function>::New(tpl->GetFunction()); // export exports->Set(String::NewSymbol("Srtp"), constructor); } v8::Handle<v8::Value> Srtp::New(const v8::Arguments& args) { HandleScope scope; if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` if(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) { return ThrowException(Exception::TypeError(String::New("Expected buffers"))); } const char *sendKey = node::Buffer::Data(args[0]); const char *recvKey = node::Buffer::Data(args[1]); Srtp* obj = new Srtp(sendKey, recvKey); obj->Wrap(args.This()); return args.This(); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local<Value> argv[1] = { argv[0] }; return scope.Close(constructor->NewInstance(argc, argv)); } } v8::Handle<v8::Value> Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) { HandleScope scope; // type checking if(!node::Buffer::HasInstance(args[0])) { return ThrowException(Exception::TypeError(String::New("Expected buffer"))); } // copy buffer for result int size = node::Buffer::Length(args[0]); char *in_buf = node::Buffer::Data(args[0]); Handle<Object> tmp = node::Buffer::New(size + 32)->handle_; char *out_buf = node::Buffer::Data(tmp); memcpy(out_buf, in_buf, size); // actual crypt stuff err_status_t err = fun(session, out_buf, &size); if(err != err_status_ok) { DEBUG("srtp error " << err); } // return slice of the right size Handle<Value> slice_v = tmp->Get(String::New("slice")); if(!slice_v->IsFunction()) { return ThrowException(Exception::Error(String::New("Buffer does not have a slice function"))); } Handle<v8::Function> slice_f = v8::Handle<v8::Function>::Cast(slice_v); const int argc = 2; Handle<Value> argv[argc] = { Integer::New(0), Integer::New(size), }; Handle<Value> res = slice_f->Call(tmp, argc, argv); return scope.Close(res); } v8::Handle<v8::Value> Srtp::protectRtp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_sendSession, srtp_protect); } v8::Handle<v8::Value> Srtp::unprotectRtp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_recvSession, srtp_unprotect); } v8::Handle<v8::Value> Srtp::protectRtcp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_sendSession, srtp_protect_rtcp); } v8::Handle<v8::Value> Srtp::unprotectRtcp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_recvSession, srtp_unprotect_rtcp); } <commit_msg>Disable srtp replay protection<commit_after>/* * webrtc-echo - A WebRTC echo server * Copyright (C) 2014 Stephan Thamm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "srtp.h" #include <node_buffer.h> #include "helper.h" using namespace v8; v8::Persistent<v8::Function> Srtp::constructor; bool Srtp::initialized = false; static void createSession(srtp_t *session, const char *key, ssrc_type_t direction) { srtp_policy_t policy; memset(&policy, 0, sizeof(policy)); crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp); crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp); policy.ssrc.type = direction; policy.ssrc.value = 0; policy.key = (unsigned char*) key; policy.window_size = 0; policy.allow_repeat_tx = 1; policy.next = NULL; srtp_create(session, &policy); } Srtp::Srtp(const char *sendKey, const char *recvKey) { if(!initialized) { DEBUG("initializing srtp"); srtp_init(); initialized = true; } createSession(&_sendSession, sendKey, ssrc_any_outbound); createSession(&_recvSession, recvKey, ssrc_any_inbound); } Srtp::~Srtp() { srtp_dealloc(_sendSession); srtp_dealloc(_recvSession); } void Srtp::init(v8::Handle<v8::Object> exports) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("Srtp")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // protoype NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtp", protectRtp); NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtp", unprotectRtp); NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtcp", protectRtcp); NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtcp", unprotectRtcp); constructor = Persistent<Function>::New(tpl->GetFunction()); // export exports->Set(String::NewSymbol("Srtp"), constructor); } v8::Handle<v8::Value> Srtp::New(const v8::Arguments& args) { HandleScope scope; if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` if(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) { return ThrowException(Exception::TypeError(String::New("Expected buffers"))); } const char *sendKey = node::Buffer::Data(args[0]); const char *recvKey = node::Buffer::Data(args[1]); Srtp* obj = new Srtp(sendKey, recvKey); obj->Wrap(args.This()); return args.This(); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local<Value> argv[1] = { argv[0] }; return scope.Close(constructor->NewInstance(argc, argv)); } } v8::Handle<v8::Value> Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) { HandleScope scope; // type checking if(!node::Buffer::HasInstance(args[0])) { return ThrowException(Exception::TypeError(String::New("Expected buffer"))); } // copy buffer for result int size = node::Buffer::Length(args[0]); char *in_buf = node::Buffer::Data(args[0]); Handle<Object> tmp = node::Buffer::New(size + 32)->handle_; char *out_buf = node::Buffer::Data(tmp); memcpy(out_buf, in_buf, size); // actual crypt stuff err_status_t err = fun(session, out_buf, &size); if(err != err_status_ok) { DEBUG("srtp error " << err); } // return slice of the right size Handle<Value> slice_v = tmp->Get(String::New("slice")); if(!slice_v->IsFunction()) { return ThrowException(Exception::Error(String::New("Buffer does not have a slice function"))); } Handle<v8::Function> slice_f = v8::Handle<v8::Function>::Cast(slice_v); const int argc = 2; Handle<Value> argv[argc] = { Integer::New(0), Integer::New(size), }; Handle<Value> res = slice_f->Call(tmp, argc, argv); return scope.Close(res); } v8::Handle<v8::Value> Srtp::protectRtp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_sendSession, srtp_protect); } v8::Handle<v8::Value> Srtp::unprotectRtp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_recvSession, srtp_unprotect); } v8::Handle<v8::Value> Srtp::protectRtcp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_sendSession, srtp_protect_rtcp); } v8::Handle<v8::Value> Srtp::unprotectRtcp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_recvSession, srtp_unprotect_rtcp); } <|endoftext|>
<commit_before>/* * webrtc-echo - A WebRTC echo server * Copyright (C) 2014 Stephan Thamm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "srtp.h" #include <node_buffer.h> #include "helper.h" using namespace v8; v8::Persistent<v8::Function> Srtp::constructor; bool Srtp::initialized = false; static void createSession(srtp_t *session, const char *key, ssrc_type_t direction) { srtp_policy_t policy; memset(&policy, 0, sizeof(policy)); crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp); crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp); policy.ssrc.type = direction; policy.ssrc.value = 0; policy.key = (unsigned char*) key; policy.window_size = 0; policy.allow_repeat_tx = 1; policy.next = NULL; srtp_create(session, &policy); } Srtp::Srtp(const char *sendKey, const char *recvKey) { if(!initialized) { DEBUG("initializing srtp"); srtp_init(); initialized = true; } createSession(&_sendSession, sendKey, ssrc_any_outbound); createSession(&_recvSession, recvKey, ssrc_any_inbound); } Srtp::~Srtp() { srtp_dealloc(_sendSession); srtp_dealloc(_recvSession); } void Srtp::init(v8::Handle<v8::Object> exports) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("Srtp")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // protoype NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtp", protectRtp); NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtp", unprotectRtp); NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtcp", protectRtcp); NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtcp", unprotectRtcp); constructor = Persistent<Function>::New(tpl->GetFunction()); // export exports->Set(String::NewSymbol("Srtp"), constructor); } v8::Handle<v8::Value> Srtp::New(const v8::Arguments& args) { HandleScope scope; if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` if(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) { return ThrowException(Exception::TypeError(String::New("Expected buffers"))); } const char *sendKey = node::Buffer::Data(args[0]); const char *recvKey = node::Buffer::Data(args[1]); Srtp* obj = new Srtp(sendKey, recvKey); obj->Wrap(args.This()); return args.This(); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local<Value> argv[1] = { argv[0] }; return scope.Close(constructor->NewInstance(argc, argv)); } } v8::Handle<v8::Value> Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) { HandleScope scope; // type checking if(!node::Buffer::HasInstance(args[0])) { return ThrowException(Exception::TypeError(String::New("Expected buffer"))); } // copy buffer for result int size = node::Buffer::Length(args[0]); char *in_buf = node::Buffer::Data(args[0]); Handle<Object> tmp = node::Buffer::New(size + 32)->handle_; char *out_buf = node::Buffer::Data(tmp); memcpy(out_buf, in_buf, size); // actual crypt stuff err_status_t err = fun(session, out_buf, &size); if(err != err_status_ok) { DEBUG("srtp error " << err); } // return slice of the right size Handle<Value> slice_v = tmp->Get(String::New("slice")); if(!slice_v->IsFunction()) { return ThrowException(Exception::Error(String::New("Buffer does not have a slice function"))); } Handle<v8::Function> slice_f = v8::Handle<v8::Function>::Cast(slice_v); const int argc = 2; Handle<Value> argv[argc] = { Integer::New(0), Integer::New(size), }; Handle<Value> res = slice_f->Call(tmp, argc, argv); return scope.Close(res); } v8::Handle<v8::Value> Srtp::protectRtp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_sendSession, srtp_protect); } v8::Handle<v8::Value> Srtp::unprotectRtp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_recvSession, srtp_unprotect); } v8::Handle<v8::Value> Srtp::protectRtcp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_sendSession, srtp_protect_rtcp); } v8::Handle<v8::Value> Srtp::unprotectRtcp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_recvSession, srtp_unprotect_rtcp); } <commit_msg>Do not set window size of srtp to zero<commit_after>/* * webrtc-echo - A WebRTC echo server * Copyright (C) 2014 Stephan Thamm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "srtp.h" #include <node_buffer.h> #include "helper.h" using namespace v8; v8::Persistent<v8::Function> Srtp::constructor; bool Srtp::initialized = false; static void createSession(srtp_t *session, const char *key, ssrc_type_t direction) { srtp_policy_t policy; memset(&policy, 0, sizeof(policy)); crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp); crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp); policy.ssrc.type = direction; policy.ssrc.value = 0; policy.key = (unsigned char*) key; //policy.window_size = 0; policy.allow_repeat_tx = 1; policy.next = NULL; srtp_create(session, &policy); } Srtp::Srtp(const char *sendKey, const char *recvKey) { if(!initialized) { DEBUG("initializing srtp"); srtp_init(); initialized = true; } createSession(&_sendSession, sendKey, ssrc_any_outbound); createSession(&_recvSession, recvKey, ssrc_any_inbound); } Srtp::~Srtp() { srtp_dealloc(_sendSession); srtp_dealloc(_recvSession); } void Srtp::init(v8::Handle<v8::Object> exports) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("Srtp")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // protoype NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtp", protectRtp); NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtp", unprotectRtp); NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtcp", protectRtcp); NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtcp", unprotectRtcp); constructor = Persistent<Function>::New(tpl->GetFunction()); // export exports->Set(String::NewSymbol("Srtp"), constructor); } v8::Handle<v8::Value> Srtp::New(const v8::Arguments& args) { HandleScope scope; if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` if(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) { return ThrowException(Exception::TypeError(String::New("Expected buffers"))); } const char *sendKey = node::Buffer::Data(args[0]); const char *recvKey = node::Buffer::Data(args[1]); Srtp* obj = new Srtp(sendKey, recvKey); obj->Wrap(args.This()); return args.This(); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local<Value> argv[1] = { argv[0] }; return scope.Close(constructor->NewInstance(argc, argv)); } } v8::Handle<v8::Value> Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) { HandleScope scope; // type checking if(!node::Buffer::HasInstance(args[0])) { return ThrowException(Exception::TypeError(String::New("Expected buffer"))); } // copy buffer for result int size = node::Buffer::Length(args[0]); char *in_buf = node::Buffer::Data(args[0]); Handle<Object> tmp = node::Buffer::New(size + 32)->handle_; char *out_buf = node::Buffer::Data(tmp); memcpy(out_buf, in_buf, size); // actual crypt stuff err_status_t err = fun(session, out_buf, &size); if(err != err_status_ok) { DEBUG("srtp error " << err); } // return slice of the right size Handle<Value> slice_v = tmp->Get(String::New("slice")); if(!slice_v->IsFunction()) { return ThrowException(Exception::Error(String::New("Buffer does not have a slice function"))); } Handle<v8::Function> slice_f = v8::Handle<v8::Function>::Cast(slice_v); const int argc = 2; Handle<Value> argv[argc] = { Integer::New(0), Integer::New(size), }; Handle<Value> res = slice_f->Call(tmp, argc, argv); return scope.Close(res); } v8::Handle<v8::Value> Srtp::protectRtp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_sendSession, srtp_protect); } v8::Handle<v8::Value> Srtp::unprotectRtp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_recvSession, srtp_unprotect); } v8::Handle<v8::Value> Srtp::protectRtcp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_sendSession, srtp_protect_rtcp); } v8::Handle<v8::Value> Srtp::unprotectRtcp(const v8::Arguments& args) { Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject()); return convert(args, srtp->_recvSession, srtp_unprotect_rtcp); } <|endoftext|>
<commit_before>#include "ompu/music/concrete/context.hpp" #include "ompu/music.hpp" namespace ompu { namespace music { namespace concrete { namespace detail { bool ContextKeyboard::empty() const noexcept { return notes_.empty(); } void ContextKeyboard::on(Note note) noexcept { notes_.emplace(std::move(note)); } void ContextKeyboard::off(Note note) noexcept { notes_.erase(note); } void ContextKeyboard::clear() { notes_.clear(); } } // detail Context::Context() : key_(keys::CMaj{}) {} void Context::set(Key key) noexcept { key_ = std::move(key); } std::vector<Chord> Context::get_closest_chords(std::size_t const limit) const { auto const notes = kb_.notes(); std::vector<Chord> ret; ret.reserve(limit); try { for (auto possible_root : notes) { auto const root_height = possible_root.height(); Chord chord{std::move(possible_root)}; for (auto possible_note : notes) { if (possible_note.height() == root_height) continue; chord.add(std::move(possible_note)); } ret.emplace_back(std::move(chord)); if (ret.size() >= limit) break; } } catch (invalid_chord_error const& e) { if (logger_) { *logger_ << e.what() << std::endl; } } return ret; } void Context::add(Note note) noexcept { kb_.on(std::move(note)); } void Context::remove(Note note) noexcept { kb_.off(std::move(note)); } void Context::add_or_remove(bool is_add, Note note) noexcept { is_add ? kb_.on(std::move(note)) : kb_.off(std::move(note)); } void Context::clear_notes() { kb_.clear(); } }}} // ompu <commit_msg>Chord detection: auto shrink buffer<commit_after>#include "ompu/music/concrete/context.hpp" #include "ompu/music.hpp" namespace ompu { namespace music { namespace concrete { namespace detail { bool ContextKeyboard::empty() const noexcept { return notes_.empty(); } void ContextKeyboard::on(Note note) noexcept { notes_.emplace(std::move(note)); } void ContextKeyboard::off(Note note) noexcept { notes_.erase(note); } void ContextKeyboard::clear() { notes_.clear(); } } // detail Context::Context() : key_(keys::CMaj{}) {} void Context::set(Key key) noexcept { key_ = std::move(key); } std::vector<Chord> Context::get_closest_chords(std::size_t const limit) const { auto const notes = kb_.notes(); std::vector<Chord> ret; ret.reserve(limit); try { for (auto possible_root : notes) { auto const root_height = possible_root.height(); Chord chord{std::move(possible_root)}; for (auto possible_note : notes) { if (possible_note.height() == root_height) continue; chord.add(std::move(possible_note)); } ret.emplace_back(std::move(chord)); if (ret.size() >= limit) break; } } catch (invalid_chord_error const& e) { if (logger_) { *logger_ << e.what() << std::endl; } } ret.shrink_to_fit(); return ret; } void Context::add(Note note) noexcept { kb_.on(std::move(note)); } void Context::remove(Note note) noexcept { kb_.off(std::move(note)); } void Context::add_or_remove(bool is_add, Note note) noexcept { is_add ? kb_.on(std::move(note)) : kb_.off(std::move(note)); } void Context::clear_notes() { kb_.clear(); } }}} // ompu <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <cmath> #include <stdlib.h> /* MacLaurin Serie for sin(x), Taylor serie with a = 0 * sin(x) = (Σn=0, ∞)(((-1 ^ n)/(2n + 1)!)(x^(2n + 1)) * As the serie converges, the next term of the sum will be * smaller than the last one, and also will be alternating * signs between + and -, therefore each iteration aproaches * the correct value. We need to get a given number of correct * digits, so we must make the last term calculated lesser * than the required absolute error. */ using namespace std; double sin(double x, double E); double maxAbsErr(int cd); ulong fact(ulong n); int main(int argc, char* args[]){ double x; int cd; if(argc > 2){ x = atof(args[1]); cd = atoi(args[2]); }else{ cout << "Input x and cd:" << endl; cin >> x; cin >> cd; } double E = maxAbsErr(cd); cout << "sin(" << x << ") = " << setprecision(cd) << sin(x, E) << ", E = " << E << ", cd = " << cd << endl; return 0; } //sin(x) = (Σn=0, ∞)(((-1 ^ n)/(2n + 1)!)(x^(2n + 1)) double sin(double x, double E){ double sin = 0.0d, term, last; int n = 0; bool bigger = true; while(bigger){ last = sin; term = (pow(-1.0d, n) / fact(2*n + 1)) * pow(x, 2*n + 1); if(abs(sin + term - last) > E){ sin += term; }else{ bigger = false; } n++; } return sin; } //Emax = 1.0 x 10 ^ -cd, asuming c++ uses floor as round method double maxAbsErr(int cd) { return pow(10.0d, -cd); } ulong fact(ulong n){ if(n <= 1) return 1; return n * fact(n - 1); } <commit_msg>Cleaned up the repository<commit_after><|endoftext|>
<commit_before>/* * Copyright 2016 - 2021 gary@drinkingtea.net * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <array> #include <SDL.h> #include <ox/claw/read.hpp> #include <nostalgia/common/point.hpp> #include <nostalgia/core/gfx.hpp> #include <nostalgia/core/userland/gfx.hpp> #include "core.hpp" namespace nostalgia::core { constexpr auto Scale = 5; ox::Error initGfx(Context *ctx) noexcept { auto id = new SdlImplData; ctx->setWindowerData(id); id->window = SDL_CreateWindow("nostalgia", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 240 * Scale, 160 * Scale, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); if (id->window == nullptr) { return OxError(1, SDL_GetError()); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); id->renderer = SDL_GL_CreateContext(id->window); if (id->renderer == nullptr) { return OxError(1, SDL_GetError()); } oxReturnError(renderer::init(ctx)); return OxError(0); } ox::Error shutdownGfx(Context *ctx) noexcept { oxReturnError(renderer::shutdown(ctx)); auto id = ctx->windowerData<SdlImplData>(); SDL_GL_DeleteContext(id->renderer); SDL_DestroyWindow(id->window); ctx->setWindowerData(nullptr); delete id; return OxError(0); } int getScreenWidth(Context *ctx) noexcept { auto id = ctx->windowerData<SdlImplData>(); int x = 0, y = 0; SDL_GetWindowSize(id->window, &x, &y); return x; } int getScreenHeight(Context *ctx) noexcept { auto id = ctx->windowerData<SdlImplData>(); int x = 0, y = 0; SDL_GetWindowSize(id->window, &x, &y); return y; } common::Size getScreenSize(Context *ctx) noexcept { auto id = ctx->windowerData<SdlImplData>(); int x = 0, y = 0; SDL_GetWindowSize(id->window, &x, &y); return {x, y}; } } <commit_msg>[nostalgia/core/sdl] Cleanup<commit_after>/* * Copyright 2016 - 2021 gary@drinkingtea.net * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <array> #include <SDL.h> #include <ox/claw/read.hpp> #include <nostalgia/core/gfx.hpp> #include <nostalgia/core/userland/gfx.hpp> #include "core.hpp" namespace nostalgia::core { constexpr auto Scale = 5; ox::Error initGfx(Context *ctx) noexcept { auto id = new SdlImplData; ctx->setWindowerData(id); id->window = SDL_CreateWindow("nostalgia", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 240 * Scale, 160 * Scale, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); if (id->window == nullptr) { return OxError(1, SDL_GetError()); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); id->renderer = SDL_GL_CreateContext(id->window); if (id->renderer == nullptr) { return OxError(1, SDL_GetError()); } oxReturnError(renderer::init(ctx)); return OxError(0); } ox::Error shutdownGfx(Context *ctx) noexcept { oxReturnError(renderer::shutdown(ctx)); auto id = ctx->windowerData<SdlImplData>(); SDL_GL_DeleteContext(id->renderer); SDL_DestroyWindow(id->window); ctx->setWindowerData(nullptr); delete id; return OxError(0); } int getScreenWidth(Context *ctx) noexcept { auto id = ctx->windowerData<SdlImplData>(); int x = 0, y = 0; SDL_GetWindowSize(id->window, &x, &y); return x; } int getScreenHeight(Context *ctx) noexcept { auto id = ctx->windowerData<SdlImplData>(); int x = 0, y = 0; SDL_GetWindowSize(id->window, &x, &y); return y; } common::Size getScreenSize(Context *ctx) noexcept { auto id = ctx->windowerData<SdlImplData>(); int x = 0, y = 0; SDL_GetWindowSize(id->window, &x, &y); return {x, y}; } } <|endoftext|>
<commit_before>#include <cmath> #include <cstdio> #include <vector> #include <deque> #include <map> #include <set> #include <iostream> #include <algorithm> #include <stdio.h> #include <string.h> #include <iostream> #include <fstream> #include <limits.h> #define DEBUG 0 #define MAX_N 5001 unsigned long long sumstb[MAX_N]; unsigned long long stb[MAX_N]; unsigned long long sumbts[MAX_N]; unsigned long long bts[MAX_N]; int n; // 0 - small to big, 1 - big to small unsigned long long cost[2][MAX_N][MAX_N]; using namespace std; class Mine { public: int x, w; Mine(int _x = 0, int _w = 0) { x = _x; w = _w; } void operator=(const Mine &m) { x = m.x; w = m.w; } }; vector<Mine> mines(MAX_N); bool func(const Mine &m1, const Mine &m2) { return (m1.x < m2.x); } inline long long costFromStoB(int s, int b) { long long ret = 0; if (s < b) { if (0 == s) { ret = stb[b]; } else { ret = stb[b] - stb[s] - sumstb[s - 1] * (long long)(mines[b].x - mines[s].x); } } return ret; } inline long long costFromBtoS(int s, int b) { long long ret = 0; if (s < b) { if (n - 1 == b) { ret = bts[s]; } else { ret = bts[s] - bts[b] - sumbts[b + 1] * (long long)(mines[b].x - mines[s].x); } } return ret; } int main() { // cout << "begin" << endl; #if DEBUG ifstream inFile; inFile.open("input.txt"); #endif int k; #if DEBUG inFile >> n >> k; #else cin >> n >> k; #endif for (size_t i = 0; i < n; i++) { int x, w; #if DEBUG inFile >> x >> w; #else cin >> x >> w; #endif mines[i].x = x; mines[i].w = w; } // sort sort(mines.begin(), mines.begin() + n, func); // small to big sumstb[0] = mines[0].w; for (size_t i = 1; i < n; i++) { sumstb[i] = mines[i].w + sumstb[i - 1]; stb[i] = stb[i - 1] + sumstb[i - 1] * (mines[i].x - mines[i - 1].x); } // big to small sumbts[n - 1] = mines[n - 1].w; for (int i = n - 2; i >= 0; i--) { sumbts[i] = mines[i].w + sumbts[i + 1]; bts[i] = bts[i + 1] + sumbts[i + 1] * (mines[i + 1].x - mines[i].x); } int tmove = n - k; unsigned long long ret = 0; for (size_t i = 0; i < n; i++) { for (size_t m = 0; m <= tmove; m++) { if (0 < i) { unsigned long long tmp = cost[0][i - 1][m]; if (0 == tmp) { tmp = cost[1][i - 1][m]; } else { if (tmp > cost[1][i - 1][m] && 0 < cost[1][i - 1][m]) { tmp = cost[1][i - 1][m]; } } if (0 < tmp && (0 == cost[0][i][m] || cost[0][i][m] > tmp)) { cost[0][i][m] = tmp; if (tmove == m) { if (0 == ret || ret > cost[0][i][m]) { ret = cost[0][i][m]; } } } if (0 < tmp && (0 == cost[1][i][m] || cost[1][i][m] > tmp)) { cost[1][i][m] = tmp; if (tmove == m) { if (0 == ret || ret > cost[1][i][m]) { ret = cost[1][i][m]; } } } } for (int j = i - 1; j >= 0 && j >= i - m; j--) { if (0 < m - (i - j) && 0 == cost[1][j][m - (i - j)]) { continue; } if (0 == cost[0][i][m] || cost[0][i][m] > (cost[1][j][m - (i - j)] + costFromStoB(j, i))) { cost[0][i][m] = cost[1][j][m - (i - j)] + costFromStoB(j, i); if (tmove == m) { if (0 == ret || ret > cost[0][i][m]) { ret = cost[0][i][m]; } } } } for (size_t j = i + 1; j < n; j++) { if (m + j - i > tmove) { break; } unsigned long long tmp = cost[0][i][m]; if (0 == tmp) { tmp = cost[1][i][m]; } else { if (tmp > cost[1][i][m] && 0 < cost[1][i][m]) { tmp = cost[1][i][m]; } } if (0 < m && 0 == tmp) { break; } if (0 == cost[1][j + 1][m + j - i] || cost[1][j + 1][m + j - i] > (tmp + costFromBtoS(i, j))) { cost[1][j + 1][m + j - i] = tmp + costFromBtoS(i, j); if (tmove == m + j - i) { if (0 == ret || ret > cost[1][j + 1][m + j - i]) { ret = cost[1][j + 1][m + j - i]; } } } } } } cout << ret << endl; #if DEBUG inFile.close(); #endif return 0; } <commit_msg>49.64 points<commit_after>#include <cmath> #include <cstdio> #include <vector> #include <deque> #include <map> #include <set> #include <iostream> #include <algorithm> #include <stdio.h> #include <string.h> #include <iostream> #include <fstream> #include <limits.h> #define DEBUG 0 #define MAX_N 5001 unsigned long long sumstb[MAX_N]; unsigned long long stb[MAX_N]; unsigned long long sumbts[MAX_N]; unsigned long long bts[MAX_N]; int n; // 0 - small to big, 1 - big to small unsigned long long cost[2][MAX_N][MAX_N]; using namespace std; class Mine { public: int x, w; Mine(int _x = 0, int _w = 0) { x = _x; w = _w; } void operator=(const Mine &m) { x = m.x; w = m.w; } }; vector<Mine> mines(MAX_N); bool func(const Mine &m1, const Mine &m2) { return (m1.x < m2.x); } inline long long costFromStoB(int s, int b) { long long ret = 0; if (s < b) { if (0 == s) { ret = stb[b]; } else { ret = stb[b] - stb[s] - sumstb[s - 1] * (long long)(mines[b].x - mines[s].x); } } return ret; } inline long long costFromBtoS(int s, int b) { long long ret = 0; if (s < b) { if (n - 1 == b) { ret = bts[s]; } else { ret = bts[s] - bts[b] - sumbts[b + 1] * (long long)(mines[b].x - mines[s].x); } } return ret; } int main() { #if DEBUG ifstream inFile; inFile.open("input.txt"); #endif int k; #if DEBUG inFile >> n >> k; #else cin >> n >> k; #endif for (size_t i = 0; i < n; i++) { int x, w; #if DEBUG inFile >> x >> w; #else cin >> x >> w; #endif mines[i].x = x; mines[i].w = w; } // sort sort(mines.begin(), mines.begin() + n, func); // small to big sumstb[0] = mines[0].w; for (size_t i = 1; i < n; i++) { sumstb[i] = mines[i].w + sumstb[i - 1]; stb[i] = stb[i - 1] + sumstb[i - 1] * (mines[i].x - mines[i - 1].x); } // big to small sumbts[n - 1] = mines[n - 1].w; for (int i = n - 2; i >= 0; i--) { sumbts[i] = mines[i].w + sumbts[i + 1]; bts[i] = bts[i + 1] + sumbts[i + 1] * (mines[i + 1].x - mines[i].x); } int tmove = n - k; unsigned long long ret = 0; for (size_t i = 0; i < n; i++) { for (size_t m = 0; m <= tmove; m++) { if (0 < i) { unsigned long long tmp = cost[0][i - 1][m]; if (0 == tmp) { tmp = cost[1][i - 1][m]; } else { if (tmp > cost[1][i - 1][m] && 0 < cost[1][i - 1][m]) { tmp = cost[1][i - 1][m]; } } if (0 < tmp && (0 == cost[0][i][m] || cost[0][i][m] > tmp)) { cost[0][i][m] = tmp; if (tmove == m) { if (0 == ret || ret > cost[0][i][m]) { ret = cost[0][i][m]; } } } if (0 < tmp && (0 == cost[1][i][m] || cost[1][i][m] > tmp)) { cost[1][i][m] = tmp; if (tmove == m) { if (0 == ret || ret > cost[1][i][m]) { ret = cost[1][i][m]; } } } } for (int j = i - 1; j >= 0 && j >= i - m; j--) { if (0 < m - (i - j) && 0 == cost[1][j][m - (i - j)]) { continue; } if (0 < ret && ret <= costFromStoB(j, i)) { break; } if (0 == cost[0][i][m] || cost[0][i][m] > (cost[1][j][m - (i - j)] + costFromStoB(j, i))) { cost[0][i][m] = cost[1][j][m - (i - j)] + costFromStoB(j, i); if (tmove == m) { if (0 == ret || ret > cost[0][i][m]) { ret = cost[0][i][m]; } } } } unsigned long long tmp = cost[0][i][m]; if (0 == tmp) { tmp = cost[1][i][m]; } else { if (tmp > cost[1][i][m] && 0 < cost[1][i][m]) { tmp = cost[1][i][m]; } } for (size_t j = i + 1; j < n; j++) { if (m + j - i > tmove) { break; } if (0 < m && 0 == tmp) { break; } if (0 < ret && (ret <= tmp + costFromBtoS(i, j))) { break; } if (0 == cost[1][j + 1][m + j - i] || cost[1][j + 1][m + j - i] > (tmp + costFromBtoS(i, j))) { cost[1][j + 1][m + j - i] = tmp + costFromBtoS(i, j); if (tmove == m + j - i) { if (0 == ret || ret > cost[1][j + 1][m + j - i]) { ret = cost[1][j + 1][m + j - i]; } } } } } } cout << ret << endl; #if DEBUG inFile.close(); #endif return 0; } <|endoftext|>
<commit_before>#ifndef CXX_CONVERSIONS_HXX # define CXX_CONVERSIONS_HXX # include <boost/optional.hpp> # include <libport/assert.hh> # include <libport/path.hh> # include <libport/symbol.hh> # include <object/cxx-object.hh> # include <object/float.hh> # include <object/list.hh> # include <object/path.hh> # include <object/string.hh> # include <runner/raise.hh> namespace object { // Nothing to do for objects template <> struct CxxConvert<libport::intrusive_ptr<Object> > { typedef libport::intrusive_ptr<Object> target_type; static rObject to(const rObject& o, unsigned) { return o; } static rObject from(rObject o) { if (!o) return void_class; return o; } }; // Convert between Urbi types template <typename Urbi> struct CxxConvert<libport::intrusive_ptr<Urbi> > { typedef libport::intrusive_ptr<Urbi> target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Urbi>(o, idx); return o->as<Urbi>(); } static rObject from(const target_type& v) { return v; } }; // Convert between Urbi types pointers template <typename Urbi> struct CxxConvert<Urbi*> { typedef Urbi* target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Urbi>(o, idx); return o->as<Urbi>().get(); } static rObject from(target_type v) { return v; } }; // Conversion with int template<> struct CxxConvert<int> { typedef int target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Float>(o, idx); return o->as<Float>()->to_int(); } static rObject from(target_type v) { return new Float(v); } }; // Conversion with unsigned chars template<> struct CxxConvert<unsigned char> { typedef unsigned char target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Float>(o, idx); int res = o->as<Float>()->to_int(); if (res < 0 || res > 255) runner::raise_bad_integer_error(res, "expected a number between 0 and 255, got %s"); return res; } static rObject from(target_type v) { return new Float(v); } }; // Conversion with float template<> struct CxxConvert<float> { typedef float target_type; static target_type to(const rObject& o, unsigned idx) { type_check(o, Float::proto, idx); return o->as<Float>()->value_get(); } static rObject from(target_type v) { return new Float(v); } }; // Conversion with unsigned int template<> struct CxxConvert<unsigned int> { typedef unsigned int target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Float>(o, idx); return o->as<Float>()->to_unsigned_int(); } static rObject from(target_type v) { return new Float(v); } }; // Conversion with unsigned_type template<> struct CxxConvert<Float::unsigned_type> { typedef Float::unsigned_type target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Float>(o, idx); return o->as<Float>()->to_unsigned_type(); } static rObject from(target_type v) { return new Float(v); } }; // Conversion with floating point template<> struct CxxConvert<Float::value_type> { typedef Float::value_type target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Float>(o, idx); return o->as<Float>()->value_get(); } static rObject from(target_type v) { return new Float(v); } }; // Conversion with std::strings template <> struct CxxConvert<std::string> { typedef std::string target_type; static target_type to(const rObject& o, unsigned idx) { type_check<String>(o, idx); return o->as<String>()->value_get(); } static rObject from(const target_type& v) { return new String(v); } }; // Conversion with libport::Symbols template <> struct CxxConvert<libport::Symbol> { typedef libport::Symbol target_type; static target_type to(const rObject& o, unsigned idx) { type_check<String>(o, idx); return libport::Symbol(o->as<String>()->value_get()); } static rObject from(target_type v) { return new String(v.name_get()); } }; // Conversion with bools template <> struct CxxConvert<bool> { typedef bool target_type; static target_type to(const rObject& o, unsigned) { return is_true(o); } static rObject from(target_type v) { return v ? true_class : false_class; } }; // Conversion with libport::path template <> struct CxxConvert<libport::path> { typedef libport::path target_type; static target_type to(const rObject& o, unsigned idx) { if (rString str = o->as<String>()) return str->value_get(); type_check<Path>(o, idx); return o->as<String>()->value_get(); } static rObject from(const target_type& v) { return new Path(v); } }; // Conversion with containers #define CONTAINER(Name, Method, ExtraT, ExtraTDecl) \ template <typename T ExtraTDecl> \ struct CxxConvert<Name<T ExtraT> > \ { \ typedef Name<T ExtraT> target_type; \ \ static target_type \ to(const rObject& o, unsigned idx) \ { \ type_check<List>(o); \ Name<T ExtraT> res; \ foreach (const rObject& elt, o->as<List>()->value_get()) \ res.Method(CxxConvert<T>::to(elt, idx)); \ return res; \ } \ \ static rObject \ from(const target_type& v) \ { \ objects_type res; \ foreach (const T& elt, v) \ res.push_back(CxxConvert<T>::from(elt)); \ return new List(res); \ } \ }; #define comma , CONTAINER(std::set, insert, /**/, /**/); CONTAINER(std::vector, push_back, /**/, /**/); CONTAINER(std::deque, push_back, /**/, /**/); CONTAINER(libport::ReservedVector, push_back, comma R, comma int R); #undef comma #undef CONTAINER // Conversion with boost::optional template <typename T> struct CxxConvert<boost::optional<T> > { typedef boost::optional<T> target_type; static target_type to(const rObject& o, unsigned idx) { if (o == void_class) return target_type(); return CxxConvert<T>::to(o, idx); } static rObject from(const target_type& v) { if (!v) return void_class; return CxxConvert<T>::from(v.get()); } }; template <typename T> rObject to_urbi(const T& v) { return CxxConvert<T>::from(v); } template <typename T> T from_urbi(rObject v) { return CxxConvert<T>::to(v, 0); } } #endif <commit_msg>Add Urbi/C++ conversions for std::pair.<commit_after>#ifndef CXX_CONVERSIONS_HXX # define CXX_CONVERSIONS_HXX # include <boost/optional.hpp> # include <libport/assert.hh> # include <libport/path.hh> # include <libport/symbol.hh> # include <object/cxx-object.hh> # include <object/float.hh> # include <object/list.hh> # include <object/path.hh> # include <object/string.hh> # include <runner/raise.hh> namespace object { // Nothing to do for objects template <> struct CxxConvert<libport::intrusive_ptr<Object> > { typedef libport::intrusive_ptr<Object> target_type; static rObject to(const rObject& o, unsigned) { return o; } static rObject from(rObject o) { if (!o) return void_class; return o; } }; // Convert between Urbi types template <typename Urbi> struct CxxConvert<libport::intrusive_ptr<Urbi> > { typedef libport::intrusive_ptr<Urbi> target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Urbi>(o, idx); return o->as<Urbi>(); } static rObject from(const target_type& v) { return v; } }; // Convert between Urbi types pointers template <typename Urbi> struct CxxConvert<Urbi*> { typedef Urbi* target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Urbi>(o, idx); return o->as<Urbi>().get(); } static rObject from(target_type v) { return v; } }; // Conversion with int template<> struct CxxConvert<int> { typedef int target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Float>(o, idx); return o->as<Float>()->to_int(); } static rObject from(target_type v) { return new Float(v); } }; // Conversion with unsigned chars template<> struct CxxConvert<unsigned char> { typedef unsigned char target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Float>(o, idx); int res = o->as<Float>()->to_int(); if (res < 0 || res > 255) runner::raise_bad_integer_error(res, "expected a number between 0 and 255, got %s"); return res; } static rObject from(target_type v) { return new Float(v); } }; // Conversion with float template<> struct CxxConvert<float> { typedef float target_type; static target_type to(const rObject& o, unsigned idx) { type_check(o, Float::proto, idx); return o->as<Float>()->value_get(); } static rObject from(target_type v) { return new Float(v); } }; // Conversion with unsigned int template<> struct CxxConvert<unsigned int> { typedef unsigned int target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Float>(o, idx); return o->as<Float>()->to_unsigned_int(); } static rObject from(target_type v) { return new Float(v); } }; // Conversion with unsigned_type template<> struct CxxConvert<Float::unsigned_type> { typedef Float::unsigned_type target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Float>(o, idx); return o->as<Float>()->to_unsigned_type(); } static rObject from(target_type v) { return new Float(v); } }; // Conversion with floating point template<> struct CxxConvert<Float::value_type> { typedef Float::value_type target_type; static target_type to(const rObject& o, unsigned idx) { type_check<Float>(o, idx); return o->as<Float>()->value_get(); } static rObject from(target_type v) { return new Float(v); } }; // Conversion with std::strings template <> struct CxxConvert<std::string> { typedef std::string target_type; static target_type to(const rObject& o, unsigned idx) { type_check<String>(o, idx); return o->as<String>()->value_get(); } static rObject from(const target_type& v) { return new String(v); } }; // Conversion with libport::Symbols template <> struct CxxConvert<libport::Symbol> { typedef libport::Symbol target_type; static target_type to(const rObject& o, unsigned idx) { type_check<String>(o, idx); return libport::Symbol(o->as<String>()->value_get()); } static rObject from(target_type v) { return new String(v.name_get()); } }; // Conversion with bools template <> struct CxxConvert<bool> { typedef bool target_type; static target_type to(const rObject& o, unsigned) { return is_true(o); } static rObject from(target_type v) { return v ? true_class : false_class; } }; // Conversion with libport::path template <> struct CxxConvert<libport::path> { typedef libport::path target_type; static target_type to(const rObject& o, unsigned idx) { if (rString str = o->as<String>()) return str->value_get(); type_check<Path>(o, idx); return o->as<String>()->value_get(); } static rObject from(const target_type& v) { return new Path(v); } }; // Conversion with containers #define CONTAINER(Name, Method, ExtraT, ExtraTDecl) \ template <typename T ExtraTDecl> \ struct CxxConvert<Name<T ExtraT> > \ { \ typedef Name<T ExtraT> target_type; \ \ static target_type \ to(const rObject& o, unsigned idx) \ { \ type_check<List>(o); \ Name<T ExtraT> res; \ foreach (const rObject& elt, o->as<List>()->value_get()) \ res.Method(CxxConvert<T>::to(elt, idx)); \ return res; \ } \ \ static rObject \ from(const target_type& v) \ { \ objects_type res; \ foreach (const T& elt, v) \ res.push_back(CxxConvert<T>::from(elt)); \ return new List(res); \ } \ }; #define comma , CONTAINER(std::set, insert, /**/, /**/); CONTAINER(std::vector, push_back, /**/, /**/); CONTAINER(std::deque, push_back, /**/, /**/); CONTAINER(libport::ReservedVector, push_back, comma R, comma int R); #undef comma #undef CONTAINER // Conversion with boost::optional template <typename T> struct CxxConvert<boost::optional<T> > { typedef boost::optional<T> target_type; static target_type to(const rObject& o, unsigned idx) { if (o == void_class) return target_type(); return CxxConvert<T>::to(o, idx); } static rObject from(const target_type& v) { if (!v) return void_class; return CxxConvert<T>::from(v.get()); } }; // Conversion with std::pair template <typename T1, typename T2> struct CxxConvert<std::pair<T1, T2> > { typedef std::pair<T1, T2> target_type; static target_type to(const rObject& o, unsigned idx) { type_check<List>(o, idx); const List::value_type& list = o->as<List>()->value_get(); if (list.size() != 2) runner::raise_primitive_error("Expected a list of size 2"); return std::make_pair(CxxConvert<T1>::to(list[0]), CxxConvert<T2>::to(list[1])); } static rObject from(const target_type& v) { List::value_type content; content.push_back(CxxConvert<T1>::from(v.first )); content.push_back(CxxConvert<T2>::from(v.second)); return new List(content); } }; template <typename T> rObject to_urbi(const T& v) { return CxxConvert<T>::from(v); } template <typename T> T from_urbi(rObject v) { return CxxConvert<T>::to(v, 0); } } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Use of this source code is governed by MIT license that can be found in the * LICENSE file in the root of the source tree. All contributing project authors * may be found in the AUTHORS file in the root of the source tree. */ #include "FFmpegSource.h" #include "Common/config.h" #include "Common/MediaSource.h" #include "Util/File.h" #include "System.h" #include "Thread/WorkThreadPool.h" #include "Network/sockutil.h" namespace FFmpeg { #define FFmpeg_FIELD "ffmpeg." const string kBin = FFmpeg_FIELD"bin"; const string kCmd = FFmpeg_FIELD"cmd"; const string kLog = FFmpeg_FIELD"log"; const string kSnap = FFmpeg_FIELD"snap"; onceToken token([]() { #ifdef _WIN32 string ffmpeg_bin = trim(System::execute("where ffmpeg")); #else string ffmpeg_bin = trim(System::execute("which ffmpeg")); #endif //默认ffmpeg命令路径为环境变量中路径 mINI::Instance()[kBin] = ffmpeg_bin.empty() ? "ffmpeg" : ffmpeg_bin; //ffmpeg日志保存路径 mINI::Instance()[kLog] = "./ffmpeg/ffmpeg.log"; mINI::Instance()[kCmd] = "%s -re -i %s -c:a aac -strict -2 -ar 44100 -ab 48k -c:v libx264 -f flv %s"; mINI::Instance()[kSnap] = "%s -i %s -y -f mjpeg -t 0.001 %s"; }); } FFmpegSource::FFmpegSource() { _poller = EventPollerPool::Instance().getPoller(); } FFmpegSource::~FFmpegSource() { DebugL; } static bool is_local_ip(const string &ip){ if (ip == "127.0.0.1" || ip == "localhost") { return true; } auto ips = SockUtil::getInterfaceList(); for (auto &obj : ips) { if (ip == obj["ip"]) { return true; } } return false; } void FFmpegSource::play(const string &src_url,const string &dst_url,int timeout_ms,const onPlay &cb) { GET_CONFIG(string,ffmpeg_bin,FFmpeg::kBin); GET_CONFIG(string,ffmpeg_cmd,FFmpeg::kCmd); GET_CONFIG(string,ffmpeg_log,FFmpeg::kLog); _src_url = src_url; _dst_url = dst_url; _media_info.parse(dst_url); char cmd[1024] = {0}; snprintf(cmd, sizeof(cmd),ffmpeg_cmd.data(),ffmpeg_bin.data(),src_url.data(),dst_url.data()); _process.run(cmd,ffmpeg_log.empty() ? "" : File::absolutePath("",ffmpeg_log)); InfoL << cmd; if (is_local_ip(_media_info._host)) { //推流给自己的,通过判断流是否注册上来判断是否正常 if(_media_info._schema != RTSP_SCHEMA && _media_info._schema != RTMP_SCHEMA){ cb(SockException(Err_other,"本服务只支持rtmp/rtsp推流")); return; } weak_ptr<FFmpegSource> weakSelf = shared_from_this(); findAsync(timeout_ms,[cb,weakSelf,timeout_ms](const MediaSource::Ptr &src){ auto strongSelf = weakSelf.lock(); if(!strongSelf){ //自己已经销毁 return; } if(src){ //推流给自己成功 cb(SockException()); strongSelf->onGetMediaSource(src); strongSelf->startTimer(timeout_ms); return; } //推流失败 if(!strongSelf->_process.wait(false)){ //ffmpeg进程已经退出 cb(SockException(Err_other,StrPrinter << "ffmpeg已经退出,exit code = " << strongSelf->_process.exit_code())); return; } //ffmpeg进程还在线,但是等待推流超时 cb(SockException(Err_other,"等待超时")); }); } else{ //推流给其他服务器的,通过判断FFmpeg进程是否在线判断是否成功 weak_ptr<FFmpegSource> weakSelf = shared_from_this(); _timer = std::make_shared<Timer>(timeout_ms / 1000,[weakSelf,cb,timeout_ms](){ auto strongSelf = weakSelf.lock(); if(!strongSelf){ //自身已经销毁 return false; } //FFmpeg还在线,那么我们认为推流成功 if(strongSelf->_process.wait(false)){ cb(SockException()); strongSelf->startTimer(timeout_ms); return false; } //ffmpeg进程已经退出 cb(SockException(Err_other,StrPrinter << "ffmpeg已经退出,exit code = " << strongSelf->_process.exit_code())); return false; },_poller); } } void FFmpegSource::findAsync(int maxWaitMS, const function<void(const MediaSource::Ptr &src)> &cb) { auto src = MediaSource::find(_media_info._schema, _media_info._vhost, _media_info._app, _media_info._streamid); if(src || !maxWaitMS){ cb(src); return; } void *listener_tag = this; //若干秒后执行等待媒体注册超时回调 auto onRegistTimeout = _poller->doDelayTask(maxWaitMS,[cb,listener_tag](){ //取消监听该事件 NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged); cb(nullptr); return 0; }); weak_ptr<FFmpegSource> weakSelf = shared_from_this(); auto onRegist = [listener_tag,weakSelf,cb,onRegistTimeout](BroadcastMediaChangedArgs) { auto strongSelf = weakSelf.lock(); if(!strongSelf) { //本身已经销毁,取消延时任务 onRegistTimeout->cancel(); NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged); return; } if (!bRegist || sender.getSchema() != strongSelf->_media_info._schema || sender.getVhost() != strongSelf->_media_info._vhost || sender.getApp() != strongSelf->_media_info._app || sender.getId() != strongSelf->_media_info._streamid) { //不是自己感兴趣的事件,忽略之 return; } //查找的流终于注册上了;取消延时任务,防止多次回调 onRegistTimeout->cancel(); //取消事件监听 NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged); //切换到自己的线程再回复 strongSelf->_poller->async([listener_tag,weakSelf,cb](){ auto strongSelf = weakSelf.lock(); if(!strongSelf) { return; } //再找一遍媒体源,一般能找到 strongSelf->findAsync(0,cb); }, false); }; //监听媒体注册事件 NoticeCenter::Instance().addListener(listener_tag, Broadcast::kBroadcastMediaChanged, onRegist); } /** * 定时检查媒体是否在线 */ void FFmpegSource::startTimer(int timeout_ms) { weak_ptr<FFmpegSource> weakSelf = shared_from_this(); _timer = std::make_shared<Timer>(1, [weakSelf, timeout_ms]() { auto strongSelf = weakSelf.lock(); if (!strongSelf) { //自身已经销毁 return false; } if (is_local_ip(strongSelf->_media_info._host)) { //推流给自己的,我们通过检查是否已经注册来判断FFmpeg是否工作正常 strongSelf->findAsync(0, [&](const MediaSource::Ptr &src) { //同步查找流 if (!src) { //流不在线,重新拉流, 这里原先是10秒超时,实际发现10秒不够,改成20秒了 if(strongSelf->_replay_ticker.elapsedTime() > 20 * 1000){ //上次重试时间超过10秒,那么再重试FFmpeg拉流 strongSelf->_replay_ticker.resetTime(); strongSelf->play(strongSelf->_src_url, strongSelf->_dst_url, timeout_ms, [](const SockException &) {}); } } }); } else { //推流给其他服务器的,我们通过判断FFmpeg进程是否在线,如果FFmpeg推流中断,那么它应该会自动退出 if (!strongSelf->_process.wait(false)) { //ffmpeg不在线,重新拉流 strongSelf->play(strongSelf->_src_url, strongSelf->_dst_url, timeout_ms, [weakSelf](const SockException &ex) { if(!ex){ //没有错误 return; } auto strongSelf = weakSelf.lock(); if (!strongSelf) { //自身已经销毁 return; } //上次重试时间超过10秒,那么再重试FFmpeg拉流 strongSelf->startTimer(10 * 1000); }); } } return true; }, _poller); } void FFmpegSource::setOnClose(const function<void()> &cb){ _onClose = cb; } bool FFmpegSource::close(MediaSource &sender, bool force) { auto listener = _listener.lock(); if(listener && !listener->close(sender,force)){ //关闭失败 return false; } //该流无人观看,我们停止吧 if(_onClose){ _onClose(); } return true; } MediaOriginType FFmpegSource::getOriginType(MediaSource &sender) const{ return MediaOriginType::ffmpeg_pull; } string FFmpegSource::getOriginUrl(MediaSource &sender) const{ return _src_url; } std::shared_ptr<SockInfo> FFmpegSource::getOriginSock(MediaSource &sender) const { return nullptr; } void FFmpegSource::onGetMediaSource(const MediaSource::Ptr &src) { auto listener = src->getListener(); if (listener.lock().get() != this) { //防止多次进入onGetMediaSource函数导致无效递归调用的bug _listener = listener; src->setListener(shared_from_this()); } else { WarnL << "多次触发onGetMediaSource事件:" << src->getSchema() << "/" << src->getVhost() << "/" << src->getApp() << "/" << src->getId(); } } void FFmpegSnap::makeSnap(const string &play_url, const string &save_path, float timeout_sec, const function<void(bool)> &cb) { GET_CONFIG(string,ffmpeg_bin,FFmpeg::kBin); GET_CONFIG(string,ffmpeg_snap,FFmpeg::kSnap); GET_CONFIG(string,ffmpeg_log,FFmpeg::kLog); std::shared_ptr<Process> process = std::make_shared<Process>(); auto delayTask = EventPollerPool::Instance().getPoller()->doDelayTask(timeout_sec * 1000,[process,cb](){ if(process->wait(false)){ //FFmpeg进程还在运行,超时就关闭它 process->kill(2000); } return 0; }); WorkThreadPool::Instance().getPoller()->async([process,play_url,save_path,delayTask,cb](){ char cmd[1024] = {0}; snprintf(cmd, sizeof(cmd),ffmpeg_snap.data(),ffmpeg_bin.data(),play_url.data(),save_path.data()); process->run(cmd,ffmpeg_log.empty() ? "" : File::absolutePath("",ffmpeg_log)); //等待FFmpeg进程退出 process->wait(true); //FFmpeg进程退出了可以取消定时器了 delayTask->cancel(); //执行回调函数 cb(process->exit_code() == 0); }); } <commit_msg>修复FFmpeg截图可能失败的问题<commit_after>/* * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Use of this source code is governed by MIT license that can be found in the * LICENSE file in the root of the source tree. All contributing project authors * may be found in the AUTHORS file in the root of the source tree. */ #include "FFmpegSource.h" #include "Common/config.h" #include "Common/MediaSource.h" #include "Util/File.h" #include "System.h" #include "Thread/WorkThreadPool.h" #include "Network/sockutil.h" namespace FFmpeg { #define FFmpeg_FIELD "ffmpeg." const string kBin = FFmpeg_FIELD"bin"; const string kCmd = FFmpeg_FIELD"cmd"; const string kLog = FFmpeg_FIELD"log"; const string kSnap = FFmpeg_FIELD"snap"; onceToken token([]() { #ifdef _WIN32 string ffmpeg_bin = trim(System::execute("where ffmpeg")); #else string ffmpeg_bin = trim(System::execute("which ffmpeg")); #endif //默认ffmpeg命令路径为环境变量中路径 mINI::Instance()[kBin] = ffmpeg_bin.empty() ? "ffmpeg" : ffmpeg_bin; //ffmpeg日志保存路径 mINI::Instance()[kLog] = "./ffmpeg/ffmpeg.log"; mINI::Instance()[kCmd] = "%s -re -i %s -c:a aac -strict -2 -ar 44100 -ab 48k -c:v libx264 -f flv %s"; mINI::Instance()[kSnap] = "%s -i %s -y -f mjpeg -t 0.001 %s"; }); } FFmpegSource::FFmpegSource() { _poller = EventPollerPool::Instance().getPoller(); } FFmpegSource::~FFmpegSource() { DebugL; } static bool is_local_ip(const string &ip){ if (ip == "127.0.0.1" || ip == "localhost") { return true; } auto ips = SockUtil::getInterfaceList(); for (auto &obj : ips) { if (ip == obj["ip"]) { return true; } } return false; } void FFmpegSource::play(const string &src_url,const string &dst_url,int timeout_ms,const onPlay &cb) { GET_CONFIG(string,ffmpeg_bin,FFmpeg::kBin); GET_CONFIG(string,ffmpeg_cmd,FFmpeg::kCmd); GET_CONFIG(string,ffmpeg_log,FFmpeg::kLog); _src_url = src_url; _dst_url = dst_url; _media_info.parse(dst_url); char cmd[1024] = {0}; snprintf(cmd, sizeof(cmd),ffmpeg_cmd.data(),ffmpeg_bin.data(),src_url.data(),dst_url.data()); _process.run(cmd,ffmpeg_log.empty() ? "" : File::absolutePath("",ffmpeg_log)); InfoL << cmd; if (is_local_ip(_media_info._host)) { //推流给自己的,通过判断流是否注册上来判断是否正常 if(_media_info._schema != RTSP_SCHEMA && _media_info._schema != RTMP_SCHEMA){ cb(SockException(Err_other,"本服务只支持rtmp/rtsp推流")); return; } weak_ptr<FFmpegSource> weakSelf = shared_from_this(); findAsync(timeout_ms,[cb,weakSelf,timeout_ms](const MediaSource::Ptr &src){ auto strongSelf = weakSelf.lock(); if(!strongSelf){ //自己已经销毁 return; } if(src){ //推流给自己成功 cb(SockException()); strongSelf->onGetMediaSource(src); strongSelf->startTimer(timeout_ms); return; } //推流失败 if(!strongSelf->_process.wait(false)){ //ffmpeg进程已经退出 cb(SockException(Err_other,StrPrinter << "ffmpeg已经退出,exit code = " << strongSelf->_process.exit_code())); return; } //ffmpeg进程还在线,但是等待推流超时 cb(SockException(Err_other,"等待超时")); }); } else{ //推流给其他服务器的,通过判断FFmpeg进程是否在线判断是否成功 weak_ptr<FFmpegSource> weakSelf = shared_from_this(); _timer = std::make_shared<Timer>(timeout_ms / 1000,[weakSelf,cb,timeout_ms](){ auto strongSelf = weakSelf.lock(); if(!strongSelf){ //自身已经销毁 return false; } //FFmpeg还在线,那么我们认为推流成功 if(strongSelf->_process.wait(false)){ cb(SockException()); strongSelf->startTimer(timeout_ms); return false; } //ffmpeg进程已经退出 cb(SockException(Err_other,StrPrinter << "ffmpeg已经退出,exit code = " << strongSelf->_process.exit_code())); return false; },_poller); } } void FFmpegSource::findAsync(int maxWaitMS, const function<void(const MediaSource::Ptr &src)> &cb) { auto src = MediaSource::find(_media_info._schema, _media_info._vhost, _media_info._app, _media_info._streamid); if(src || !maxWaitMS){ cb(src); return; } void *listener_tag = this; //若干秒后执行等待媒体注册超时回调 auto onRegistTimeout = _poller->doDelayTask(maxWaitMS,[cb,listener_tag](){ //取消监听该事件 NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged); cb(nullptr); return 0; }); weak_ptr<FFmpegSource> weakSelf = shared_from_this(); auto onRegist = [listener_tag,weakSelf,cb,onRegistTimeout](BroadcastMediaChangedArgs) { auto strongSelf = weakSelf.lock(); if(!strongSelf) { //本身已经销毁,取消延时任务 onRegistTimeout->cancel(); NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged); return; } if (!bRegist || sender.getSchema() != strongSelf->_media_info._schema || sender.getVhost() != strongSelf->_media_info._vhost || sender.getApp() != strongSelf->_media_info._app || sender.getId() != strongSelf->_media_info._streamid) { //不是自己感兴趣的事件,忽略之 return; } //查找的流终于注册上了;取消延时任务,防止多次回调 onRegistTimeout->cancel(); //取消事件监听 NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged); //切换到自己的线程再回复 strongSelf->_poller->async([listener_tag,weakSelf,cb](){ auto strongSelf = weakSelf.lock(); if(!strongSelf) { return; } //再找一遍媒体源,一般能找到 strongSelf->findAsync(0,cb); }, false); }; //监听媒体注册事件 NoticeCenter::Instance().addListener(listener_tag, Broadcast::kBroadcastMediaChanged, onRegist); } /** * 定时检查媒体是否在线 */ void FFmpegSource::startTimer(int timeout_ms) { weak_ptr<FFmpegSource> weakSelf = shared_from_this(); _timer = std::make_shared<Timer>(1, [weakSelf, timeout_ms]() { auto strongSelf = weakSelf.lock(); if (!strongSelf) { //自身已经销毁 return false; } if (is_local_ip(strongSelf->_media_info._host)) { //推流给自己的,我们通过检查是否已经注册来判断FFmpeg是否工作正常 strongSelf->findAsync(0, [&](const MediaSource::Ptr &src) { //同步查找流 if (!src) { //流不在线,重新拉流, 这里原先是10秒超时,实际发现10秒不够,改成20秒了 if(strongSelf->_replay_ticker.elapsedTime() > 20 * 1000){ //上次重试时间超过10秒,那么再重试FFmpeg拉流 strongSelf->_replay_ticker.resetTime(); strongSelf->play(strongSelf->_src_url, strongSelf->_dst_url, timeout_ms, [](const SockException &) {}); } } }); } else { //推流给其他服务器的,我们通过判断FFmpeg进程是否在线,如果FFmpeg推流中断,那么它应该会自动退出 if (!strongSelf->_process.wait(false)) { //ffmpeg不在线,重新拉流 strongSelf->play(strongSelf->_src_url, strongSelf->_dst_url, timeout_ms, [weakSelf](const SockException &ex) { if(!ex){ //没有错误 return; } auto strongSelf = weakSelf.lock(); if (!strongSelf) { //自身已经销毁 return; } //上次重试时间超过10秒,那么再重试FFmpeg拉流 strongSelf->startTimer(10 * 1000); }); } } return true; }, _poller); } void FFmpegSource::setOnClose(const function<void()> &cb){ _onClose = cb; } bool FFmpegSource::close(MediaSource &sender, bool force) { auto listener = _listener.lock(); if(listener && !listener->close(sender,force)){ //关闭失败 return false; } //该流无人观看,我们停止吧 if(_onClose){ _onClose(); } return true; } MediaOriginType FFmpegSource::getOriginType(MediaSource &sender) const{ return MediaOriginType::ffmpeg_pull; } string FFmpegSource::getOriginUrl(MediaSource &sender) const{ return _src_url; } std::shared_ptr<SockInfo> FFmpegSource::getOriginSock(MediaSource &sender) const { return nullptr; } void FFmpegSource::onGetMediaSource(const MediaSource::Ptr &src) { auto listener = src->getListener(); if (listener.lock().get() != this) { //防止多次进入onGetMediaSource函数导致无效递归调用的bug _listener = listener; src->setListener(shared_from_this()); } else { WarnL << "多次触发onGetMediaSource事件:" << src->getSchema() << "/" << src->getVhost() << "/" << src->getApp() << "/" << src->getId(); } } void FFmpegSnap::makeSnap(const string &play_url, const string &save_path, float timeout_sec, const function<void(bool)> &cb) { GET_CONFIG(string,ffmpeg_bin,FFmpeg::kBin); GET_CONFIG(string,ffmpeg_snap,FFmpeg::kSnap); GET_CONFIG(string,ffmpeg_log,FFmpeg::kLog); Ticker ticker; WorkThreadPool::Instance().getPoller()->async([timeout_sec, play_url,save_path,cb, ticker](){ auto elapsed_ms = ticker.elapsedTime(); if (elapsed_ms > timeout_sec * 1000) { //超时,后台线程负载太高,当代太久才启动该任务 cb(false); return; } char cmd[1024] = {0}; snprintf(cmd, sizeof(cmd),ffmpeg_snap.data(),ffmpeg_bin.data(),play_url.data(),save_path.data()); std::shared_ptr<Process> process = std::make_shared<Process>(); process->run(cmd,ffmpeg_log.empty() ? "" : File::absolutePath("",ffmpeg_log)); //定时器延时应该减去后台任务启动的延时 auto delayTask = EventPollerPool::Instance().getPoller()->doDelayTask(timeout_sec * 1000 - elapsed_ms,[process,cb](){ if(process->wait(false)){ //FFmpeg进程还在运行,超时就关闭它 process->kill(2000); } return 0; }); //等待FFmpeg进程退出 process->wait(true); //FFmpeg进程退出了可以取消定时器了 delayTask->cancel(); //执行回调函数 cb(process->exit_code() == 0); }); } <|endoftext|>
<commit_before><commit_msg>p843 - Crypt Kicker<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <cstdio> // printf() #include <cstring> // memcmp() #include <string> #include <queue> #include <openssl/sha.h> #include <byteswap.h> #include "alphabet.h" using namespace std; // clear text password entered by user string pwd; // contains the hash of the unknown password char pwdHash[SHA256_DIGEST_LENGTH]; // contains the hash of a bruteforced string char bruteHash[SHA256_DIGEST_LENGTH]; // the maximum number of characters bruteforce shall check const unsigned char MaxChars = 20; /** * @brief prints 32 bytes of memory * * prints a hex dump of 32 bytes of memory pointed to * * @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash */ void printSHAHash(const unsigned int *const pbuf) { // byteswap the integer pointed to, to display hex dump in correct order // TODO: how to deal with big endian machines printf("%X%X%X%X%X%X%X%X\n", bswap_32(*(pbuf)), bswap_32(*(pbuf+1)), bswap_32(*(pbuf+2)), bswap_32(*(pbuf+3)), bswap_32(*(pbuf+4)), bswap_32(*(pbuf+5)), bswap_32(*(pbuf+6)), bswap_32(*(pbuf+7)) ); } /** * @brief generates an SHA256 hash * * generates an SHA256 hash using openSSL * * @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated * @param[in] length: the number of bytes the that input points to holds * @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash * * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false */ bool generateSHA256(const void *const input, const size_t &length, char *const hashStr) { if(!hashStr || !input || length==0) { return false; } SHA256_CTX hash; if(!SHA256_Init(&hash)) { return false; } if(!SHA256_Update(&hash, input, length)) { return false; } if(!SHA256_Final(reinterpret_cast<unsigned char*>(hashStr), &hash)) { return false; } return true; } /** * @brief checks equality of two hashes * * calculates the SHA256 hash of 'password' and compares it * with the initial password hash * * @param[in] password: a const string containing a guessed password * * @return returns true if hashes match; false if generation of hash failed or hashes not match */ bool checkPassword(const string &password) { #ifdef VERBOSE cout << "checking " << password << endl; #endif // VERBOSE // generate sha hash from entered string and write it to pwdHash if(!generateSHA256(password.c_str(), password.length(), bruteHash)) { cerr << "Error when generating SHA256 from \"" << password << "\"" << endl; return false; } if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH)) { cout << "match [" << password << "]" << endl << "hash: " << endl; printSHAHash((unsigned int*)bruteHash); return true; } return false; } /** * @brief recursive implementation of bruteforce * * recursive implementation of bruteforce attack * call it as follows: bruteRecursive(string(""), width); * * @param[in] baseString: a const string indicates the prefix of a string to be checked * @param[in] width: the maximum number of characters you wish to be checked */ volatile bool strFound = false; void bruteRecursive(const string baseString, const unsigned int width) { for(int i=0; (i<SizeAlphabet) && (!strFound); i++) { if (baseString.length()+1 < width) { bruteRecursive(baseString+alphabet[i], width); } if(checkPassword(baseString+alphabet[i])) { strFound = true; } } } /** * @brief iterative implementation of bruteforce * * iterative implementation of bruteforce attack * call it as follows: bruteIterative(width); * * @param[in] width: the maximum number of characters you wish to be checked * * @return return true if the password was found */ bool bruteIterative(const unsigned int width) { queue<string> myQueue; // myQueue must contain at least one element when entering loop // else: SIGSEGV // hence, start checking with an empty string myQueue.push(""); do { string baseString = myQueue.front(); myQueue.pop(); for(int i=0; i<SizeAlphabet; i++) { if (baseString.length()+1 < width) { myQueue.push(baseString+alphabet[i]); } if(checkPassword(baseString+alphabet[i])) { return true; } } } while(!myQueue.empty()); return false; } int bruteInit(string password) { pwd=password; // generate sha hash from entered string and write it to pwdHash if(!generateSHA256(pwd.c_str(), pwd.length(), pwdHash)) { cerr << "Error when generating SHA256 from \"" << pwd << "\"" << endl; return -2; } else { printf("SHA256 Hash for secret password is:\n"); printSHAHash((unsigned int*)pwdHash); } cout << "checking using Recusive Method" << endl; for(int i=1; (i<=MaxChars) && (!strFound); i++) { cout << "checking passwords with " << i << " characters..." << endl; bruteRecursive(string(""),i); } cout << "checking using Iterative Method" << endl; bruteIterative(MaxChars); return 0; } <commit_msg>use cout instead of printf<commit_after>#include <iostream> #include <cstring> // memcmp() #include <string> #include <queue> #include <openssl/sha.h> #include <byteswap.h> #include "alphabet.h" using namespace std; // clear text password entered by user string pwd; // contains the hash of the unknown password char pwdHash[SHA256_DIGEST_LENGTH]; // contains the hash of a bruteforced string char bruteHash[SHA256_DIGEST_LENGTH]; // the maximum number of characters bruteforce shall check const unsigned char MaxChars = 20; /** * @brief prints 32 bytes of memory * * prints a hex dump of 32 bytes of memory pointed to * * @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash */ void printSHAHash(const unsigned int *const pbuf) { // byteswap the integer pointed to, to display hex dump in correct order // TODO: how to deal with big endian machines cout << std::hex << std::uppercase << bswap_32(*(pbuf)) << bswap_32(*(pbuf+1)) << bswap_32(*(pbuf+2)) << bswap_32(*(pbuf+3)) << bswap_32(*(pbuf+4)) << bswap_32(*(pbuf+5)) << bswap_32(*(pbuf+6)) << bswap_32(*(pbuf+7)) << endl; } /** * @brief generates an SHA256 hash * * generates an SHA256 hash using openSSL * * @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated * @param[in] length: the number of bytes the that input points to holds * @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash * * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false */ bool generateSHA256(const void *const input, const size_t &length, char *const hashStr) { if(!hashStr || !input || length==0) { return false; } SHA256_CTX hash; if(!SHA256_Init(&hash)) { return false; } if(!SHA256_Update(&hash, input, length)) { return false; } if(!SHA256_Final(reinterpret_cast<unsigned char*>(hashStr), &hash)) { return false; } return true; } /** * @brief checks equality of two hashes * * calculates the SHA256 hash of 'password' and compares it * with the initial password hash * * @param[in] password: a const string containing a guessed password * * @return returns true if hashes match; false if generation of hash failed or hashes not match */ bool checkPassword(const string &password) { #ifdef VERBOSE cout << "checking " << password << endl; #endif // VERBOSE // generate sha hash from entered string and write it to pwdHash if(!generateSHA256(password.c_str(), password.length(), bruteHash)) { cerr << "Error when generating SHA256 from \"" << password << "\"" << endl; return false; } if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH)) { cout << "match [" << password << "]" << endl << "hash: " << endl; printSHAHash((unsigned int*)bruteHash); return true; } return false; } /** * @brief recursive implementation of bruteforce * * recursive implementation of bruteforce attack * call it as follows: bruteRecursive(string(""), width); * * @param[in] baseString: a const string indicates the prefix of a string to be checked * @param[in] width: the maximum number of characters you wish to be checked */ volatile bool strFound = false; void bruteRecursive(const string baseString, const unsigned int width) { for(int i=0; (i<SizeAlphabet) && (!strFound); i++) { if (baseString.length()+1 < width) { bruteRecursive(baseString+alphabet[i], width); } if(checkPassword(baseString+alphabet[i])) { strFound = true; } } } /** * @brief iterative implementation of bruteforce * * iterative implementation of bruteforce attack * call it as follows: bruteIterative(width); * * @param[in] width: the maximum number of characters you wish to be checked * * @return return true if the password was found */ bool bruteIterative(const unsigned int width) { queue<string> myQueue; // myQueue must contain at least one element when entering loop // else: SIGSEGV // hence, start checking with an empty string myQueue.push(""); do { string baseString = myQueue.front(); myQueue.pop(); for(int i=0; i<SizeAlphabet; i++) { if (baseString.length()+1 < width) { myQueue.push(baseString+alphabet[i]); } if(checkPassword(baseString+alphabet[i])) { return true; } } } while(!myQueue.empty()); return false; } int bruteInit(string password) { pwd=password; // generate sha hash from entered string and write it to pwdHash if(!generateSHA256(pwd.c_str(), pwd.length(), pwdHash)) { cerr << "Error when generating SHA256 from \"" << pwd << "\"" << endl; return -2; } else { cout << "SHA256 Hash for secret password is:" << endl; printSHAHash((unsigned int*)pwdHash); } cout << "checking using Recusive Method" << endl; for(int i=1; (i<=MaxChars) && (!strFound); i++) { cout << "checking passwords with " << i << " characters..." << endl; bruteRecursive(string(""),i); } cout << "checking using Iterative Method" << endl; bruteIterative(MaxChars); return 0; } <|endoftext|>
<commit_before>#ifndef STAN_MODEL_MODEL_BASE_CRTP_HPP #define STAN_MODEL_MODEL_BASE_CRTP_HPP #include <stan/model/model_base.hpp> #include <iostream> #include <utility> #include <vector> namespace stan { namespace model { /** * Base class employing the curiously recursive template pattern for * static inheritance to adapt templated `log_prob` and `write_array` * methods to their untemplated virtual counterparts declared in * `model_base`. * * The derived class `M` is required to implement the following two * pairs of template functions, * * ``` * template <bool propto, bool jacobian, typename T> * T log_prob(std::vector<T>& params_r, * std::vector<int>& params_i, * std::ostream* msgs = 0) const; * template <bool propto, bool jacobian, typename T> * T log_prob(Eigen::Matrix<T, -1, 1>& params_r, * std::ostream* msgs = 0) const; * ``` * * and * * ``` * template <typename RNG> * void write_array(RNG& base_rng, * std::vector<double>& params_r, * std::vector<int>& params_i, * std::vector<double>& vars, * bool include_tparams = true, * bool include_gqs = true, * std::ostream* msgs = 0) const; * * template <typename RNG> * void write_array(RNG& base_rng, * Eigen::Matrix<double, -1, 1>& params_r, * Eigen::Matrix<double, -1, 1>& vars, * bool include_tparams = true, * bool include_gqs = true, * std::ostream* msgs = 0) const * ``` * * <p>The derived class `M` must be declared following the curiously * recursive template pattern, for example, if `M` is `foo_model`, * then `foo_model` should be declared as * * ``` * class foo_model : public stan::model::model_base_crtp<foo_model> { ... }; * ``` * * The recursion arises when the type of the declared class appears as * a template parameter in the class it extends. For example, * `foo_model` is declared to extend `model_base_crtp<foo_model>`. In * general, the template parameter `M` for this class is called the * derived class, and must be declared to extend `foo_model<M>`. * * @tparam M type of derived model, which must implemented the * template methods defined in the class documentation */ template <typename M> class model_base_crtp : public stan::model::model_base { public: /** * Construct a model with the specified number of real unconstrained * parameters. * * @param[in] num_params_r number of real unconstrained parameters */ explicit model_base_crtp(size_t num_params_r) : model_base(num_params_r) {} /** * Destroy this class. This is required to be virtual to allow * subclass references to clean up superclasses, but is otherwise a * no-op. */ virtual ~model_base_crtp() {} inline double log_prob(Eigen::VectorXd& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, false, double>( theta, msgs); } inline math::var log_prob(Eigen::Matrix<math::var, -1, 1>& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, false>(theta, msgs); } inline double log_prob_jacobian(Eigen::VectorXd& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, true>(theta, msgs); } inline math::var log_prob_jacobian(Eigen::Matrix<math::var, -1, 1>& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, true>(theta, msgs); } inline double log_prob_propto(Eigen::VectorXd& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, false>(theta, msgs); } inline math::var log_prob_propto(Eigen::Matrix<math::var, -1, 1>& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, false>(theta, msgs); } inline double log_prob_propto_jacobian(Eigen::VectorXd& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, true>(theta, msgs); } inline math::var log_prob_propto_jacobian( Eigen::Matrix<math::var, -1, 1>& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, true>(theta, msgs); } void write_array(boost::ecuyer1988& rng, Eigen::VectorXd& theta, Eigen::VectorXd& vars, bool include_tparams = true, bool include_gqs = true, std::ostream* msgs = 0) const override { return static_cast<const M*>(this)->template write_array( rng, theta, vars, include_tparams, include_gqs, msgs); } // TODO(carpenter): remove redundant std::vector methods below here ===== // ====================================================================== inline double log_prob(std::vector<double>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, false>( theta, theta_i, msgs); } inline math::var log_prob(std::vector<math::var>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, false>( theta, theta_i, msgs); } inline double log_prob_jacobian(std::vector<double>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, true>( theta, theta_i, msgs); } inline math::var log_prob_jacobian(std::vector<math::var>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, true>( theta, theta_i, msgs); } inline double log_prob_propto(std::vector<double>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, false>( theta, theta_i, msgs); } inline math::var log_prob_propto(std::vector<math::var>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, false>( theta, theta_i, msgs); } inline double log_prob_propto_jacobian(std::vector<double>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, true>( theta, theta_i, msgs); } inline math::var log_prob_propto_jacobian(std::vector<math::var>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, true>( theta, theta_i, msgs); } void write_array(boost::ecuyer1988& rng, std::vector<double>& theta, std::vector<int>& theta_i, std::vector<double>& vars, bool include_tparams = true, bool include_gqs = true, std::ostream* msgs = 0) const override { return static_cast<const M*>(this)->template write_array( rng, theta, theta_i, vars, include_tparams, include_gqs, msgs); } void transform_inits(const io::var_context& context, Eigen::VectorXd& params_r, std::ostream* msgs) const override { return static_cast<const M*>(this)->template transform_inits( context, params_r, msgs); } }; } // namespace model } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MODEL_MODEL_BASE_CRTP_HPP #define STAN_MODEL_MODEL_BASE_CRTP_HPP #include <stan/model/model_base.hpp> #include <iostream> #include <utility> #include <vector> namespace stan { namespace model { /** * Base class employing the curiously recursive template pattern for * static inheritance to adapt templated `log_prob` and `write_array` * methods to their untemplated virtual counterparts declared in * `model_base`. * * The derived class `M` is required to implement the following two * pairs of template functions, * * ``` * template <bool propto, bool jacobian, typename T> * T log_prob(std::vector<T>& params_r, * std::vector<int>& params_i, * std::ostream* msgs = 0) const; * template <bool propto, bool jacobian, typename T> * T log_prob(Eigen::Matrix<T, -1, 1>& params_r, * std::ostream* msgs = 0) const; * ``` * * and * * ``` * template <typename RNG> * void write_array(RNG& base_rng, * std::vector<double>& params_r, * std::vector<int>& params_i, * std::vector<double>& vars, * bool include_tparams = true, * bool include_gqs = true, * std::ostream* msgs = 0) const; * * template <typename RNG> * void write_array(RNG& base_rng, * Eigen::Matrix<double, -1, 1>& params_r, * Eigen::Matrix<double, -1, 1>& vars, * bool include_tparams = true, * bool include_gqs = true, * std::ostream* msgs = 0) const * ``` * * <p>The derived class `M` must be declared following the curiously * recursive template pattern, for example, if `M` is `foo_model`, * then `foo_model` should be declared as * * ``` * class foo_model : public stan::model::model_base_crtp<foo_model> { ... }; * ``` * * The recursion arises when the type of the declared class appears as * a template parameter in the class it extends. For example, * `foo_model` is declared to extend `model_base_crtp<foo_model>`. In * general, the template parameter `M` for this class is called the * derived class, and must be declared to extend `foo_model<M>`. * * @tparam M type of derived model, which must implemented the * template methods defined in the class documentation */ template <typename M> class model_base_crtp : public stan::model::model_base { public: /** * Construct a model with the specified number of real unconstrained * parameters. * * @param[in] num_params_r number of real unconstrained parameters */ explicit model_base_crtp(size_t num_params_r) : model_base(num_params_r) {} /** * Destroy this class. This is required to be virtual to allow * subclass references to clean up superclasses, but is otherwise a * no-op. */ virtual ~model_base_crtp() {} inline double log_prob(Eigen::VectorXd& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, false, double>( theta, msgs); } inline math::var log_prob(Eigen::Matrix<math::var, -1, 1>& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, false>(theta, msgs); } inline double log_prob_jacobian(Eigen::VectorXd& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, true>(theta, msgs); } inline math::var log_prob_jacobian(Eigen::Matrix<math::var, -1, 1>& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, true>(theta, msgs); } inline double log_prob_propto(Eigen::VectorXd& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, false>(theta, msgs); } inline math::var log_prob_propto(Eigen::Matrix<math::var, -1, 1>& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, false>(theta, msgs); } inline double log_prob_propto_jacobian(Eigen::VectorXd& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, true>(theta, msgs); } inline math::var log_prob_propto_jacobian( Eigen::Matrix<math::var, -1, 1>& theta, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, true>(theta, msgs); } void write_array(boost::ecuyer1988& rng, Eigen::VectorXd& theta, Eigen::VectorXd& vars, bool include_tparams = true, bool include_gqs = true, std::ostream* msgs = 0) const override { return static_cast<const M*>(this)->template write_array( rng, theta, vars, include_tparams, include_gqs, msgs); } // TODO(carpenter): remove redundant std::vector methods below here ===== // ====================================================================== inline double log_prob(std::vector<double>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, false>( theta, theta_i, msgs); } inline math::var log_prob(std::vector<math::var>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, false>( theta, theta_i, msgs); } inline double log_prob_jacobian(std::vector<double>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, true>( theta, theta_i, msgs); } inline math::var log_prob_jacobian(std::vector<math::var>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<false, true>( theta, theta_i, msgs); } inline double log_prob_propto(std::vector<double>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, false>( theta, theta_i, msgs); } inline math::var log_prob_propto(std::vector<math::var>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, false>( theta, theta_i, msgs); } inline double log_prob_propto_jacobian(std::vector<double>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, true>( theta, theta_i, msgs); } inline math::var log_prob_propto_jacobian(std::vector<math::var>& theta, std::vector<int>& theta_i, std::ostream* msgs) const override { return static_cast<const M*>(this)->template log_prob<true, true>( theta, theta_i, msgs); } void write_array(boost::ecuyer1988& rng, std::vector<double>& theta, std::vector<int>& theta_i, std::vector<double>& vars, bool include_tparams = true, bool include_gqs = true, std::ostream* msgs = 0) const override { return static_cast<const M*>(this)->template write_array( rng, theta, theta_i, vars, include_tparams, include_gqs, msgs); } void transform_inits(const io::var_context& context, Eigen::VectorXd& params_r, std::ostream* msgs) const override { return static_cast<const M*>(this)->template transform_inits( context, params_r, msgs); } }; } // namespace model } // namespace stan #endif <|endoftext|>
<commit_before>/** * @file Test_StaticStore.cpp * @brief Tests: libxaos-core:memory/store/impl/StaticStore.h * * Several StaticStores are constructed in mememory, populated with data, * and tested to see if said data persists. */ #include <cstdint> #include "memory/store/impl/StaticStore.h" #include "catch.hpp" // Define some types. constexpr short Store128_ALIGN = 4; constexpr short Store256_ALIGN = 64; constexpr short Store512_ALIGN = 128; constexpr short Store4096_ALIGN = 4096; // THIS IS RIDICULOUS using Store128 = libxaos::memory::StaticStore<128, Store128_ALIGN, 0>; using Store256 = libxaos::memory::StaticStore<256, Store256_ALIGN, 0>; using Store512 = libxaos::memory::StaticStore<512, Store512_ALIGN, 0>; using Store4096 = libxaos::memory::StaticStore<4096, Store4096_ALIGN, 0>; TEST_CASE("CORE:MEMORY/STORE/IMPL/StaticStore | Stores hold data.", "[core][memory]") { // create our stores to test Store128 storeA {}; Store256 storeB {}; Store512 storeC {}; REQUIRE(storeA.getRawStorage()); REQUIRE(storeB.getRawStorage()); REQUIRE(storeC.getRawStorage()); // loop through and populate stores with data for (int i = 0; i < 128 + 256 + 512; i++) { uint8_t* data = nullptr; if (i < 128) { data = storeA.getRawStorage() + i; } else if (i < 256) { data = storeB.getRawStorage() + (i - 128); } else { data = storeC.getRawStorage() + (i - 128 - 256); } *data = i; } // Verify data is correct. uint8_t index = 0; for (int i = 0; i < 128 + 256 + 512; i++) { if (i < 128) { REQUIRE(*(storeA.getRawStorage() + index) == index); } else if (i < 256) { REQUIRE(*(storeB.getRawStorage() + index - 128) == index); } else { REQUIRE(*(storeC.getRawStorage() + index - 128 - 256) == index); } index++; } } TEST_CASE("CORE:MEMORY/STORE/IMPL/StaticStore | Stores are aligned.", "[core][memory][!mayfail]") { // create our stores Store128 storeA {}; Store256 storeB {}; Store512 storeC {}; Store4096 storeD {}; // Test alignments uintptr_t addressA = reinterpret_cast<uintptr_t>(storeA.getRawStorage()); uintptr_t addressB = reinterpret_cast<uintptr_t>(storeB.getRawStorage()); uintptr_t addressC = reinterpret_cast<uintptr_t>(storeC.getRawStorage()); uintptr_t addressD = reinterpret_cast<uintptr_t>(storeD.getRawStorage()); REQUIRE(addressA % Store128_ALIGN == 0); REQUIRE(addressB % Store256_ALIGN == 0); REQUIRE(addressC % Store512_ALIGN == 0); REQUIRE(addressD % Store4096_ALIGN == 0); } <commit_msg>Fixed a StaticStore testing bug.<commit_after>/** * @file Test_StaticStore.cpp * @brief Tests: libxaos-core:memory/store/impl/StaticStore.h * * Several StaticStores are constructed in mememory, populated with data, * and tested to see if said data persists. */ #include <cstdint> #include "memory/store/impl/StaticStore.h" #include "catch.hpp" // Define some types. constexpr short Store128_ALIGN = 4; constexpr short Store256_ALIGN = 64; constexpr short Store512_ALIGN = 128; constexpr short Store4096_ALIGN = 4096; // THIS IS RIDICULOUS using Store128 = libxaos::memory::StaticStore<128, Store128_ALIGN, 0>; using Store256 = libxaos::memory::StaticStore<256, Store256_ALIGN, 0>; using Store512 = libxaos::memory::StaticStore<512, Store512_ALIGN, 0>; using Store4096 = libxaos::memory::StaticStore<4096, Store4096_ALIGN, 0>; TEST_CASE("CORE:MEMORY/STORE/IMPL/StaticStore | Stores hold data.", "[core][memory]") { // create our stores to test Store128 storeA {}; Store256 storeB {}; Store512 storeC {}; REQUIRE(storeA.getRawStorage()); REQUIRE(storeB.getRawStorage()); REQUIRE(storeC.getRawStorage()); // loop through and populate stores with data for (int i = 0; i < 128 + 256 + 512; i++) { uint8_t* data = nullptr; if (i < 128) { data = storeA.getRawStorage() + i; } else if (i < 256) { data = storeB.getRawStorage() + (i - 128); } else { data = storeC.getRawStorage() + (i - 128 - 256); } *data = i; } // Verify data is correct. uint8_t index = 0; for (int i = 0; i < 128 + 256 + 512; i++) { INFO("Current iteration: " << i); if (i < 128) { REQUIRE(*(storeA.getRawStorage() + i) == index); } else if (i < 256) { REQUIRE(*(storeB.getRawStorage() + i - 128) == index); } else { REQUIRE(*(storeC.getRawStorage() + i - 128 - 256) == index); } index++; } } TEST_CASE("CORE:MEMORY/STORE/IMPL/StaticStore | Stores are aligned.", "[core][memory][!mayfail]") { // create our stores Store128 storeA {}; Store256 storeB {}; Store512 storeC {}; Store4096 storeD {}; // Test alignments uintptr_t addressA = reinterpret_cast<uintptr_t>(storeA.getRawStorage()); uintptr_t addressB = reinterpret_cast<uintptr_t>(storeB.getRawStorage()); uintptr_t addressC = reinterpret_cast<uintptr_t>(storeC.getRawStorage()); uintptr_t addressD = reinterpret_cast<uintptr_t>(storeD.getRawStorage()); REQUIRE(addressA % Store128_ALIGN == 0); REQUIRE(addressB % Store256_ALIGN == 0); REQUIRE(addressC % Store512_ALIGN == 0); REQUIRE(addressD % Store4096_ALIGN == 0); } <|endoftext|>
<commit_before>#include <cstdio> #include <algorithm> #include <string> #include <map> #include <cstdlib> using namespace std; map <string ,int> Dict; //debug #ifdef LOCAL #define fp stdin #else FILE *fp; #endif string getword(){ char ch; string s; while((ch=getc(fp))!=EOF){ if(ch=='-'){ if(getc(fp)=='\n'){ continue; }else{ fseek(fp,ftell(fp)-1,SEEK_CUR); break; } } if(ch>'A'&&ch<'Z' || ch>'a'&&ch<'z') s.push_back(ch); else break; } } int main(int argc, char const *argv[]) { #ifndef LOCAL fp=fopen("case1.in","r"); #else printf("used LOCAL"); #endif cout<< getword()<<endl; return 0; } <commit_msg>update uoj1109<commit_after>#include <cstdio> #include <algorithm> #include <string> #include <map> #include <cstdlib> #include <iostream> using namespace std; map <string ,int> Dict; //debug #ifdef LOCAL #define fp stdin #else FILE *fp; #endif string getword(){ char ch; string s; while((ch=getc(fp))!=EOF){ if(ch=='-'){ if(getc(fp)=='\n'){ continue; }else{ fseek(fp,ftell(fp)-1,SEEK_CUR); break; } } if(ch>'A'&&ch<'Z' || ch>'a'&&ch<'z') s.push_back(ch); else break; } } int main(int argc, char const *argv[]) { #ifndef LOCAL fp=fopen("case1.in","r"); #else printf("used LOCAL"); #endif cout << getword()<<endl; return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); int fa[10010],le[30],bgn[30]; int n, a[10010],b[10010],la = 0,lb = 0; int find(int x) { return (x==fa[x]?x:find(fa[x])); } void Union(int m, int n) { m = find(m); n = find(n); if(m!=n) fa[m] = n; } void Init(){ scanf("%d",&n); scanf("%d",&le[0]); bgn[0] = 2; REP(i,1,n-1) { scanf("%d",&le[i]); bgn[i] = bgn[i-1] + le[i-1]; } char ch; getchar(); while((ch= getchar())!='=') if(ch=='0' || ch=='1') a[la++] = ch-'0'; else REP(i,0,le[ch-'a']-1) a[la++] = bgn[ch-'a'] + i; while((ch= getchar())!='\n') if(ch=='0' || ch=='1') b[lb++] = ch-'0'; else REP(i,0,le[ch-'a']-1) b[lb++] = bgn[ch-'a'] + i; return ; } void Solve(){ if(la!=lb) { print(0); return ; } REP(i,0,bg[n-1]+le[n-1]-1) fa[i] = i; REP(i,0,la-1) { if(s1[i]+s2[i]==1) { print(0); return ; } Union(s1[i],s2[i]); } int ans = 0; REP(i,0,bg[n-1]+le[n-1]-1) if(fa[i]==i) ans++; printf("%.0lf\n",pow(2,ans-2)); return ; } int main(){ #ifdef LOCAL freopen("uoj1138.in","r",stdin); #endif Init(),Solve(); return 0; }<commit_msg>update uoj1138<commit_after>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); int fa[10010],le[30],bgn[30]; int n, a[10010],b[10010],la = 0,lb = 0; int find(int x) { return (x==fa[x]?x:find(fa[x])); } void Union(int m, int n) { m = find(m); n = find(n); if(m!=n) fa[m] = n; } void Init(){ scanf("%d",&n); scanf("%d",&le[0]); bgn[0] = 2; REP(i,1,n-1) { scanf("%d",&le[i]); bgn[i] = bgn[i-1] + le[i-1]; } char ch; getchar(); while((ch= getchar())!='=') if(ch=='0' || ch=='1') a[la++] = ch-'0'; else REP(i,0,le[ch-'a']-1) a[la++] = bgn[ch-'a'] + i; while((ch= getchar())!='\n') if(ch=='0' || ch=='1') b[lb++] = ch-'0'; else REP(i,0,le[ch-'a']-1) b[lb++] = bgn[ch-'a'] + i; return ; } void Solve(){ if(la!=lb) { print(0); return ; } REP(i,0,bgn[n-1]+le[n-1]-1) fa[i] = i; REP(i,0,la-1) { if(a[i]+b[i]==1) { print(0); return ; } Union(a[i],b[i]); } int ans = 0; REP(i,0,bgn[n-1]+le[n-1]-1) if(fa[i]==i) ans++; printf("%.0lf\n",pow(2,ans-2)); return ; } int main(){ #ifdef LOCAL freopen("uoj1138.in","r",stdin); #endif Init(),Solve(); return 0; }<|endoftext|>
<commit_before>#include <stdio.h> #include <queue> #include <vector> #include <utility> #include <iostream> #include <string> #include <stack> #include <queue> using namespace std; queue<string> lv1; queue<string> lv2; queue<string> lv3; queue<string> lv4; string temp; int templv; int temptime=0; int usernum; int users=0; int read(int now){ if(now < temptime || users>usernum) return 0; do{ if(temp.empty()){ }else{ switch(templv){ case 1: lv1.push(temp);break; case 2: lv2.push(temp);break; case 3: lv3.push(temp);break; case 4: lv4.push(temp);break; } } users++; if(users<=usernum){ temp.resize(21); //需要预先分配空间 scanf("%d%d%s",&temptime,&templv,&temp[0]); } else return 0; }while(temptime<=now); } int pop(){ if(lv4.size()>0){ printf("%s\n",lv4.front().c_str()); lv4.pop(); return 4; } if(lv3.size()>0){ printf("%s\n",lv3.front().c_str()); lv3.pop(); return 3; } if(lv2.size()>0){ printf("%s\n",lv2.front().c_str()); lv2.pop(); return 2; } if(lv1.size()>0){ printf("%s\n",lv1.front().c_str()); lv1.pop(); return 1; } return 0; } int main(int argc, char const *argv[]) { int time; scanf("%d%d",&usernum,&time); for (int i = 0; i < time && i< usernum *5; ++i) { read(i); //cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl; if(i%5==0) pop(); } //while(pop()){} return 0; }<commit_msg>update uoj2254<commit_after>#include <stdio.h> #include <queue> #include <vector> #include <utility> #include <iostream> #include <string> #include <stack> #include <queue> using namespace std; queue<string> lv1; queue<string> lv2; queue<string> lv3; queue<string> lv4; string temp; int templv; int temptime=0; int usernum; int users=0; int read(int now){ if(now < temptime || users>usernum) return 0; do{ if(temp.empty()){ }else{ switch(templv){ case 1: lv1.push(temp);break; case 2: lv2.push(temp);break; case 3: lv3.push(temp);break; case 4: lv4.push(temp);break; } } users++; if(users<=usernum){ temp.resize(21); //需要预先分配空间 scanf("%d%d%s",&temptime,&templv,&temp[0]); } else return 0; }while(temptime<=now); } int pop(){ if(lv4.size()>0){ printf("%s\n",lv4.front().c_str()); lv4.pop(); return 4; } if(lv3.size()>0){ printf("%s\n",lv3.front().c_str()); lv3.pop(); return 3; } if(lv2.size()>0){ printf("%s\n",lv2.front().c_str()); lv2.pop(); return 2; } if(lv1.size()>0){ printf("%s\n",lv1.front().c_str()); lv1.pop(); return 1; } return 0; } int main(int argc, char const *argv[]) { int time; scanf("%d%d",&usernum,&time); for (int i = 0; i < time && i< usernum *5; ++i) { read(i); //cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl; if(i%5==0) pop(); } //while(pop()){} return 0; }<|endoftext|>
<commit_before>// rbOOmit: An implementation of the Certified Reduced Basis method. // Copyright (C) 2009, 2010 David J. Knezevic // This file is part of rbOOmit. // rbOOmit is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // rbOOmit is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "transient_rb_param_subdomain_node.h" #include "transient_rb_param_subdomain_tree.h" #include "transient_rb_system.h" #include "libmesh_logging.h" namespace libMesh { TransientRBParamSubdomainNode::TransientRBParamSubdomainNode(TransientRBParamSubdomainTree& tree_in, const std::vector<Real>& anchor_in) : Parent(tree_in, anchor_in) { } void TransientRBParamSubdomainNode::add_child(const std::vector<Real>& new_anchor, Child c) { START_LOG("add_child()", "TransientRBParamSubdomainNode"); // cast the tree reference to a TransientRBParamSubdomainTree TransientRBParamSubdomainTree& trans_tree = libmesh_cast_ref<TransientRBParamSubdomainTree&>(_tree); if(c == LEFT) { if(left_child != NULL) { std::cout << "Error: Child already exists!" << std::endl; libmesh_error(); } else { // Allocate a new child node left_child = new TransientRBParamSubdomainNode(trans_tree, new_anchor); } } if(c == RIGHT) { if(right_child != NULL) { std::cout << "Error: Child already exists!" << std::endl; libmesh_error(); } else { // Allocate a new child node right_child = new TransientRBParamSubdomainNode(trans_tree, new_anchor); } } STOP_LOG("add_child()", "TransientRBParamSubdomainNode"); } void TransientRBParamSubdomainNode::hp_greedy() { _rb_system.clear_basis_function_dependent_data(); // Load the (full or subsampled) training set if(_tree.n_subsampled_training_points >= n_global_training_parameters()) { _rb_system.load_training_set( training_set ); } else { std::vector< std::vector<Number> > subsampled_training_set = get_subsampled_training_set(); _rb_system.load_training_set( subsampled_training_set ); } _rb_system.set_current_parameters( this->anchor ); _rb_system.set_training_tolerance(_tree.h_tol); Real greedy_bound; // These casts have to succeed TransientRBParamSubdomainTree& trans_tree = libmesh_cast_ref<TransientRBParamSubdomainTree&>(_tree); TransientRBSystem& trans_rb = libmesh_cast_ref<TransientRBSystem&>(_rb_system); // Set the maximum number of truth solves to N_bar in the time-dependent case trans_rb.set_max_truth_solves(_tree.N_bar); if (!trans_tree.use_delta_N_in_h_stage) { trans_rb.set_POD_tol(_tree.h_tol/trans_tree.conserv_factor); } else { trans_rb.set_POD_tol(-1.); } // delta_N might be changed in basis training in the transient case // (i.e., if we're using POD_tol, or if we hit Nmax) // hence we save and reload delta_N unsigned int saved_delta_N = trans_rb.get_delta_N(); greedy_bound = trans_rb.train_reduced_basis(); // Reload delta_N trans_rb.set_delta_N(saved_delta_N); trans_rb.set_current_parameters(this->anchor); Real RB_error = trans_rb.RB_solve(trans_rb.get_n_basis_functions()); if (RB_error > _tree.h_tol/trans_tree.conserv_factor) { std::cout << "Error: The h-tolerance was not satisfied at the " << "anchor point hence h-type refinement may not converge." << std::endl; libmesh_error(); } if ( greedy_bound > _tree.h_tol) // recursive call to hp_greedy { std::cout << "h tolerance not satisfied, splitting subdomain..." << std::endl; split_this_subdomain(true); left_child->hp_greedy(); right_child->hp_greedy(); } else // terminate branch, populate the model with standard p-type,write out subelement data { std::cout << "h tolerance satisfied, performing p-refinement..." << std::endl; greedy_bound = perform_p_stage(greedy_bound); if (greedy_bound > _tree.p_tol) { std::cout << "p tolerance not satisfied, splitting subdomain..." << std::endl; split_this_subdomain(false); left_child->hp_greedy(); right_child->hp_greedy(); } else { std::cout << "p tolerance satisfied, subdomain " << _tree.leaf_node_index << " is a leaf node..." << std::endl; // Finally, write out the data for this subdomain write_subdomain_data_to_files(); _tree.leaf_node_index++; } } } Real TransientRBParamSubdomainNode::perform_p_stage(Real greedy_bound) { START_LOG("perform_p_stage()", "TransientRBParamSubdomainNode"); // Continue the greedy process on this subdomain, i.e. // we do not discard the basis functions generated for // this subdomain in the h-refinement phase _rb_system.set_training_tolerance(_tree.p_tol); TransientRBSystem& trans_rb = libmesh_cast_ref<TransientRBSystem&>(_rb_system); // Ignore max_truth_solves and POD-tol in the p-stage trans_rb.set_POD_tol(-1.); trans_rb.set_max_truth_solves(-1); // Clear the reduced basis and reinitialize the greedy to the anchor point trans_rb.clear_basis_function_dependent_data(); trans_rb.set_current_parameters( this->anchor ); // Checking if p-tol is already satisfied or Nmax has been reached // if not do another (standard) greedy if ( (greedy_bound > _tree.p_tol) || (_rb_system.get_n_basis_functions() < _rb_system.get_Nmax()) ) { greedy_bound = _rb_system.train_reduced_basis(); } STOP_LOG("perform_p_stage()", "TransientRBParamSubdomainNode"); return greedy_bound; } void TransientRBParamSubdomainNode::split_this_subdomain(bool h_stage_split) { START_LOG("split_this_subdomain()", "TransientRBParamSubdomainNode"); // These first few lines are the same as RBParamSubdomainNode::split_this_subdomain this->add_child( _rb_system.get_greedy_parameter(0), RBParamSubdomainNode::LEFT); this->add_child( _rb_system.get_greedy_parameter(1), RBParamSubdomainNode::RIGHT); // Compute distance between the children anchor points, and pass to children (JLE 2010-09-16) Real distance_between_children_anchors = 0.; for (unsigned int i = 0; i < left_child->anchor.size(); i++) { distance_between_children_anchors += std::pow((left_child->anchor[i] - right_child->anchor[i]),2.); } distance_between_children_anchors = std::sqrt(distance_between_children_anchors); left_child->distance_between_anchors = distance_between_children_anchors; right_child->distance_between_anchors = distance_between_children_anchors; // We now need some code specific to the transient case because it // is possible that we have repeated selection of training points // in the transient case (due to the POD-Greedy) and hence we // may have distance_between_children_anchors == 0. bool anchors_are_equal = (distance_between_children_anchors == 0.); if (h_stage_split) { if (anchors_are_equal) { std::cout << "Error: Anchor points for children are equal!" << std::endl; libmesh_error(); } } else { if (anchors_are_equal) { for (unsigned int i=2; i< _rb_system.greedy_param_list.size() ; i++) { bool parameters_are_equal = true; for (unsigned int j = 0; j < left_child->anchor.size(); j++) { parameters_are_equal = ( parameters_are_equal && (left_child->anchor[j] == _rb_system.get_greedy_parameter(i)[j])); } if (!parameters_are_equal) { right_child->anchor = _rb_system.get_greedy_parameter(i); anchors_are_equal = false; break; } } // anchors_are_equal has been updated, check if we have found different point. if(anchors_are_equal) { std::cout << "Error: Unable to find distinct anchors in additional splitting step." << std::endl; libmesh_error(); } } } this->initialize_child_training_sets(); STOP_LOG("split_this_subdomain()", "TransientRBParamSubdomainNode"); } } // namespace libMesh <commit_msg>Fixing single precision regression<commit_after>// rbOOmit: An implementation of the Certified Reduced Basis method. // Copyright (C) 2009, 2010 David J. Knezevic // This file is part of rbOOmit. // rbOOmit is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // rbOOmit is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "transient_rb_param_subdomain_node.h" #include "transient_rb_param_subdomain_tree.h" #include "transient_rb_system.h" #include "libmesh_logging.h" namespace libMesh { TransientRBParamSubdomainNode::TransientRBParamSubdomainNode(TransientRBParamSubdomainTree& tree_in, const std::vector<Real>& anchor_in) : Parent(tree_in, anchor_in) { } void TransientRBParamSubdomainNode::add_child(const std::vector<Real>& new_anchor, Child c) { START_LOG("add_child()", "TransientRBParamSubdomainNode"); // cast the tree reference to a TransientRBParamSubdomainTree TransientRBParamSubdomainTree& trans_tree = libmesh_cast_ref<TransientRBParamSubdomainTree&>(_tree); if(c == LEFT) { if(left_child != NULL) { std::cout << "Error: Child already exists!" << std::endl; libmesh_error(); } else { // Allocate a new child node left_child = new TransientRBParamSubdomainNode(trans_tree, new_anchor); } } if(c == RIGHT) { if(right_child != NULL) { std::cout << "Error: Child already exists!" << std::endl; libmesh_error(); } else { // Allocate a new child node right_child = new TransientRBParamSubdomainNode(trans_tree, new_anchor); } } STOP_LOG("add_child()", "TransientRBParamSubdomainNode"); } void TransientRBParamSubdomainNode::hp_greedy() { _rb_system.clear_basis_function_dependent_data(); // Load the (full or subsampled) training set if(_tree.n_subsampled_training_points >= n_global_training_parameters()) { _rb_system.load_training_set( training_set ); } else { std::vector< std::vector<Number> > subsampled_training_set = get_subsampled_training_set(); _rb_system.load_training_set( subsampled_training_set ); } _rb_system.set_current_parameters( this->anchor ); _rb_system.set_training_tolerance(_tree.h_tol); Real greedy_bound; // These casts have to succeed TransientRBParamSubdomainTree& trans_tree = libmesh_cast_ref<TransientRBParamSubdomainTree&>(_tree); TransientRBSystem& trans_rb = libmesh_cast_ref<TransientRBSystem&>(_rb_system); // Set the maximum number of truth solves to N_bar in the time-dependent case trans_rb.set_max_truth_solves(_tree.N_bar); if (!trans_tree.use_delta_N_in_h_stage) { trans_rb.set_POD_tol(_tree.h_tol/trans_tree.conserv_factor); } else { trans_rb.set_POD_tol(-1.); } // delta_N might be changed in basis training in the transient case // (i.e., if we're using POD_tol, or if we hit Nmax) // hence we save and reload delta_N unsigned int saved_delta_N = trans_rb.get_delta_N(); greedy_bound = trans_rb.train_reduced_basis(); // Reload delta_N trans_rb.set_delta_N(saved_delta_N); trans_rb.set_current_parameters(this->anchor); Real RB_error = trans_rb.RB_solve(trans_rb.get_n_basis_functions()); if (RB_error > _tree.h_tol/trans_tree.conserv_factor) { std::cout << "Error: The h-tolerance was not satisfied at the " << "anchor point hence h-type refinement may not converge." << std::endl; libmesh_error(); } if ( greedy_bound > _tree.h_tol) // recursive call to hp_greedy { std::cout << "h tolerance not satisfied, splitting subdomain..." << std::endl; split_this_subdomain(true); left_child->hp_greedy(); right_child->hp_greedy(); } else // terminate branch, populate the model with standard p-type,write out subelement data { std::cout << "h tolerance satisfied, performing p-refinement..." << std::endl; greedy_bound = perform_p_stage(greedy_bound); if (greedy_bound > _tree.p_tol) { std::cout << "p tolerance not satisfied, splitting subdomain..." << std::endl; split_this_subdomain(false); left_child->hp_greedy(); right_child->hp_greedy(); } else { std::cout << "p tolerance satisfied, subdomain " << _tree.leaf_node_index << " is a leaf node..." << std::endl; // Finally, write out the data for this subdomain write_subdomain_data_to_files(); _tree.leaf_node_index++; } } } Real TransientRBParamSubdomainNode::perform_p_stage(Real greedy_bound) { START_LOG("perform_p_stage()", "TransientRBParamSubdomainNode"); // Continue the greedy process on this subdomain, i.e. // we do not discard the basis functions generated for // this subdomain in the h-refinement phase _rb_system.set_training_tolerance(_tree.p_tol); TransientRBSystem& trans_rb = libmesh_cast_ref<TransientRBSystem&>(_rb_system); // Ignore max_truth_solves and POD-tol in the p-stage trans_rb.set_POD_tol(-1.); trans_rb.set_max_truth_solves(-1); // Clear the reduced basis and reinitialize the greedy to the anchor point trans_rb.clear_basis_function_dependent_data(); trans_rb.set_current_parameters( this->anchor ); // Checking if p-tol is already satisfied or Nmax has been reached // if not do another (standard) greedy if ( (greedy_bound > _tree.p_tol) || (_rb_system.get_n_basis_functions() < _rb_system.get_Nmax()) ) { greedy_bound = _rb_system.train_reduced_basis(); } STOP_LOG("perform_p_stage()", "TransientRBParamSubdomainNode"); return greedy_bound; } void TransientRBParamSubdomainNode::split_this_subdomain(bool h_stage_split) { START_LOG("split_this_subdomain()", "TransientRBParamSubdomainNode"); // These first few lines are the same as RBParamSubdomainNode::split_this_subdomain this->add_child( _rb_system.get_greedy_parameter(0), RBParamSubdomainNode::LEFT); this->add_child( _rb_system.get_greedy_parameter(1), RBParamSubdomainNode::RIGHT); // Compute distance between the children anchor points, and pass to children (JLE 2010-09-16) Real distance_between_children_anchors = 0.; for (unsigned int i = 0; i < left_child->anchor.size(); i++) { distance_between_children_anchors += std::pow((left_child->anchor[i] - right_child->anchor[i]),Real(2.)); } distance_between_children_anchors = std::sqrt(distance_between_children_anchors); left_child->distance_between_anchors = distance_between_children_anchors; right_child->distance_between_anchors = distance_between_children_anchors; // We now need some code specific to the transient case because it // is possible that we have repeated selection of training points // in the transient case (due to the POD-Greedy) and hence we // may have distance_between_children_anchors == 0. bool anchors_are_equal = (distance_between_children_anchors == 0.); if (h_stage_split) { if (anchors_are_equal) { std::cout << "Error: Anchor points for children are equal!" << std::endl; libmesh_error(); } } else { if (anchors_are_equal) { for (unsigned int i=2; i< _rb_system.greedy_param_list.size() ; i++) { bool parameters_are_equal = true; for (unsigned int j = 0; j < left_child->anchor.size(); j++) { parameters_are_equal = ( parameters_are_equal && (left_child->anchor[j] == _rb_system.get_greedy_parameter(i)[j])); } if (!parameters_are_equal) { right_child->anchor = _rb_system.get_greedy_parameter(i); anchors_are_equal = false; break; } } // anchors_are_equal has been updated, check if we have found different point. if(anchors_are_equal) { std::cout << "Error: Unable to find distinct anchors in additional splitting step." << std::endl; libmesh_error(); } } } this->initialize_child_training_sets(); STOP_LOG("split_this_subdomain()", "TransientRBParamSubdomainNode"); } } // namespace libMesh <|endoftext|>
<commit_before>/** * Open[Flex] Board View * * Copyright chloridite 2016 * Copyright inflex 2016 (Paul Daniels) * * Git Fork: https://github.com/inflex/OpenBoardView * */ #include "BoardView.h" #include "imgui_impl_dx9.h" #include <d3d9.h> #define DIRECTINPUT_VERSION 0x0800 #include "platform.h" #include "confparse.h" #include "crtdbg.h" #include "resource.h" #include <dinput.h> #include <direct.h> #include <shlwapi.h> #include <tchar.h> // Data static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; static D3DPRESENT_PARAMETERS g_d3dpp; // local functions #ifndef S_ISDIR #define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) #endif uint32_t byte4swap(uint32_t x) { /* * used to convert RGBA -> ABGR etc */ return (((x & 0x000000ff) << 24) | ((x & 0x0000ff00) << 8) | ((x & 0x00ff0000) >> 8) | ((x & 0xff000000) >> 24)); } extern LRESULT ImGui_ImplDX9_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplDX9_WndProcHandler(hWnd, msg, wParam, lParam)) return true; switch (msg) { case WM_SIZE: if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) { ImGui_ImplDX9_InvalidateDeviceObjects(); g_d3dpp.BackBufferWidth = LOWORD(lParam); g_d3dpp.BackBufferHeight = HIWORD(lParam); HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp); if (hr == D3DERR_INVALIDCALL) IM_ASSERT(0); ImGui_ImplDX9_CreateDeviceObjects(); } return 0; case WM_SYSCOMMAND: if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu return 0; break; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wParam, lParam); } int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Initialize comctl CoInitializeEx(NULL, COINIT_MULTITHREADED); char ss[1025]; char *homepath; int err; size_t hpsz; // Confparse obvconfig; int sizex, sizey; bool use_exepath = false; bool use_homepath = true; BoardView app{}; CHAR history_file[MAX_PATH]; CHAR conf_file[MAX_PATH]; static const wchar_t *class_name = L"Openflex Board View"; /* * To make OBV very easy to use and transportable among windows * users, one method is to just make it do all its business in the * folder that the EXE is launched from. It's not "proper" but * it is very simple and it works. */ HMODULE hModule = GetModuleHandleA(NULL); CHAR exepath[MAX_PATH]; GetModuleFileNameA(hModule, exepath, MAX_PATH); /* * Trim off the filename at the end of the path */ int l = strlen(exepath); while (--l) { if (exepath[l] == '\\') { exepath[l] = '\0'; break; } } snprintf(history_file, sizeof(history_file), "%s\\obv.history", exepath); snprintf(conf_file, sizeof(conf_file), "%s\\obv.conf", exepath); /* * Next, we check to see if there's an APPDATA folder that's * already setup with our name on it. This will be the case * if OBV has been 'installed', even via the simple install.bat * script. */ err = _dupenv_s(&homepath, &hpsz, "APPDATA"); if (homepath) { struct stat st; int sr; snprintf(ss, sizeof(ss), "%s/openboardview", homepath); sr = stat(ss, &st); if (sr == -1) { //_mkdir(ss); // sr = stat(ss, &st); } else { snprintf(history_file, sizeof(history_file), "%s\\obv.history", homepath); snprintf(conf_file, sizeof(conf_file), "%s\\obv.conf", homepath); } } // Create application window HINSTANCE instance = GetModuleHandle(NULL); HICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1)); WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, instance, icon, NULL, NULL, NULL, class_name, NULL}; RegisterClassEx(&wc); app.obvconfig.Load(conf_file); sizex = app.obvconfig.ParseInt("windowX", 900); sizey = app.obvconfig.ParseInt("windowY", 600); HWND hwnd = CreateWindow(class_name, _T("Openflex Board Viewer"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, sizex, sizey, NULL, NULL, wc.hInstance, NULL); // Initialize Direct3D LPDIRECT3D9 pD3D; if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) { UnregisterClass(class_name, wc.hInstance); return 0; } ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); g_d3dpp.Windowed = TRUE; g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; g_d3dpp.EnableAutoDepthStencil = TRUE; g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Create the D3DDevice if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) { pD3D->Release(); UnregisterClass(class_name, wc.hInstance); return 0; } // Setup ImGui binding ImGui_ImplDX9_Init(hwnd, g_pd3dDevice); // Load Fonts // (there is a default font, this is only if you want to change it. see // extra_fonts/README.txt // for more details) ImGuiIO &io = ImGui::GetIO(); io.IniFilename = NULL; int ttf_size; unsigned char *ttf_data = LoadAsset(&ttf_size, ASSET_FIRA_SANS); ImFontConfig font_cfg{}; font_cfg.FontDataOwnedByAtlas = false; io.Fonts->AddFontFromMemoryTTF(ttf_data, ttf_size, app.obvconfig.ParseDouble("fontSize", 20.0f), &font_cfg); /* * Load the existing file loaded history */ if (history_file[0] != '\0') { app.fhistory.Set_filename(history_file); app.fhistory.Load(); } /* * Parse the settings in the configuration file * * There are some settings which have been parsed * earlier but they apply to the startup of the * main, as opposed to OBV itself. This call * parses all the things that'll influence OBV */ app.ConfigParse(); bool show_test_window = true; bool show_another_window = false; ImVec4 clear_col = ImColor(app.m_colors.backgroundColor); // Main loop MSG msg; ZeroMemory(&msg, sizeof(msg)); ShowWindow(hwnd, SW_SHOWDEFAULT); UpdateWindow(hwnd); while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); continue; } ImGui_ImplDX9_NewFrame(); app.Update(); if (app.m_wantsQuit) { PostMessage(hwnd, WM_QUIT, 0, 0); } // Rendering g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false); D3DCOLOR clear_col_dx = D3DCOLOR_RGBA( (int)(clear_col.x * 255.0f), (int)(clear_col.y * 255.0f), (int)(clear_col.z * 255.0f), (int)(clear_col.w * 255.0f)); g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); if (g_pd3dDevice->BeginScene() >= 0) { ImGui::Render(); g_pd3dDevice->EndScene(); } g_pd3dDevice->Present(NULL, NULL, NULL, NULL); } ImGui_ImplDX9_Shutdown(); if (g_pd3dDevice) g_pd3dDevice->Release(); if (pD3D) pD3D->Release(); UnregisterClass(class_name, wc.hInstance); return 0; } <commit_msg>Windows dpi font setup<commit_after>/** * Open[Flex] Board View * * Copyright chloridite 2016 * Copyright inflex 2016 (Paul Daniels) * * Git Fork: https://github.com/inflex/OpenBoardView * */ #include "BoardView.h" #include "imgui_impl_dx9.h" #include <d3d9.h> #define DIRECTINPUT_VERSION 0x0800 #include "platform.h" #include "confparse.h" #include "crtdbg.h" #include "resource.h" #include <dinput.h> #include <direct.h> #include <shlwapi.h> #include <tchar.h> // Data static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; static D3DPRESENT_PARAMETERS g_d3dpp; // local functions #ifndef S_ISDIR #define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) #endif uint32_t byte4swap(uint32_t x) { /* * used to convert RGBA -> ABGR etc */ return (((x & 0x000000ff) << 24) | ((x & 0x0000ff00) << 8) | ((x & 0x00ff0000) >> 8) | ((x & 0xff000000) >> 24)); } extern LRESULT ImGui_ImplDX9_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplDX9_WndProcHandler(hWnd, msg, wParam, lParam)) return true; switch (msg) { case WM_SIZE: if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) { ImGui_ImplDX9_InvalidateDeviceObjects(); g_d3dpp.BackBufferWidth = LOWORD(lParam); g_d3dpp.BackBufferHeight = HIWORD(lParam); HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp); if (hr == D3DERR_INVALIDCALL) IM_ASSERT(0); ImGui_ImplDX9_CreateDeviceObjects(); } return 0; case WM_SYSCOMMAND: if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu return 0; break; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wParam, lParam); } int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Initialize comctl CoInitializeEx(NULL, COINIT_MULTITHREADED); char ss[1025]; char *homepath; int err; size_t hpsz; // Confparse obvconfig; int sizex, sizey; bool use_exepath = false; bool use_homepath = true; BoardView app{}; CHAR history_file[MAX_PATH]; CHAR conf_file[MAX_PATH]; static const wchar_t *class_name = L"Openflex Board View"; /* * To make OBV very easy to use and transportable among windows * users, one method is to just make it do all its business in the * folder that the EXE is launched from. It's not "proper" but * it is very simple and it works. */ HMODULE hModule = GetModuleHandleA(NULL); CHAR exepath[MAX_PATH]; GetModuleFileNameA(hModule, exepath, MAX_PATH); /* * Trim off the filename at the end of the path */ int l = strlen(exepath); while (--l) { if (exepath[l] == '\\') { exepath[l] = '\0'; break; } } snprintf(history_file, sizeof(history_file), "%s\\obv.history", exepath); snprintf(conf_file, sizeof(conf_file), "%s\\obv.conf", exepath); /* * Next, we check to see if there's an APPDATA folder that's * already setup with our name on it. This will be the case * if OBV has been 'installed', even via the simple install.bat * script. */ err = _dupenv_s(&homepath, &hpsz, "APPDATA"); if (homepath) { struct stat st; int sr; snprintf(ss, sizeof(ss), "%s/openboardview", homepath); sr = stat(ss, &st); if (sr == -1) { //_mkdir(ss); // sr = stat(ss, &st); } else { snprintf(history_file, sizeof(history_file), "%s\\obv.history", homepath); snprintf(conf_file, sizeof(conf_file), "%s\\obv.conf", homepath); } } // Create application window HINSTANCE instance = GetModuleHandle(NULL); HICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1)); WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, instance, icon, NULL, NULL, NULL, class_name, NULL}; RegisterClassEx(&wc); app.obvconfig.Load(conf_file); sizex = app.obvconfig.ParseInt("windowX", 900); sizey = app.obvconfig.ParseInt("windowY", 600); HWND hwnd = CreateWindow(class_name, _T("Openflex Board Viewer"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, sizex, sizey, NULL, NULL, wc.hInstance, NULL); // Initialize Direct3D LPDIRECT3D9 pD3D; if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) { UnregisterClass(class_name, wc.hInstance); return 0; } ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); g_d3dpp.Windowed = TRUE; g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; g_d3dpp.EnableAutoDepthStencil = TRUE; g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Create the D3DDevice if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) { pD3D->Release(); UnregisterClass(class_name, wc.hInstance); return 0; } // Setup ImGui binding ImGui_ImplDX9_Init(hwnd, g_pd3dDevice); // Load Fonts // (there is a default font, this is only if you want to change it. see // extra_fonts/README.txt // for more details) ImGuiIO &io = ImGui::GetIO(); io.IniFilename = NULL; /* * Load the existing file loaded history */ if (history_file[0] != '\0') { app.fhistory.Set_filename(history_file); app.fhistory.Load(); } /* * Parse the settings in the configuration file * * There are some settings which have been parsed * earlier but they apply to the startup of the * main, as opposed to OBV itself. This call * parses all the things that'll influence OBV */ app.ConfigParse(); /* * Set the font based on the dpi */ int ttf_size; unsigned char *ttf_data = LoadAsset(&ttf_size, ASSET_FIRA_SANS); ImFontConfig font_cfg{}; font_cfg.FontDataOwnedByAtlas = false; io.Fonts->AddFontFromMemoryTTF(ttf_data, ttf_size, app.obvconfig.ParseDouble("fontSize", 20.0f * (app.dpi / 100.0)), &font_cfg); bool show_test_window = true; bool show_another_window = false; ImVec4 clear_col = ImColor(app.m_colors.backgroundColor); // Main loop MSG msg; ZeroMemory(&msg, sizeof(msg)); ShowWindow(hwnd, SW_SHOWDEFAULT); UpdateWindow(hwnd); while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); continue; } ImGui_ImplDX9_NewFrame(); app.Update(); if (app.m_wantsQuit) { PostMessage(hwnd, WM_QUIT, 0, 0); } // Rendering g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false); D3DCOLOR clear_col_dx = D3DCOLOR_RGBA( (int)(clear_col.x * 255.0f), (int)(clear_col.y * 255.0f), (int)(clear_col.z * 255.0f), (int)(clear_col.w * 255.0f)); g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); if (g_pd3dDevice->BeginScene() >= 0) { ImGui::Render(); g_pd3dDevice->EndScene(); } g_pd3dDevice->Present(NULL, NULL, NULL, NULL); } ImGui_ImplDX9_Shutdown(); if (g_pd3dDevice) g_pd3dDevice->Release(); if (pD3D) pD3D->Release(); UnregisterClass(class_name, wc.hInstance); return 0; } <|endoftext|>
<commit_before>#include <math.h> #include "angort.h" #define FN(f) a->pushFloat(f(a->popFloat())) %name stdmath %word cos (x -- cos x) { FN(cosf); } %word sin (x -- sin x) { FN(sinf); } %word tan (x -- tan x) { FN(tanf); } %word ln (x -- ln x) { FN(logf); } %word log (x -- ln x) { FN(log10f); } %word log2 (x -- log2 x) { FN(log2f); } %word sqrt (x -- sqrt x) { FN(sqrtf); } <commit_msg>added exp to math<commit_after>#include <math.h> #include "angort.h" /* * Mappings for (some) standard maths library functions */ // macro for helping generate unary float functions #define FN(f) a->pushFloat(f(a->popFloat())) %name stdmath %word cos (x -- cos x) { FN(cosf); } %word sin (x -- sin x) { FN(sinf); } %word tan (x -- tan x) { FN(tanf); } %word ln (x -- ln x) { FN(logf); } %word log (x -- ln x) { FN(log10f); } %word log2 (x -- log2 x) { FN(log2f); } %word sqrt (x -- sqrt x) { FN(sqrtf); } %word exp (x -- exp x) { FN(exp); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include <time.h> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("BitBar"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "32a928e" # define GIT_COMMIT_DATE __DATE__ //# define GIT_COMMIT_DATE "Apr 15 2016" // when cross compiling for windows, the commit date shows // in the rpcconsole build date as "$Format:%cD" time_t t=time(NULL); struct tm *tm=localtime(&t); // #define GIT_COMMIT_DATE asctime(tm) #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Marked for release<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include <time.h> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("BitBar"); // Client version number //#define CLIENT_VERSION_SUFFIX "-beta" #define CLIENT_VERSION_SUFFIX "-release" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "32a928e" # define GIT_COMMIT_DATE __DATE__ //# define GIT_COMMIT_DATE "Apr 15 2016" // when cross compiling for windows, the commit date shows // in the rpcconsole build date as "$Format:%cD" time_t t=time(NULL); struct tm *tm=localtime(&t); // #define GIT_COMMIT_DATE asctime(tm) #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>/* This file is part of Android File Transfer For Linux. Copyright (C) 2015-2018 Vladimir Menshakov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <usb/BufferAllocator.h> #include <usb/Device.h> #include <Exception.h> #include <mtp/usb/TimeoutException.h> #include <mtp/usb/DeviceBusyException.h> #include <mtp/usb/DeviceNotFoundException.h> #include <mtp/ByteArray.h> #include <mtp/log.h> #include <sys/ioctl.h> #include <sys/time.h> #include <poll.h> #include <signal.h> #include "linux/usbdevice_fs.h" #define IOCTL(FD, ...) do \ { \ int r = ioctl(FD, __VA_ARGS__); \ if (r < 0) \ { \ if (errno == EBUSY) \ throw DeviceBusyException(FD); \ else if (errno == ENODEV) \ throw DeviceNotFoundException(); \ else \ throw posix::Exception("ioctl(" #__VA_ARGS__ ")"); \ } \ } while(false) namespace mtp { namespace usb { InterfaceToken::InterfaceToken(int fd, unsigned interfaceNumber): _fd(fd), _interfaceNumber(interfaceNumber) { IOCTL(_fd, USBDEVFS_CLAIMINTERFACE, &interfaceNumber); } InterfaceToken::~InterfaceToken() { ioctl(_fd, USBDEVFS_RELEASEINTERFACE, &_interfaceNumber); } #define PRINT_CAP(CAP, NAME) \ if (capabilities & (CAP)) \ { \ debug(NAME " "); \ capabilities &= ~(CAP); \ } Device::Device(int fd, const EndpointPtr &controlEp): _fd(fd), _capabilities(0), _controlEp(controlEp) { try { IOCTL(_fd.Get(), USBDEVFS_RESET); } catch(const std::exception &ex) { error("resetting device failed: ", ex.what()); } try { IOCTL(_fd.Get(), USBDEVFS_GET_CAPABILITIES, &_capabilities); } catch(const std::exception &ex) { error("get usbfs capabilities failed: ", ex.what()); } debug("capabilities = 0x", hex(_capabilities, 8)); bool mmap = _capabilities & USBDEVFS_CAP_MMAP; //disable mmap allocation for now, see https://github.com/whoozle/android-file-transfer-linux/issues/194 #if 1 mmap = false; #endif _bufferAllocator = std::make_shared<BufferAllocator>(mmap? fd: -1); if (_capabilities) { u32 capabilities = _capabilities; PRINT_CAP(USBDEVFS_CAP_ZERO_PACKET, "<zero-packet>"); PRINT_CAP(USBDEVFS_CAP_BULK_CONTINUATION, "<bulk-continuation>"); PRINT_CAP(USBDEVFS_CAP_NO_PACKET_SIZE_LIM, "<no-packet-size-limit>"); PRINT_CAP(USBDEVFS_CAP_BULK_SCATTER_GATHER, "<bulk-scatter-gather>"); PRINT_CAP(USBDEVFS_CAP_REAP_AFTER_DISCONNECT, "<reap-after-disconnect>"); PRINT_CAP(USBDEVFS_CAP_MMAP, "<mmap>"); PRINT_CAP(USBDEVFS_CAP_DROP_PRIVILEGES, "<drop-privileges>"); if (capabilities) debug("<unknown capability 0x", hex(capabilities, 2), ">"); } else debug("[none]\n"); } Device::~Device() { } int Device::GetConfiguration() const { return 0; } void Device::SetConfiguration(int idx) { error("SetConfiguration(", idx, "): not implemented"); } struct Device::Urb : usbdevfs_urb, Noncopyable { static const int MaxBufferSize = 4096; BufferAllocator & Allocator; int Fd; int PacketSize; Buffer DataBuffer; Urb(BufferAllocator & allocator, int fd, u8 urbType, const EndpointPtr & ep): usbdevfs_urb(), Allocator(allocator), Fd(fd), PacketSize(ep->GetMaxPacketSize()), DataBuffer(Allocator.Allocate(std::max(PacketSize, MaxBufferSize / PacketSize * PacketSize))) { type = urbType; endpoint = ep->GetAddress(); buffer = DataBuffer.GetData(); buffer_length = DataBuffer.GetSize(); } usbdevfs_urb *GetKernelUrb() { return static_cast<usbdevfs_urb *>(this); } ~Urb() { Allocator.Free(DataBuffer); } size_t GetTransferSize() const { return DataBuffer.GetSize(); } void Submit() { IOCTL(Fd, USBDEVFS_SUBMITURB, GetKernelUrb()); } void Discard() { int r = ioctl(Fd, USBDEVFS_DISCARDURB, GetKernelUrb()); if (r != 0) { perror("ioctl(USBDEVFS_DISCARDURB)"); } } size_t Send(const IObjectInputStreamPtr &inputStream, size_t size) { if (size > DataBuffer.GetSize()) throw std::logic_error("invalid size passed to Send"); auto data = DataBuffer.GetData(); size_t r = inputStream->Read(data, size); //HexDump("write", ByteArray(data, data + r), true); buffer_length = r; return r; } size_t Send(const ByteArray &inputData) { size_t r = std::min(DataBuffer.GetSize(), inputData.size()); std::copy(inputData.data(), inputData.data() + r, DataBuffer.GetData()); buffer_length = r; return r; } size_t Recv(const IObjectOutputStreamPtr &outputStream) { auto data = DataBuffer.GetData(); //HexDump("read", ByteArray(data, data + actual_length), true); return outputStream->Write(data, actual_length); } template<unsigned Flag> void SetFlag(bool value) { if (value) flags |= Flag; else flags &= ~Flag; } void SetContinuationFlag(bool continuation) { SetFlag<USBDEVFS_URB_BULK_CONTINUATION>(continuation); } void SetZeroPacketFlag(bool zero) { SetFlag<USBDEVFS_URB_ZERO_PACKET>(zero); } }; void * Device::Reap(int timeout) { auto urb = AsyncReap(); //attempt to pick up old urbs if (urb) return urb; timeval started = {}; if (gettimeofday(&started, NULL) == -1) throw posix::Exception("gettimeofday"); pollfd fd = {}; fd.fd = _fd.Get(); fd.events = POLLOUT | POLLWRNORM; int r = poll(&fd, 1, timeout); timeval now = {}; if (gettimeofday(&now, NULL) == -1) throw posix::Exception("gettimeofday"); if (r < 0) throw posix::Exception("poll"); if (r == 0 && timeout > 0) { int ms = (now.tv_sec - started.tv_sec) * 1000 + (now.tv_usec - started.tv_usec) / 1000; error(ms, " ms since the last poll call"); } urb = AsyncReap(); if (urb) return urb; else throw TimeoutException("timeout reaping usb urb"); } void * Device::AsyncReap() { usbdevfs_urb *urb; int r = ioctl(_fd.Get(), USBDEVFS_REAPURBNDELAY, &urb); if (r == 0) return urb; else if (errno == EAGAIN) return nullptr; else throw posix::Exception("ioctl(USBDEVFS_REAPURBNDELAY)"); } void Device::ClearHalt(const EndpointPtr & ep) { try { unsigned index = ep->GetAddress(); IOCTL(_fd.Get(), USBDEVFS_CLEAR_HALT, &index); } catch(const std::exception &ex) { error("clearing halt status for ep ", hex(ep->GetAddress(), 2), ": ", ex.what()); } } void Device::Submit(Urb *urb, int timeout) { urb->Submit(); try { while(true) { usbdevfs_urb * completedKernelUrb = static_cast<usbdevfs_urb *>(Reap(timeout)); if (urb->GetKernelUrb() != completedKernelUrb) { error("got unknown urb: ", completedKernelUrb); continue; } else break; } } catch(const TimeoutException &ex) { urb->Discard(); throw; } catch(const std::exception &ex) { error("error while submitting urb: ", ex.what()); urb->Discard(); throw; } } void Device::WriteBulk(const EndpointPtr & ep, const IObjectInputStreamPtr &inputStream, int timeout) { Urb urb(*_bufferAllocator, _fd.Get(), USBDEVFS_URB_TYPE_BULK, ep); size_t transferSize = urb.GetTransferSize(); size_t r; bool continuation = false; do { r = urb.Send(inputStream, transferSize); if (_capabilities & USBDEVFS_CAP_ZERO_PACKET) urb.SetZeroPacketFlag(r != transferSize); if (_capabilities & USBDEVFS_CAP_BULK_CONTINUATION) { urb.SetContinuationFlag(continuation); continuation = true; } Submit(&urb, timeout); } while(r == transferSize); } void Device::ReadBulk(const EndpointPtr & ep, const IObjectOutputStreamPtr &outputStream, int timeout) { Urb urb(*_bufferAllocator, _fd.Get(), USBDEVFS_URB_TYPE_BULK, ep); size_t transferSize = urb.GetTransferSize(); size_t r; bool continuation = false; do { if (_capabilities & USBDEVFS_CAP_BULK_CONTINUATION) { urb.SetContinuationFlag(continuation); continuation = true; } Submit(&urb, timeout); r = urb.Recv(outputStream); } while(r == transferSize); } u8 Device::TransactionType(const EndpointPtr &ep) { EndpointType type = ep->GetType(); switch(type) { case EndpointType::Control: return USBDEVFS_URB_TYPE_CONTROL; case EndpointType::Isochronous: return USBDEVFS_URB_TYPE_ISO; case EndpointType::Bulk: return USBDEVFS_URB_TYPE_BULK; case EndpointType::Interrupt: return USBDEVFS_URB_TYPE_INTERRUPT; default: throw std::runtime_error("invalid endpoint type"); } } void Device::ReadControl(u8 type, u8 req, u16 value, u16 index, ByteArray &data, int timeout) { debug("read control ", hex(type, 2), " ", hex(req, 2), " ", hex(value, 4), " ", hex(index, 4)); usbdevfs_ctrltransfer ctrl = { }; ctrl.bRequestType = type; ctrl.bRequest = req; ctrl.wValue = value; ctrl.wIndex = index; ctrl.wLength = data.size(); ctrl.data = const_cast<u8 *>(data.data()); ctrl.timeout = timeout; int fd = _fd.Get(); int r = ioctl(fd, USBDEVFS_CONTROL, &ctrl); if (r >= 0) data.resize(r); else if (errno == EAGAIN) throw TimeoutException("timeout sending control transfer"); else throw posix::Exception("ioctl"); } void Device::WriteControl(u8 type, u8 req, u16 value, u16 index, const ByteArray &data, int timeout) { debug("write control ", hex(type, 2), " ", hex(req, 2), " ", hex(value, 4), " ", hex(index, 4)); usbdevfs_ctrltransfer ctrl = { }; ctrl.bRequestType = type; ctrl.bRequest = req; ctrl.wValue = value; ctrl.wIndex = index; ctrl.wLength = data.size(); ctrl.data = const_cast<u8 *>(data.data()); ctrl.timeout = timeout; int fd = _fd.Get(); int r = ioctl(fd, USBDEVFS_CONTROL, &ctrl); if (r >= 0) return; else if (errno == EAGAIN) throw TimeoutException("timeout sending control transfer"); else throw posix::Exception("ioctl"); } }} <commit_msg>call gettimeofday after exception being thrown<commit_after>/* This file is part of Android File Transfer For Linux. Copyright (C) 2015-2018 Vladimir Menshakov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <usb/BufferAllocator.h> #include <usb/Device.h> #include <Exception.h> #include <mtp/usb/TimeoutException.h> #include <mtp/usb/DeviceBusyException.h> #include <mtp/usb/DeviceNotFoundException.h> #include <mtp/ByteArray.h> #include <mtp/log.h> #include <sys/ioctl.h> #include <sys/time.h> #include <poll.h> #include <signal.h> #include "linux/usbdevice_fs.h" #define IOCTL(FD, ...) do \ { \ int r = ioctl(FD, __VA_ARGS__); \ if (r < 0) \ { \ if (errno == EBUSY) \ throw DeviceBusyException(FD); \ else if (errno == ENODEV) \ throw DeviceNotFoundException(); \ else \ throw posix::Exception("ioctl(" #__VA_ARGS__ ")"); \ } \ } while(false) namespace mtp { namespace usb { InterfaceToken::InterfaceToken(int fd, unsigned interfaceNumber): _fd(fd), _interfaceNumber(interfaceNumber) { IOCTL(_fd, USBDEVFS_CLAIMINTERFACE, &interfaceNumber); } InterfaceToken::~InterfaceToken() { ioctl(_fd, USBDEVFS_RELEASEINTERFACE, &_interfaceNumber); } #define PRINT_CAP(CAP, NAME) \ if (capabilities & (CAP)) \ { \ debug(NAME " "); \ capabilities &= ~(CAP); \ } Device::Device(int fd, const EndpointPtr &controlEp): _fd(fd), _capabilities(0), _controlEp(controlEp) { try { IOCTL(_fd.Get(), USBDEVFS_RESET); } catch(const std::exception &ex) { error("resetting device failed: ", ex.what()); } try { IOCTL(_fd.Get(), USBDEVFS_GET_CAPABILITIES, &_capabilities); } catch(const std::exception &ex) { error("get usbfs capabilities failed: ", ex.what()); } debug("capabilities = 0x", hex(_capabilities, 8)); bool mmap = _capabilities & USBDEVFS_CAP_MMAP; //disable mmap allocation for now, see https://github.com/whoozle/android-file-transfer-linux/issues/194 #if 1 mmap = false; #endif _bufferAllocator = std::make_shared<BufferAllocator>(mmap? fd: -1); if (_capabilities) { u32 capabilities = _capabilities; PRINT_CAP(USBDEVFS_CAP_ZERO_PACKET, "<zero-packet>"); PRINT_CAP(USBDEVFS_CAP_BULK_CONTINUATION, "<bulk-continuation>"); PRINT_CAP(USBDEVFS_CAP_NO_PACKET_SIZE_LIM, "<no-packet-size-limit>"); PRINT_CAP(USBDEVFS_CAP_BULK_SCATTER_GATHER, "<bulk-scatter-gather>"); PRINT_CAP(USBDEVFS_CAP_REAP_AFTER_DISCONNECT, "<reap-after-disconnect>"); PRINT_CAP(USBDEVFS_CAP_MMAP, "<mmap>"); PRINT_CAP(USBDEVFS_CAP_DROP_PRIVILEGES, "<drop-privileges>"); if (capabilities) debug("<unknown capability 0x", hex(capabilities, 2), ">"); } else debug("[none]\n"); } Device::~Device() { } int Device::GetConfiguration() const { return 0; } void Device::SetConfiguration(int idx) { error("SetConfiguration(", idx, "): not implemented"); } struct Device::Urb : usbdevfs_urb, Noncopyable { static const int MaxBufferSize = 4096; BufferAllocator & Allocator; int Fd; int PacketSize; Buffer DataBuffer; Urb(BufferAllocator & allocator, int fd, u8 urbType, const EndpointPtr & ep): usbdevfs_urb(), Allocator(allocator), Fd(fd), PacketSize(ep->GetMaxPacketSize()), DataBuffer(Allocator.Allocate(std::max(PacketSize, MaxBufferSize / PacketSize * PacketSize))) { type = urbType; endpoint = ep->GetAddress(); buffer = DataBuffer.GetData(); buffer_length = DataBuffer.GetSize(); } usbdevfs_urb *GetKernelUrb() { return static_cast<usbdevfs_urb *>(this); } ~Urb() { Allocator.Free(DataBuffer); } size_t GetTransferSize() const { return DataBuffer.GetSize(); } void Submit() { IOCTL(Fd, USBDEVFS_SUBMITURB, GetKernelUrb()); } void Discard() { int r = ioctl(Fd, USBDEVFS_DISCARDURB, GetKernelUrb()); if (r != 0) { perror("ioctl(USBDEVFS_DISCARDURB)"); } } size_t Send(const IObjectInputStreamPtr &inputStream, size_t size) { if (size > DataBuffer.GetSize()) throw std::logic_error("invalid size passed to Send"); auto data = DataBuffer.GetData(); size_t r = inputStream->Read(data, size); //HexDump("write", ByteArray(data, data + r), true); buffer_length = r; return r; } size_t Send(const ByteArray &inputData) { size_t r = std::min(DataBuffer.GetSize(), inputData.size()); std::copy(inputData.data(), inputData.data() + r, DataBuffer.GetData()); buffer_length = r; return r; } size_t Recv(const IObjectOutputStreamPtr &outputStream) { auto data = DataBuffer.GetData(); //HexDump("read", ByteArray(data, data + actual_length), true); return outputStream->Write(data, actual_length); } template<unsigned Flag> void SetFlag(bool value) { if (value) flags |= Flag; else flags &= ~Flag; } void SetContinuationFlag(bool continuation) { SetFlag<USBDEVFS_URB_BULK_CONTINUATION>(continuation); } void SetZeroPacketFlag(bool zero) { SetFlag<USBDEVFS_URB_ZERO_PACKET>(zero); } }; void * Device::Reap(int timeout) { auto urb = AsyncReap(); //attempt to pick up old urbs if (urb) return urb; timeval started = {}; if (gettimeofday(&started, NULL) == -1) throw posix::Exception("gettimeofday"); pollfd fd = {}; fd.fd = _fd.Get(); fd.events = POLLOUT | POLLWRNORM; int r = poll(&fd, 1, timeout); if (r < 0) throw posix::Exception("poll"); timeval now = {}; if (gettimeofday(&now, NULL) == -1) throw posix::Exception("gettimeofday"); if (r == 0 && timeout > 0) { int ms = (now.tv_sec - started.tv_sec) * 1000 + (now.tv_usec - started.tv_usec) / 1000; error(ms, " ms since the last poll call"); } urb = AsyncReap(); if (urb) return urb; else throw TimeoutException("timeout reaping usb urb"); } void * Device::AsyncReap() { usbdevfs_urb *urb; int r = ioctl(_fd.Get(), USBDEVFS_REAPURBNDELAY, &urb); if (r == 0) return urb; else if (errno == EAGAIN) return nullptr; else throw posix::Exception("ioctl(USBDEVFS_REAPURBNDELAY)"); } void Device::ClearHalt(const EndpointPtr & ep) { try { unsigned index = ep->GetAddress(); IOCTL(_fd.Get(), USBDEVFS_CLEAR_HALT, &index); } catch(const std::exception &ex) { error("clearing halt status for ep ", hex(ep->GetAddress(), 2), ": ", ex.what()); } } void Device::Submit(Urb *urb, int timeout) { urb->Submit(); try { while(true) { usbdevfs_urb * completedKernelUrb = static_cast<usbdevfs_urb *>(Reap(timeout)); if (urb->GetKernelUrb() != completedKernelUrb) { error("got unknown urb: ", completedKernelUrb); continue; } else break; } } catch(const TimeoutException &ex) { urb->Discard(); throw; } catch(const std::exception &ex) { error("error while submitting urb: ", ex.what()); urb->Discard(); throw; } } void Device::WriteBulk(const EndpointPtr & ep, const IObjectInputStreamPtr &inputStream, int timeout) { Urb urb(*_bufferAllocator, _fd.Get(), USBDEVFS_URB_TYPE_BULK, ep); size_t transferSize = urb.GetTransferSize(); size_t r; bool continuation = false; do { r = urb.Send(inputStream, transferSize); if (_capabilities & USBDEVFS_CAP_ZERO_PACKET) urb.SetZeroPacketFlag(r != transferSize); if (_capabilities & USBDEVFS_CAP_BULK_CONTINUATION) { urb.SetContinuationFlag(continuation); continuation = true; } Submit(&urb, timeout); } while(r == transferSize); } void Device::ReadBulk(const EndpointPtr & ep, const IObjectOutputStreamPtr &outputStream, int timeout) { Urb urb(*_bufferAllocator, _fd.Get(), USBDEVFS_URB_TYPE_BULK, ep); size_t transferSize = urb.GetTransferSize(); size_t r; bool continuation = false; do { if (_capabilities & USBDEVFS_CAP_BULK_CONTINUATION) { urb.SetContinuationFlag(continuation); continuation = true; } Submit(&urb, timeout); r = urb.Recv(outputStream); } while(r == transferSize); } u8 Device::TransactionType(const EndpointPtr &ep) { EndpointType type = ep->GetType(); switch(type) { case EndpointType::Control: return USBDEVFS_URB_TYPE_CONTROL; case EndpointType::Isochronous: return USBDEVFS_URB_TYPE_ISO; case EndpointType::Bulk: return USBDEVFS_URB_TYPE_BULK; case EndpointType::Interrupt: return USBDEVFS_URB_TYPE_INTERRUPT; default: throw std::runtime_error("invalid endpoint type"); } } void Device::ReadControl(u8 type, u8 req, u16 value, u16 index, ByteArray &data, int timeout) { debug("read control ", hex(type, 2), " ", hex(req, 2), " ", hex(value, 4), " ", hex(index, 4)); usbdevfs_ctrltransfer ctrl = { }; ctrl.bRequestType = type; ctrl.bRequest = req; ctrl.wValue = value; ctrl.wIndex = index; ctrl.wLength = data.size(); ctrl.data = const_cast<u8 *>(data.data()); ctrl.timeout = timeout; int fd = _fd.Get(); int r = ioctl(fd, USBDEVFS_CONTROL, &ctrl); if (r >= 0) data.resize(r); else if (errno == EAGAIN) throw TimeoutException("timeout sending control transfer"); else throw posix::Exception("ioctl"); } void Device::WriteControl(u8 type, u8 req, u16 value, u16 index, const ByteArray &data, int timeout) { debug("write control ", hex(type, 2), " ", hex(req, 2), " ", hex(value, 4), " ", hex(index, 4)); usbdevfs_ctrltransfer ctrl = { }; ctrl.bRequestType = type; ctrl.bRequest = req; ctrl.wValue = value; ctrl.wIndex = index; ctrl.wLength = data.size(); ctrl.data = const_cast<u8 *>(data.data()); ctrl.timeout = timeout; int fd = _fd.Get(); int r = ioctl(fd, USBDEVFS_CONTROL, &ctrl); if (r >= 0) return; else if (errno == EAGAIN) throw TimeoutException("timeout sending control transfer"); else throw posix::Exception("ioctl"); } }} <|endoftext|>
<commit_before>/* <License> Copyright 2015 Virtium Technology 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. </License> */ #include <assert.h> #include "AtaProtocolEssense1.h" #include "ProtocolAtaPassThrough.h" namespace vtStor { namespace Protocol { const vtStor::U8 FEATURE_REGISTER_OFFSET = 0; const vtStor::U8 ERROR_REGISTER_OFFSET = 0; const vtStor::U8 COUNT_REGISTER_OFFSET = 1; const vtStor::U8 LBA_LOW_REGISTER_OFFSET = 2; const vtStor::U8 LBA_MID_REGISTER_OFFSET = 3; const vtStor::U8 LBA_HIGH_REGISTER_OFFSET = 4; const vtStor::U8 DEVICE_REGISTER_OFFSET = 5; const vtStor::U8 COMMAND_REGISTER_OFFSET = 6; const vtStor::U8 STATUS_REGISTER_OFFSET = 6; const vtStor::U8 RESERVED_REGISTER_OFFSET = 7; eErrorCode cAtaPassThrough::IssueCommand( std::shared_ptr<cBufferInterface> Essense, std::shared_ptr<cBufferInterface> DataBuffer ) { eErrorCode errorCode = eErrorCode::None; cEssenseAta1 essense = cEssenseAta1::Reader( Essense ); switch (essense.GetHeader().Format) { case 1: { m_DeviceHandle = essense.GetDeviceHandle(); InitializePassThroughDirect( essense.GetCommandCharacteristics(), essense.GetTaskFileExt(), essense.GetTaskFile(), DataBuffer, 60 //TODO: allow configurable timeout ); U32 bytesReturned = 0; errorCode = IssuePassThroughDirectCommand(bytesReturned); } break; default: errorCode = eErrorCode::FormatNotSupported; break; } return(errorCode); } void cAtaPassThrough::InitializePassThroughDirect( const StorageUtility::Ata::sCommandCharacteristic& CommandCharacteristics, const StorageUtility::Ata::uTaskFileRegister& PreviousTaskFile, const StorageUtility::Ata::uTaskFileRegister& CurrentTaskFile, std::shared_ptr<cBufferInterface> DataBuffer, U32 TimeoutValueInSeconds ) { m_AtaPassThrough.Length = sizeof( ATA_PASS_THROUGH_DIRECT ); m_AtaPassThrough.DataTransferLength = CommandCharacteristics.DataTransferLengthInBytes; m_AtaPassThrough.TimeOutValue = TimeoutValueInSeconds; if (nullptr != DataBuffer) { m_AtaPassThrough.DataBuffer = DataBuffer->ToDataBuffer(); } m_AtaPassThrough.ReservedAsUchar = 0; m_AtaPassThrough.ReservedAsUlong = 0; InitializeFlags( CommandCharacteristics ); InitializeTaskFileInputRegisters( PreviousTaskFile, CurrentTaskFile ); } void cAtaPassThrough::InitializeFlags( const StorageUtility::Ata::sCommandCharacteristic& AtaCommandCharacteristic ) { // Clear all flags m_AtaPassThrough.AtaFlags = 0; if (StorageUtility::Ata::eDeviceReadyFlag::DEVICE_READY_REQUIRED == AtaCommandCharacteristic.DeviceReadyFlag) { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DRDY_REQUIRED; } switch (AtaCommandCharacteristic.DataAccess) { case StorageUtility::Ata::eDataAccess::READ_FROM_DEVICE: { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DATA_IN; } break; case StorageUtility::Ata::eDataAccess::WRITE_TO_DEVICE: { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DATA_OUT; } break; } if (StorageUtility::Ata::eFieldFormatting::COMMAND_48_BIT == AtaCommandCharacteristic.FieldFormatting) { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_48BIT_COMMAND; } if (StorageUtility::Ata::eTransferMode::DMA_PROTOCOL == AtaCommandCharacteristic.TransferMode) { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_USE_DMA; } if (StorageUtility::Ata::eMultipleMode::NOT_MULTIPLE_COMMAND == AtaCommandCharacteristic.MultipleMode) { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_NO_MULTIPLE; } } void cAtaPassThrough::InitializeTaskFileInputRegisters( const StorageUtility::Ata::uTaskFileRegister& PreviousTaskFile, const StorageUtility::Ata::uTaskFileRegister& CurrentTaskFile ) { m_AtaPassThrough.PreviousTaskFile[FEATURE_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Feature; m_AtaPassThrough.PreviousTaskFile[COUNT_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Count; m_AtaPassThrough.PreviousTaskFile[LBA_LOW_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaLow; m_AtaPassThrough.PreviousTaskFile[LBA_MID_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaMid; m_AtaPassThrough.PreviousTaskFile[LBA_HIGH_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaHigh; m_AtaPassThrough.PreviousTaskFile[DEVICE_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Device; m_AtaPassThrough.PreviousTaskFile[COMMAND_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Command; m_AtaPassThrough.PreviousTaskFile[RESERVED_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Reserved; m_AtaPassThrough.CurrentTaskFile[FEATURE_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Feature; m_AtaPassThrough.CurrentTaskFile[COUNT_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Count; m_AtaPassThrough.CurrentTaskFile[LBA_LOW_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaLow; m_AtaPassThrough.CurrentTaskFile[LBA_MID_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaMid; m_AtaPassThrough.CurrentTaskFile[LBA_HIGH_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaHigh; m_AtaPassThrough.CurrentTaskFile[DEVICE_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Device; m_AtaPassThrough.CurrentTaskFile[COMMAND_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Command; m_AtaPassThrough.CurrentTaskFile[RESERVED_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Reserved; } eErrorCode cAtaPassThrough::IssuePassThroughDirectCommand( U32& BytesReturned ) { assert( INVALID_HANDLE_VALUE != m_DeviceHandle ); eErrorCode error; error = eErrorCode::None; BOOL commandSuccessfulFlag; DWORD bytesReturned; commandSuccessfulFlag = DeviceIoControl ( m_DeviceHandle, IOCTL_ATA_PASS_THROUGH_DIRECT, &m_AtaPassThrough, m_AtaPassThrough.Length, &m_AtaPassThrough, m_AtaPassThrough.Length, &bytesReturned, NULL ); // If the operation was not successful: if (FALSE == commandSuccessfulFlag) { error = eErrorCode::Io; //TODO: report extended error //fprintf( stderr, "\nDeviceIoControl was not successful. Error Code: %d", GetLastError() ); } BytesReturned = bytesReturned; return(error); } } } VT_STOR_ATA_PROTOCOL_API void vtStorProtocolAtaPassThroughInit(std::shared_ptr<vtStor::Protocol::cProtocolInterface>& Protocol) { Protocol = std::make_shared<vtStor::Protocol::cAtaPassThrough>(); }<commit_msg>Check header of Essense before create Essense object<commit_after>/* <License> Copyright 2015 Virtium Technology 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. </License> */ #include <assert.h> #include "AtaProtocolEssense1.h" #include "ProtocolAtaPassThrough.h" namespace vtStor { namespace Protocol { const vtStor::U8 FEATURE_REGISTER_OFFSET = 0; const vtStor::U8 ERROR_REGISTER_OFFSET = 0; const vtStor::U8 COUNT_REGISTER_OFFSET = 1; const vtStor::U8 LBA_LOW_REGISTER_OFFSET = 2; const vtStor::U8 LBA_MID_REGISTER_OFFSET = 3; const vtStor::U8 LBA_HIGH_REGISTER_OFFSET = 4; const vtStor::U8 DEVICE_REGISTER_OFFSET = 5; const vtStor::U8 COMMAND_REGISTER_OFFSET = 6; const vtStor::U8 STATUS_REGISTER_OFFSET = 6; const vtStor::U8 RESERVED_REGISTER_OFFSET = 7; eErrorCode cAtaPassThrough::IssueCommand( std::shared_ptr<cBufferInterface> Essense, std::shared_ptr<cBufferInterface> DataBuffer ) { eErrorCode errorCode = eErrorCode::None; cBufferFormatter bufferFormatter = cBufferFormatter::Reader(Essense); switch (bufferFormatter.GetHeader().Format) { case 1: { cEssenseAta1 essense = cEssenseAta1::Reader(Essense); m_DeviceHandle = essense.GetDeviceHandle(); InitializePassThroughDirect( essense.GetCommandCharacteristics(), essense.GetTaskFileExt(), essense.GetTaskFile(), DataBuffer, 60 //TODO: allow configurable timeout ); U32 bytesReturned = 0; errorCode = IssuePassThroughDirectCommand(bytesReturned); } break; default: errorCode = eErrorCode::FormatNotSupported; break; } return(errorCode); } void cAtaPassThrough::InitializePassThroughDirect( const StorageUtility::Ata::sCommandCharacteristic& CommandCharacteristics, const StorageUtility::Ata::uTaskFileRegister& PreviousTaskFile, const StorageUtility::Ata::uTaskFileRegister& CurrentTaskFile, std::shared_ptr<cBufferInterface> DataBuffer, U32 TimeoutValueInSeconds ) { m_AtaPassThrough.Length = sizeof( ATA_PASS_THROUGH_DIRECT ); m_AtaPassThrough.DataTransferLength = CommandCharacteristics.DataTransferLengthInBytes; m_AtaPassThrough.TimeOutValue = TimeoutValueInSeconds; if (nullptr != DataBuffer) { m_AtaPassThrough.DataBuffer = DataBuffer->ToDataBuffer(); } m_AtaPassThrough.ReservedAsUchar = 0; m_AtaPassThrough.ReservedAsUlong = 0; InitializeFlags( CommandCharacteristics ); InitializeTaskFileInputRegisters( PreviousTaskFile, CurrentTaskFile ); } void cAtaPassThrough::InitializeFlags( const StorageUtility::Ata::sCommandCharacteristic& AtaCommandCharacteristic ) { // Clear all flags m_AtaPassThrough.AtaFlags = 0; if (StorageUtility::Ata::eDeviceReadyFlag::DEVICE_READY_REQUIRED == AtaCommandCharacteristic.DeviceReadyFlag) { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DRDY_REQUIRED; } switch (AtaCommandCharacteristic.DataAccess) { case StorageUtility::Ata::eDataAccess::READ_FROM_DEVICE: { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DATA_IN; } break; case StorageUtility::Ata::eDataAccess::WRITE_TO_DEVICE: { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DATA_OUT; } break; } if (StorageUtility::Ata::eFieldFormatting::COMMAND_48_BIT == AtaCommandCharacteristic.FieldFormatting) { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_48BIT_COMMAND; } if (StorageUtility::Ata::eTransferMode::DMA_PROTOCOL == AtaCommandCharacteristic.TransferMode) { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_USE_DMA; } if (StorageUtility::Ata::eMultipleMode::NOT_MULTIPLE_COMMAND == AtaCommandCharacteristic.MultipleMode) { m_AtaPassThrough.AtaFlags |= ATA_FLAGS_NO_MULTIPLE; } } void cAtaPassThrough::InitializeTaskFileInputRegisters( const StorageUtility::Ata::uTaskFileRegister& PreviousTaskFile, const StorageUtility::Ata::uTaskFileRegister& CurrentTaskFile ) { m_AtaPassThrough.PreviousTaskFile[FEATURE_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Feature; m_AtaPassThrough.PreviousTaskFile[COUNT_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Count; m_AtaPassThrough.PreviousTaskFile[LBA_LOW_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaLow; m_AtaPassThrough.PreviousTaskFile[LBA_MID_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaMid; m_AtaPassThrough.PreviousTaskFile[LBA_HIGH_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaHigh; m_AtaPassThrough.PreviousTaskFile[DEVICE_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Device; m_AtaPassThrough.PreviousTaskFile[COMMAND_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Command; m_AtaPassThrough.PreviousTaskFile[RESERVED_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Reserved; m_AtaPassThrough.CurrentTaskFile[FEATURE_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Feature; m_AtaPassThrough.CurrentTaskFile[COUNT_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Count; m_AtaPassThrough.CurrentTaskFile[LBA_LOW_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaLow; m_AtaPassThrough.CurrentTaskFile[LBA_MID_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaMid; m_AtaPassThrough.CurrentTaskFile[LBA_HIGH_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaHigh; m_AtaPassThrough.CurrentTaskFile[DEVICE_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Device; m_AtaPassThrough.CurrentTaskFile[COMMAND_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Command; m_AtaPassThrough.CurrentTaskFile[RESERVED_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Reserved; } eErrorCode cAtaPassThrough::IssuePassThroughDirectCommand( U32& BytesReturned ) { assert( INVALID_HANDLE_VALUE != m_DeviceHandle ); eErrorCode error; error = eErrorCode::None; BOOL commandSuccessfulFlag; DWORD bytesReturned; commandSuccessfulFlag = DeviceIoControl ( m_DeviceHandle, IOCTL_ATA_PASS_THROUGH_DIRECT, &m_AtaPassThrough, m_AtaPassThrough.Length, &m_AtaPassThrough, m_AtaPassThrough.Length, &bytesReturned, NULL ); // If the operation was not successful: if (FALSE == commandSuccessfulFlag) { error = eErrorCode::Io; //TODO: report extended error //fprintf( stderr, "\nDeviceIoControl was not successful. Error Code: %d", GetLastError() ); } BytesReturned = bytesReturned; return(error); } } } VT_STOR_ATA_PROTOCOL_API void vtStorProtocolAtaPassThroughInit(std::shared_ptr<vtStor::Protocol::cProtocolInterface>& Protocol) { Protocol = std::make_shared<vtStor::Protocol::cAtaPassThrough>(); }<|endoftext|>
<commit_before>#include "Core\Context.h" #include "Core\Engine.h" using namespace Mile; int main( ) { auto context = std::make_unique<Context>( ); auto engine = new Engine( context.get( ) ); if ( !engine->Init( ) ) { return 1; } int execute = engine->Execute( ); context.reset( ); return execute; }<commit_msg>Fxied Component Register<commit_after>#include "Core\Context.h" #include "Core\Engine.h" #include "Core\World.h" #include "Core\Entity.h" #include "Component\CameraComponent.h" #include "Component\MeshRenderComponent.h" #include "Component\LightComponent.h" #include "Resource\ResourceManager.h" #include "Resource\Model.h" #include "Resource\ModelLoader.h" #include "Resource\Material.h" #include "Resource\Texture2D.h" using namespace Mile; int main( ) { auto context = std::make_unique<Context>( ); auto engine = new Engine( context.get( ) ); if ( !engine->Init( ) ) { return 1; } auto world = context->GetSubSystem<World>( ); auto resMng = context->GetSubSystem<ResourceManager>( ); auto camera = world->CreateEntity( TEXT( "Camera" ) ); auto camComp = camera->AddComponent<CameraComponent>( ); auto camTransform = camera->GetTransform( ); camTransform->SetPosition( Vector3( 0.0f, 0.0f, -100.0f ) ); // Camera setup auto light = world->CreateEntity( TEXT( "DirectionalLight" ) ); auto lightComp = camera->AddComponent<LightComponent>( ); // Light setup auto model = resMng->Load<Model>( TEXT( "Contents/Models/dragon.obj" ) ); auto modelEntity = Model::Instantiate( model, world ); auto modelMeshRenderer = modelEntity->GetComponent<MeshRenderComponent>( ); auto mat = modelMeshRenderer->GetMaterial( ); auto texture = resMng->Load<Texture2D>( TEXT( "Contents/Textures/test.png" ) ); mat->SetDiffuseMap( texture ); // Model setup int execute = engine->Execute( ); SafeDelete( engine ); return execute; }<|endoftext|>
<commit_before>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2016 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "Interface/Thread.h" #include "ThreadPool.h" #include "Server.h" #include "stringtools.h" const unsigned int max_waiting_threads=2; CPoolThread::CPoolThread(CThreadPool *pMgr) { mgr=pMgr; dexit=false; } void CPoolThread::operator()(void) { THREAD_ID tid = Server->getThreadID(); THREADPOOL_TICKET ticket; bool stop=false; std::string name; IThread *tr=mgr->getRunnable(&ticket, false, stop, name); if(tr!=NULL) { if (!name.empty()) { Server->setCurrentThreadName(name); } else { Server->setCurrentThreadName("unnamed"); } (*tr)(); Server->clearDatabases(tid); } if(!stop) { while(dexit==false) { stop=false; std::string name; IThread *tr=mgr->getRunnable(&ticket, true, stop, name); if(tr!=NULL) { if (!name.empty()) { Server->setCurrentThreadName(name); } else { Server->setCurrentThreadName("unnamed"); } (*tr)(); Server->clearDatabases(tid); } else if(stop) { break; } } } Server->destroyDatabases(tid); mgr->Remove(this); delete this; } void CPoolThread::shutdown(void) { dexit=true; } IThread * CThreadPool::getRunnable(THREADPOOL_TICKET *todel, bool del, bool& stop, std::string& name) { IScopedLock lock(mutex); if( del==true ) { --nRunning; std::map<THREADPOOL_TICKET, ICondition *>::iterator it=running.find(*todel); if( it!=running.end() ) { if( it->second!=NULL ) it->second->notify_all(); running.erase(it); } } IThread *ret=NULL; while(ret==NULL && dexit==false) { if( toexecute.size()==0) { if(nThreads-nRunning>max_waiting_threads) { stop=true; return NULL; } Server->setCurrentThreadName("idle pool thread"); cond->wait(&lock); } else { ret=toexecute[0].runnable; *todel=toexecute[0].ticket; name = toexecute[0].name; toexecute.erase( toexecute.begin() ); } } return ret; } void CThreadPool::Remove(CPoolThread *pt) { IScopedLock lock(mutex); for(size_t i=0;i<threads.size();++i) { if( threads[i]==pt ) { threads.erase( threads.begin()+i); --nThreads; return; } } } CThreadPool::CThreadPool() { nRunning=0; nThreads=0; currticket=0; dexit=false; mutex=Server->createMutex(); cond=Server->createCondition(); } CThreadPool::~CThreadPool() { delete mutex; delete cond; } void CThreadPool::Shutdown(void) { bool do_leak_check=(Server->getServerParameter("leak_check")=="true"); IScopedLock lock(mutex); for(size_t i=0;i<threads.size();++i) { threads[i]->shutdown(); } dexit=true; unsigned int max=0; while(threads.size()>0 ) { lock.relock(NULL); cond->notify_all(); Server->wait(100); lock.relock(mutex); //wait for max 300 msec if( (!do_leak_check && max>=3) || (do_leak_check && max>=30) ) { Server->Log("Maximum wait time for thread pool exceeded. Shutting down the hard way", LL_ERROR); break; } ++max; } } bool CThreadPool::isRunningInt(THREADPOOL_TICKET ticket) { std::map<THREADPOOL_TICKET, ICondition*>::iterator it=running.find(ticket); if( it!=running.end() ) return true; else return false; } bool CThreadPool::isRunning(THREADPOOL_TICKET ticket) { IScopedLock lock(mutex); return isRunningInt(ticket); } bool CThreadPool::waitFor(std::vector<THREADPOOL_TICKET> tickets, int timems) { int64 starttime; if(timems>=0) { starttime = Server->getTimeMS(); } IScopedLock lock(mutex); ICondition *cond=Server->createCondition(); for( size_t i=0;i<tickets.size();++i) { std::map<THREADPOOL_TICKET, ICondition*>::iterator it=running.find(tickets[i]); if( it!=running.end() ) { it->second=cond; } } bool ret=false; while(true) { bool r=false; for(size_t i=0;i<tickets.size();++i) { if( isRunningInt(tickets[i]) ) { r=true; break; } } if( r==false ) { ret = true; break; } cond->wait(&lock, timems); if(timems>=0) { int64 ctime = Server->getTimeMS(); if(ctime-starttime>timems) { break; } } } for( size_t i=0;i<tickets.size();++i) { std::map<THREADPOOL_TICKET, ICondition*>::iterator it=running.find(tickets[i]); if( it!=running.end() ) { if(it->second==cond) { it->second=NULL; } } } Server->destroy(cond); return ret; } THREADPOOL_TICKET CThreadPool::execute(IThread *runnable, const std::string& name) { IScopedLock lock(mutex); if( nThreads-nRunning==0 ) { CPoolThread *nt=new CPoolThread(this); Server->createThread(nt); ++nThreads; threads.push_back(nt); } toexecute.push_back(SNewTask(runnable, ++currticket, name)); running.insert(std::pair<THREADPOOL_TICKET, ICondition*>(currticket, (ICondition*)NULL) ); ++nRunning; cond->notify_one(); return currticket; } void CThreadPool::executeWait(IThread *runnable, const std::string& name) { THREADPOOL_TICKET ticket=execute(runnable, name); waitFor(ticket); } bool CThreadPool::waitFor(THREADPOOL_TICKET ticket, int timems) { std::vector<THREADPOOL_TICKET> t; t.push_back(ticket); return waitFor(t, timems); } <commit_msg>Check waitFor timeout before condition wait<commit_after>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2016 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "Interface/Thread.h" #include "ThreadPool.h" #include "Server.h" #include "stringtools.h" const unsigned int max_waiting_threads=2; CPoolThread::CPoolThread(CThreadPool *pMgr) { mgr=pMgr; dexit=false; } void CPoolThread::operator()(void) { THREAD_ID tid = Server->getThreadID(); THREADPOOL_TICKET ticket; bool stop=false; std::string name; IThread *tr=mgr->getRunnable(&ticket, false, stop, name); if(tr!=NULL) { if (!name.empty()) { Server->setCurrentThreadName(name); } else { Server->setCurrentThreadName("unnamed"); } (*tr)(); Server->clearDatabases(tid); } if(!stop) { while(dexit==false) { stop=false; std::string name; IThread *tr=mgr->getRunnable(&ticket, true, stop, name); if(tr!=NULL) { if (!name.empty()) { Server->setCurrentThreadName(name); } else { Server->setCurrentThreadName("unnamed"); } (*tr)(); Server->clearDatabases(tid); } else if(stop) { break; } } } Server->destroyDatabases(tid); mgr->Remove(this); delete this; } void CPoolThread::shutdown(void) { dexit=true; } IThread * CThreadPool::getRunnable(THREADPOOL_TICKET *todel, bool del, bool& stop, std::string& name) { IScopedLock lock(mutex); if( del==true ) { --nRunning; std::map<THREADPOOL_TICKET, ICondition *>::iterator it=running.find(*todel); if( it!=running.end() ) { if( it->second!=NULL ) it->second->notify_all(); running.erase(it); } } IThread *ret=NULL; while(ret==NULL && dexit==false) { if( toexecute.size()==0) { if(nThreads-nRunning>max_waiting_threads) { stop=true; return NULL; } Server->setCurrentThreadName("idle pool thread"); cond->wait(&lock); } else { ret=toexecute[0].runnable; *todel=toexecute[0].ticket; name = toexecute[0].name; toexecute.erase( toexecute.begin() ); } } return ret; } void CThreadPool::Remove(CPoolThread *pt) { IScopedLock lock(mutex); for(size_t i=0;i<threads.size();++i) { if( threads[i]==pt ) { threads.erase( threads.begin()+i); --nThreads; return; } } } CThreadPool::CThreadPool() { nRunning=0; nThreads=0; currticket=0; dexit=false; mutex=Server->createMutex(); cond=Server->createCondition(); } CThreadPool::~CThreadPool() { delete mutex; delete cond; } void CThreadPool::Shutdown(void) { bool do_leak_check=(Server->getServerParameter("leak_check")=="true"); IScopedLock lock(mutex); for(size_t i=0;i<threads.size();++i) { threads[i]->shutdown(); } dexit=true; unsigned int max=0; while(threads.size()>0 ) { lock.relock(NULL); cond->notify_all(); Server->wait(100); lock.relock(mutex); //wait for max 300 msec if( (!do_leak_check && max>=3) || (do_leak_check && max>=30) ) { Server->Log("Maximum wait time for thread pool exceeded. Shutting down the hard way", LL_ERROR); break; } ++max; } } bool CThreadPool::isRunningInt(THREADPOOL_TICKET ticket) { std::map<THREADPOOL_TICKET, ICondition*>::iterator it=running.find(ticket); if( it!=running.end() ) return true; else return false; } bool CThreadPool::isRunning(THREADPOOL_TICKET ticket) { IScopedLock lock(mutex); return isRunningInt(ticket); } bool CThreadPool::waitFor(std::vector<THREADPOOL_TICKET> tickets, int timems) { int64 starttime; if(timems>=0) { starttime = Server->getTimeMS(); } IScopedLock lock(mutex); ICondition *cond=Server->createCondition(); for( size_t i=0;i<tickets.size();++i) { std::map<THREADPOOL_TICKET, ICondition*>::iterator it=running.find(tickets[i]); if( it!=running.end() ) { it->second=cond; } } bool ret=false; while(true) { bool r=false; for(size_t i=0;i<tickets.size();++i) { if( isRunningInt(tickets[i]) ) { r=true; break; } } if( r==false ) { ret = true; break; } if (timems >= 0) { int64 ctime = Server->getTimeMS(); if (ctime - starttime>=timems) { break; } } cond->wait(&lock, timems); } for( size_t i=0;i<tickets.size();++i) { std::map<THREADPOOL_TICKET, ICondition*>::iterator it=running.find(tickets[i]); if( it!=running.end() ) { if(it->second==cond) { it->second=NULL; } } } Server->destroy(cond); return ret; } THREADPOOL_TICKET CThreadPool::execute(IThread *runnable, const std::string& name) { IScopedLock lock(mutex); if( nThreads-nRunning==0 ) { CPoolThread *nt=new CPoolThread(this); Server->createThread(nt); ++nThreads; threads.push_back(nt); } toexecute.push_back(SNewTask(runnable, ++currticket, name)); running.insert(std::pair<THREADPOOL_TICKET, ICondition*>(currticket, (ICondition*)NULL) ); ++nRunning; cond->notify_one(); return currticket; } void CThreadPool::executeWait(IThread *runnable, const std::string& name) { THREADPOOL_TICKET ticket=execute(runnable, name); waitFor(ticket); } bool CThreadPool::waitFor(THREADPOOL_TICKET ticket, int timems) { std::vector<THREADPOOL_TICKET> t; t.push_back(ticket); return waitFor(t, timems); } <|endoftext|>
<commit_before>/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "TiUIPicker.h" #include "TiGenericFunctionObject.h" TiUIPicker::TiUIPicker(NativeObjectFactory* nativeObjectFactory) : TiUIBase(nativeObjectFactory, "") { } TiUIPicker::~TiUIPicker() { } TiUIPicker* TiUIPicker::createPicker(NativeObjectFactory* nativeObjectFactory) { TiUIPicker* obj = new TiUIPicker(nativeObjectFactory); obj->initializeTiObject(NULL); return obj; } void TiUIPicker::initializeTiObject(TiObject* parentContext) { if (!isInitialized()) { TiUIBase::initializeTiObject(parentContext); //currently cascades only supports date/time picker that is why we should create native DateTimePicker object here NativeObject* obj = getNativeObjectFactory()->createNativeObject(N_TYPE_DATE_TIME_PICKER); setNativeObject(obj); obj->release(); } } void TiUIPicker::onCreateStaticMembers() { TiUIBase::onCreateStaticMembers(); } <commit_msg>TIMOB-9876: BlackBerry: Fix build failure Reviewers: JP, David L<commit_after>/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "TiUIPicker.h" #include "TiGenericFunctionObject.h" TiUIPicker::TiUIPicker(NativeObjectFactory* nativeObjectFactory) : TiUIBase("") { } TiUIPicker::~TiUIPicker() { } TiUIPicker* TiUIPicker::createPicker(NativeObjectFactory* nativeObjectFactory) { TiUIPicker* obj = new TiUIPicker(nativeObjectFactory); obj->initializeTiObject(NULL); return obj; } void TiUIPicker::initializeTiObject(TiObject* parentContext) { if (!isInitialized()) { TiUIBase::initializeTiObject(parentContext); //currently cascades only supports date/time picker that is why we should create native DateTimePicker object here NativeObject* obj = getNativeObjectFactory()->createNativeObject(N_TYPE_DATE_TIME_PICKER); setNativeObject(obj); obj->release(); } } void TiUIPicker::onCreateStaticMembers() { TiUIBase::onCreateStaticMembers(); } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include "camera.hpp" #pragma comment(lib,"opencv_world320.lib") static const int N = 256;//文字列の長さ static const int AOV = 62.2;//ANGLE OF VIEW //明度について static const int MAX_VALUE = 255;//明るさ最大 static const int NO_VALUE = 0;//明るさ最小 //時間を元にStringを作る char* makeTimeString(void) { static char timeString[N]; time_t timer;//時刻を受け取る変数 struct tm *timeptr;//日時を集めた構造体ポインタ time(&timer);//現在時刻の取得 timeptr = localtime(&timer);//ポインタ strftime(timeString, N, "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入 return timeString; } char* makeBinaryString(char *timeString) { static char binaryString[N]; sprintf(binaryString, "%s%s",timeString,"Binary"); return binaryString; } //full_pathを作る char* makePath(char* name) { static char full_path[N];//NOTE 自動変数をreturn するために使った. smartなやり方か? char directry_path[] = "/home/pi/Pictures/";//pathの先頭 char file_extention[] = ".jpg";//拡張子 sprintf(full_path, "%s%s%s",directry_path,name,file_extention); return full_path; } //写真をとる int takePhoto(char* name) { char full_command[N]; char front_command[] = "raspistill -o ";//command sprintf(full_command, "%s%s", front_command,name);//コマンドの文字列をつなげる。 system(full_command);//raspistillで静止画を撮って日時を含むファイル名で保存。 printf("%s\n",full_command); //NOTE system関数以外を使うべきか? return 0; } //二値化画像を作成 cv::Mat binarize(cv::Mat src) { cv::Mat hsv; cv::Mat hsv_filtered15 ;//画像の初期化 cv::Mat hsv_filtered180;//画像の初期化 cv::cvtColor(src, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換 //inRange(入力画像,下界画像,上界画像,出力画像) //「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value) cv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15); cv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180); cv::add(hsv_filtered15,hsv_filtered180,hsv); return hsv; } //ノイズ除去 cv::Mat rmNoize(cv::Mat src) { cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理 cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理 cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理 return src; } int saveBinary(cv::Mat src,char* path) { cv::Mat binary_img; cv::resize(src,binary_img,cv::Size(),0.25,0.25); return 0; } //写真を撮り画像処理する cv::Mat Mred(void) { char* stime = makeTimeString(); printf("%s\n",stime); char* sbtime = makeBinaryString(stime); printf("%s\n",sbtime); char* path = makePath(stime); printf("%s\n",path); takePhoto(path); char* bpath = makePath(sbtime); printf("%s\n",path); cv::Mat src = cv::imread(path);//画像の読み込み cv::Mat hsv; hsv = rmNoize(binarize(src)); saveBinary(hsv,bpath); return hsv; } //二値化した画像から1の面積を抽出 double countArea(cv::Mat src) { double Area = src.rows*src.cols;//全ピクセル数 double redCount = 0; //赤色を認識したピクセルの数 redCount = cv::countNonZero(src);//赤色部分の面積を計算 double percentage = 0; //割合 percentage = (redCount / Area)*100;//割合を計算 printf("面積のPercentageは%f\n", percentage); return percentage; } //二値化画像のcenterを角度で返す double getCenter(cv::Mat src) { cv::Moments mu = cv::moments(src, false);//重心の計算結果をmuに代入 double mc = mu.m10 / mu.m00;//重心のx座標 double center = (mc - src.cols / 2) * AOV / src.cols;//正規化 printf("重心の位置は%f\n",center); return center; } <commit_msg>dbeug<commit_after>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include "camera.hpp" #pragma comment(lib,"opencv_world320.lib") static const int N = 256;//文字列の長さ static const int AOV = 62.2;//ANGLE OF VIEW //明度について static const int MAX_VALUE = 255;//明るさ最大 static const int NO_VALUE = 0;//明るさ最小 //時間を元にStringを作る char* makeTimeString(void) { static char timeString[N]; time_t timer;//時刻を受け取る変数 struct tm *timeptr;//日時を集めた構造体ポインタ time(&timer);//現在時刻の取得 timeptr = localtime(&timer);//ポインタ strftime(timeString, N, "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入 return timeString; } char* makeBinaryString(char *timeString) { static char binaryString[N]; sprintf(binaryString, "%s%s",timeString,"Binary"); return binaryString; } //full_pathを作る char* makePath(char* name) { static char full_path[N];//NOTE 自動変数をreturn するために使った. smartなやり方か? char directry_path[] = "/home/pi/Pictures/";//pathの先頭 char file_extention[] = ".jpg";//拡張子 sprintf(full_path, "%s%s%s",directry_path,name,file_extention); return full_path; } //写真をとる int takePhoto(char* name) { char full_command[N]; char front_command[] = "raspistill -o ";//command sprintf(full_command, "%s%s", front_command,name);//コマンドの文字列をつなげる。 system(full_command);//raspistillで静止画を撮って日時を含むファイル名で保存。 printf("%s\n",full_command); //NOTE system関数以外を使うべきか? return 0; } //二値化画像を作成 cv::Mat binarize(cv::Mat src) { cv::Mat hsv; cv::Mat hsv_filtered15 ;//画像の初期化 cv::Mat hsv_filtered180;//画像の初期化 cv::cvtColor(src, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換 //inRange(入力画像,下界画像,上界画像,出力画像) //「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value) cv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15); cv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180); cv::add(hsv_filtered15,hsv_filtered180,hsv); return hsv; } //ノイズ除去 cv::Mat rmNoize(cv::Mat src) { cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理 cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理 cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理 return src; } int saveBinary(cv::Mat src,char* path) { cv::Mat binary_img; cv::resize(src,binary_img,cv::Size(),0.25,0.25); return 0; } //写真を撮り画像処理する cv::Mat Mred(void) { char* stime = makeTimeString(); printf("%s\n",stime); char* sbtime = makeBinaryString(stime); printf("%s\n",sbtime); const char* path = makePath(stime); printf("%s\n",path); takePhoto(path); char* bpath = makePath(sbtime); printf("%s\n",path); cv::Mat src = cv::imread(path);//画像の読み込み cv::Mat hsv; hsv = rmNoize(binarize(src)); saveBinary(hsv,bpath); return hsv; } //二値化した画像から1の面積を抽出 double countArea(cv::Mat src) { double Area = src.rows*src.cols;//全ピクセル数 double redCount = 0; //赤色を認識したピクセルの数 redCount = cv::countNonZero(src);//赤色部分の面積を計算 double percentage = 0; //割合 percentage = (redCount / Area)*100;//割合を計算 printf("面積のPercentageは%f\n", percentage); return percentage; } //二値化画像のcenterを角度で返す double getCenter(cv::Mat src) { cv::Moments mu = cv::moments(src, false);//重心の計算結果をmuに代入 double mc = mu.m10 / mu.m00;//重心のx座標 double center = (mc - src.cols / 2) * AOV / src.cols;//正規化 printf("重心の位置は%f\n",center); return center; } <|endoftext|>
<commit_before>#ifndef TSA_VU8_DETAIL_FROM_V8_HPP #define TSA_VU8_DETAIL_FROM_V8_HPP #include <vu8/detail/ConvertibleString.hpp> #include <v8.h> #include <string> #include <stdexcept> #include <vector> namespace vu8 { namespace detail { typedef v8::Handle<v8::Value> ValueHandle; template <class T> struct FromV8; template <> struct FromV8<std::string> { static inline std::string exec(ValueHandle value) { if (! value->IsString()) throw std::runtime_error("cannot make string from non-string type"); v8::String::Utf8Value str(value); return *str; } }; template <> struct FromV8<ConvertibleString> { static inline ConvertibleString exec(ValueHandle value) { if (! value->IsString()) throw std::runtime_error("cannot make string from non-string type"); v8::String::Utf8Value str(value); return *str; } }; template <> struct FromV8< v8::Handle<v8::Function> > { static inline v8::Handle<v8::Function> exec(ValueHandle value) { if (! value->IsFunction()) throw std::runtime_error("expected javascript function"); return value.As<v8::Function>(); } }; template <> struct FromV8<int32_t> { static inline int32_t exec(ValueHandle value) { if (! value->IsNumber()) throw std::runtime_error("expected javascript number"); return value->ToInt32()->Value(); } }; template <> struct FromV8<uint32_t> { static inline uint32_t exec(ValueHandle value) { if (! value->IsNumber()) throw std::runtime_error("expected javascript number"); return value->ToUint32()->Value(); } }; template <> struct FromV8<int64_t> { static inline int64_t exec(ValueHandle value) { if (! value->IsNumber()) throw std::runtime_error("expected javascript number"); return value->ToNumber()->Value(); } }; template <> struct FromV8<uint64_t> { static inline uint64_t exec(ValueHandle value) { if (! value->IsNumber()) throw std::runtime_error("expected javascript number"); return value->ToNumber()->Value(); } }; template <class T, class A> struct FromV8< std::vector<T, A> > { static inline std::vector<T, A> exec(ValueHandle value) { if (! value->IsArray()) throw std::runtime_error("expected javascript array"); v8::Array *array = v8::Array::Cast(*value); std::vector<T, A> result; for (uint32_t i = 0; i < array->Length(); ++i) { v8::Local<v8::Value> obj = array->Get(i); result.push_back(FromV8<T>::exec(obj)); } return result; } }; template <> struct FromV8<ValueHandle> { static inline ValueHandle exec(ValueHandle value) { return value; } }; } } #endif <commit_msg>can extract object pointers from v8 handles now<commit_after>#ifndef TSA_VU8_DETAIL_FROM_V8_HPP #define TSA_VU8_DETAIL_FROM_V8_HPP #include <vu8/detail/ConvertibleString.hpp> #include <v8.h> #include <string> #include <stdexcept> #include <vector> namespace vu8 { namespace detail { typedef v8::Handle<v8::Value> ValueHandle; template <class T> struct FromV8; template <> struct FromV8<std::string> { static inline std::string exec(ValueHandle value) { if (! value->IsString()) throw std::runtime_error("cannot make string from non-string type"); v8::String::Utf8Value str(value); return *str; } }; template <> struct FromV8<ConvertibleString> { static inline ConvertibleString exec(ValueHandle value) { if (! value->IsString()) throw std::runtime_error("cannot make string from non-string type"); v8::String::Utf8Value str(value); return *str; } }; template <> struct FromV8< v8::Handle<v8::Function> > { static inline v8::Handle<v8::Function> exec(ValueHandle value) { if (! value->IsFunction()) throw std::runtime_error("expected javascript function"); return value.As<v8::Function>(); } }; template <> struct FromV8<int32_t> { static inline int32_t exec(ValueHandle value) { if (! value->IsNumber()) throw std::runtime_error("expected javascript number"); return value->ToInt32()->Value(); } }; template <> struct FromV8<uint32_t> { static inline uint32_t exec(ValueHandle value) { if (! value->IsNumber()) throw std::runtime_error("expected javascript number"); return value->ToUint32()->Value(); } }; template <> struct FromV8<int64_t> { static inline int64_t exec(ValueHandle value) { if (! value->IsNumber()) throw std::runtime_error("expected javascript number"); return value->ToNumber()->Value(); } }; template <> struct FromV8<uint64_t> { static inline uint64_t exec(ValueHandle value) { if (! value->IsNumber()) throw std::runtime_error("expected javascript number"); return value->ToNumber()->Value(); } }; template <class T, class A> struct FromV8< std::vector<T, A> > { static inline std::vector<T, A> exec(ValueHandle value) { if (! value->IsArray()) throw std::runtime_error("expected javascript array"); v8::Array *array = v8::Array::Cast(*value); std::vector<T, A> result; for (uint32_t i = 0; i < array->Length(); ++i) { v8::Local<v8::Value> obj = array->Get(i); result.push_back(FromV8<T>::exec(obj)); } return result; } }; template <> struct FromV8<ValueHandle> { static inline ValueHandle exec(ValueHandle value) { return value; } }; //////////////////////////////////////////////////////////////////////////// // extracting classes template <class T> struct FromV8Ptr { static inline T exec(ValueHandle value) { if (! value->IsObject()) throw std::runtime_error("expected object"); v8::Local<v8::Object> obj = value->ToObject(); if (! obj->InternalFieldCount()) throw std::runtime_error("expected c++ wrapped object"); return static_cast<T>(obj->GetPointerFromInternalField(0)); } }; template <class T> struct FromV8<T *> : FromV8Ptr<T *> {}; template <class T> struct FromV8<T const *> : FromV8Ptr<T const *> {}; } } #endif <|endoftext|>
<commit_before>#include <yuni/yuni.h> #include <yuni/core/noncopyable.h> #include <yuni/io/file.h> #include <yuni/core/system/console.h> #include <yuni/core/getopt.h> #include <yuni/io/directory.h> #include <yuni/io/directory/info.h> #include <yuni/datetime/timestamp.h> #include <yuni/core/logs/logs.h> #include "nany/nany.h" #include <algorithm> #include <yuni/datetime/timestamp.h> #include <iostream> #include <vector> using namespace Yuni; namespace { struct { //! List of filenames to verify std::vector<String> filenames; // no colors bool noColors = false; // Result expected from filename convention bool useFilenameConvention = false; } settings; template<class LeftType = Logs::NullDecorator> struct ParseVerbosity : public LeftType { template<class Handler, class VerbosityType, class O> void internalDecoratorAddPrefix(O& out, const AnyString& s) const { // Write the verbosity to the output if (VerbosityType::hasName) { AnyString name{VerbosityType::Name()}; if (s.empty()) { } else if (name == "info") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::yellow>::Set(out); #ifndef YUNI_OS_WINDOWS out << " \u2713 "; #else out << " > "; #endif if (Handler::colorsAllowed) System::Console::TextColor<System::Console::white>::Set(out); out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else if (name == "error") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::red>::Set(out); out << " FAILED "; if (Handler::colorsAllowed) System::Console::TextColor<System::Console::white>::Set(out); out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else if (name == "warning") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::yellow>::Set(out); out << " {warn} "; if (Handler::colorsAllowed) System::Console::TextColor<System::Console::white>::Set(out); out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else { // Set Color if (Handler::colorsAllowed && VerbosityType::color != System::Console::none) System::Console::TextColor<VerbosityType::color>::Set(out); // The verbosity VerbosityType::AppendName(out); // Reset Color if (Handler::colorsAllowed && VerbosityType::color != System::Console::none) System::Console::ResetTextColor(out); } } // Transmit the message to the next decorator LeftType::template internalDecoratorAddPrefix<Handler, VerbosityType,O>(out, s); } }; // struct VerbosityLevel using Logging = Logs::Logger<Logs::StdCout<>, ParseVerbosity<Logs::Message<>>>; static Logging logs; uint32_t fincCommonFolderLength(const std::vector<String>& filenames) { if (filenames.empty()) return 0; auto& firstElement = filenames[0]; const char sep = IO::Separator; uint32_t pos = 0; for (; ; ++pos) { for (size_t i = 0; i < filenames.size(); ++i) { auto& str = filenames[i]; if (pos == firstElement.size()) return pos; if (pos < str.size() and str[pos] != '\0' and str[pos] == firstElement[pos]) continue; // back to the last sep while (pos > 0 && firstElement[--pos] != sep) { } return pos; } } return pos; } bool expandFilelist(std::vector<String>& list) { std::vector<String> filelist; filelist.reserve(512); String currentfile; currentfile.reserve(4096); for (auto& element: list) { IO::Canonicalize(currentfile, element); switch (IO::TypeOf(currentfile)) { case IO::typeFile: { filelist.emplace_back(currentfile); break; } case IO::typeFolder: { ShortString16 ext; IO::Directory::Info info(currentfile); auto end = info.recursive_file_end(); for (auto i = info.recursive_file_begin(); i != end; ++i) { IO::ExtractExtension(ext, *i); if (ext == ".ny") filelist.emplace_back(i.filename()); } break; } default: { logs.error() << "impossible to find '" << currentfile << "'"; return false; } } } // for beauty in singled-threaded (and to always produce the same output) std::sort(filelist.begin(), filelist.end()); list.swap(filelist); return true; } template<class F> bool IterateThroughAllFiles(const std::vector<String>& filenames, const F& callback) { String currentfile; uint32_t testOK = 0; uint32_t testFAILED = 0; int64_t maxCheckDuration = 0; int64_t startTime = DateTime::NowMilliSeconds(); for (auto& filename: filenames) { int64_t duration = 0; if (callback(filename, duration)) ++testOK; else ++testFAILED; if (duration > maxCheckDuration) maxCheckDuration = duration; } int64_t endTime = DateTime::NowMilliSeconds(); uint32_t total = testOK + testFAILED; if (total > 0) { int64_t duration = (endTime - startTime); String durationStr; durationStr << " (in " << duration << "ms, max: " << maxCheckDuration << "ms)"; if (total > 1) { if (0 != testFAILED) { switch (total) { case 1: logs.warning() << "-- FAILED -- 1 file, +" << testOK << ", -" << testFAILED << durationStr; break; default: logs.warning() << "-- FAILED -- " << total << " files, +" << testOK << ", -" << testFAILED << durationStr; } } else { switch (total) { case 1: logs.info() << "success: 1 file, +" << testOK << ", -0" << durationStr; break; default: logs.info() << "success: " << total << " files, +" << testOK << ", -0" << durationStr; } } } } else logs.warning() << "no input file"; return (0 == testFAILED); } bool batchCheckIfFilenamesConformToGrammar(std::vector<String>& filenames) { if (not expandFilelist(filenames)) return false; auto commonFolder = (filenames.size() > 1 ? fincCommonFolderLength(filenames) : 0); if (0 != commonFolder) ++commonFolder; return IterateThroughAllFiles(filenames, [&](const AnyString& file, int64_t& duration) -> bool { String barefile; IO::ExtractFileName(barefile, file); bool expected = true; bool canfail = false; if (settings.useFilenameConvention) { if (barefile.startsWith("ko-")) expected = false; if (barefile.find("-canfail-") < barefile.size()) canfail = true; } // PARSE int64_t start = DateTime::NowMilliSeconds(); bool success = (nytrue == nytry_parse_file_n(file.c_str(), file.size())); duration = DateTime::NowMilliSeconds() - start; success = (success == expected); if (success and duration < 300) { logs.info() << AnyString{file, commonFolder} << " [" << duration << "ms]"; } else { if (not success) { if (not canfail) logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms]"; else logs.warning() << AnyString{file, commonFolder} << " [" << duration << "ms, can fail]"; } else logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms - time limit reached]"; success = canfail; } return success; }); } } // namespace int main(int argc, char** argv) { // parse the command { // The command line options parser GetOpt::Parser options; // Input files options.add(settings.filenames, 'i', "input", "Input files (or folders)"); options.remainingArguments(settings.filenames); // --no-color options.addFlag(settings.noColors, ' ', "no-color", "Disable color output"); // use filename convention options.addFlag(settings.useFilenameConvention, ' ', "use-filename-convention", "Use the filename to determine if the test should succeed or not (should succeed if starting with 'ok-'"); // version bool optVersion = false; options.addFlag(optVersion, ' ', "version", "Display the version of the compiler and exit"); // Ask to the parser to parse the command line if (not options(argc, argv)) { // The program should not continue here // The user may have requested the help or an error has happened // If an error has happened, the exit status should be different from 0 if (options.errors()) { std::cerr << "Abort due to error\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } if (optVersion) { std::cout << "0.0\n"; return EXIT_SUCCESS; } if (settings.filenames.empty()) { std::cerr << argv[0] << ": no input file\n"; return EXIT_FAILURE; } } // Print AST or check for Nany Grammar bool success = batchCheckIfFilenamesConformToGrammar(settings.filenames); return success ? EXIT_SUCCESS : EXIT_FAILURE; } <commit_msg>check-syntax: remove global variable 'settings'<commit_after>#include <yuni/yuni.h> #include <yuni/core/noncopyable.h> #include <yuni/io/file.h> #include <yuni/core/system/console.h> #include <yuni/core/getopt.h> #include <yuni/io/directory.h> #include <yuni/io/directory/info.h> #include <yuni/datetime/timestamp.h> #include <yuni/core/logs/logs.h> #include "nany/nany.h" #include <algorithm> #include <yuni/datetime/timestamp.h> #include <iostream> #include <vector> using namespace Yuni; namespace { struct Settings { //! List of filenames to verify std::vector<String> filenames; // no colors bool noColors = false; // Result expected from filename convention bool useFilenameConvention = false; }; template<class LeftType = Logs::NullDecorator> struct ParseVerbosity : public LeftType { template<class Handler, class VerbosityType, class O> void internalDecoratorAddPrefix(O& out, const AnyString& s) const { // Write the verbosity to the output if (VerbosityType::hasName) { AnyString name{VerbosityType::Name()}; if (s.empty()) { } else if (name == "info") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::yellow>::Set(out); #ifndef YUNI_OS_WINDOWS out << " \u2713 "; #else out << " > "; #endif if (Handler::colorsAllowed) System::Console::TextColor<System::Console::white>::Set(out); out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else if (name == "error") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::red>::Set(out); out << " FAILED "; if (Handler::colorsAllowed) System::Console::TextColor<System::Console::white>::Set(out); out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else if (name == "warning") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::yellow>::Set(out); out << " {warn} "; if (Handler::colorsAllowed) System::Console::TextColor<System::Console::white>::Set(out); out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else { // Set Color if (Handler::colorsAllowed && VerbosityType::color != System::Console::none) System::Console::TextColor<VerbosityType::color>::Set(out); // The verbosity VerbosityType::AppendName(out); // Reset Color if (Handler::colorsAllowed && VerbosityType::color != System::Console::none) System::Console::ResetTextColor(out); } } // Transmit the message to the next decorator LeftType::template internalDecoratorAddPrefix<Handler, VerbosityType,O>(out, s); } }; // struct VerbosityLevel using Logging = Logs::Logger<Logs::StdCout<>, ParseVerbosity<Logs::Message<>>>; static Logging logs; uint32_t fincCommonFolderLength(const std::vector<String>& filenames) { if (filenames.empty()) return 0; auto& firstElement = filenames[0]; const char sep = IO::Separator; uint32_t pos = 0; for (; ; ++pos) { for (size_t i = 0; i < filenames.size(); ++i) { auto& str = filenames[i]; if (pos == firstElement.size()) return pos; if (pos < str.size() and str[pos] != '\0' and str[pos] == firstElement[pos]) continue; // back to the last sep while (pos > 0 && firstElement[--pos] != sep) { } return pos; } } return pos; } bool expandFilelist(std::vector<String>& list) { std::vector<String> filelist; filelist.reserve(512); String currentfile; currentfile.reserve(4096); for (auto& element: list) { IO::Canonicalize(currentfile, element); switch (IO::TypeOf(currentfile)) { case IO::typeFile: { filelist.emplace_back(currentfile); break; } case IO::typeFolder: { ShortString16 ext; IO::Directory::Info info(currentfile); auto end = info.recursive_file_end(); for (auto i = info.recursive_file_begin(); i != end; ++i) { IO::ExtractExtension(ext, *i); if (ext == ".ny") filelist.emplace_back(i.filename()); } break; } default: { logs.error() << "impossible to find '" << currentfile << "'"; return false; } } } // for beauty in singled-threaded (and to always produce the same output) std::sort(filelist.begin(), filelist.end()); list.swap(filelist); return true; } template<class F> bool IterateThroughAllFiles(const std::vector<String>& filenames, const F& callback) { String currentfile; uint32_t testOK = 0; uint32_t testFAILED = 0; int64_t maxCheckDuration = 0; int64_t startTime = DateTime::NowMilliSeconds(); for (auto& filename: filenames) { int64_t duration = 0; if (callback(filename, duration)) ++testOK; else ++testFAILED; if (duration > maxCheckDuration) maxCheckDuration = duration; } int64_t endTime = DateTime::NowMilliSeconds(); uint32_t total = testOK + testFAILED; if (total > 0) { int64_t duration = (endTime - startTime); String durationStr; durationStr << " (in " << duration << "ms, max: " << maxCheckDuration << "ms)"; if (total > 1) { if (0 != testFAILED) { switch (total) { case 1: logs.warning() << "-- FAILED -- 1 file, +" << testOK << ", -" << testFAILED << durationStr; break; default: logs.warning() << "-- FAILED -- " << total << " files, +" << testOK << ", -" << testFAILED << durationStr; } } else { switch (total) { case 1: logs.info() << "success: 1 file, +" << testOK << ", -0" << durationStr; break; default: logs.info() << "success: " << total << " files, +" << testOK << ", -0" << durationStr; } } } } else logs.warning() << "no input file"; return (0 == testFAILED); } bool batchCheckIfFilenamesConformToGrammar(Settings& settings) { if (not expandFilelist(settings.filenames)) return false; auto commonFolder = (settings.filenames.size() > 1 ? fincCommonFolderLength(settings.filenames) : 0); if (0 != commonFolder) ++commonFolder; return IterateThroughAllFiles(settings.filenames, [&](const AnyString& file, int64_t& duration) -> bool { String barefile; IO::ExtractFileName(barefile, file); bool expected = true; bool canfail = false; if (settings.useFilenameConvention) { if (barefile.startsWith("ko-")) expected = false; if (barefile.find("-canfail-") < barefile.size()) canfail = true; } // PARSE int64_t start = DateTime::NowMilliSeconds(); bool success = (nytrue == nytry_parse_file_n(file.c_str(), file.size())); duration = DateTime::NowMilliSeconds() - start; success = (success == expected); if (success and duration < 300) { logs.info() << AnyString{file, commonFolder} << " [" << duration << "ms]"; } else { if (not success) { if (not canfail) logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms]"; else logs.warning() << AnyString{file, commonFolder} << " [" << duration << "ms, can fail]"; } else logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms - time limit reached]"; success = canfail; } return success; }); } } // namespace int main(int argc, char** argv) { Settings settings; // parse the command { // The command line options parser GetOpt::Parser options; // Input files options.add(settings.filenames, 'i', "input", "Input files (or folders)"); options.remainingArguments(settings.filenames); // --no-color options.addFlag(settings.noColors, ' ', "no-color", "Disable color output"); // use filename convention options.addFlag(settings.useFilenameConvention, ' ', "use-filename-convention", "Use the filename to determine if the test should succeed or not (should succeed if starting with 'ok-'"); // version bool optVersion = false; options.addFlag(optVersion, ' ', "version", "Display the version of the compiler and exit"); // Ask to the parser to parse the command line if (not options(argc, argv)) { // The program should not continue here // The user may have requested the help or an error has happened // If an error has happened, the exit status should be different from 0 if (options.errors()) { std::cerr << "Abort due to error\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } if (optVersion) { std::cout << "0.0\n"; return EXIT_SUCCESS; } if (settings.filenames.empty()) { std::cerr << argv[0] << ": no input file\n"; return EXIT_FAILURE; } } // Print AST or check for Nany Grammar bool success = batchCheckIfFilenamesConformToGrammar(settings); return success ? EXIT_SUCCESS : EXIT_FAILURE; } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/file_system_provider/request_manager.h" #include "base/files/file.h" #include "base/stl_util.h" #include "base/trace_event/trace_event.h" #include "chrome/browser/extensions/window_controller_list.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/common/constants.h" namespace chromeos { namespace file_system_provider { namespace { // Timeout in seconds, before a request is considered as stale and hence // aborted. const int kDefaultTimeout = 10; } // namespace RequestManager::RequestManager( Profile* profile, const std::string& extension_id, NotificationManagerInterface* notification_manager) : profile_(profile), extension_id_(extension_id), notification_manager_(notification_manager), next_id_(1), timeout_(base::TimeDelta::FromSeconds(kDefaultTimeout)), weak_ptr_factory_(this) { } RequestManager::~RequestManager() { // Abort all of the active requests. RequestMap::iterator it = requests_.begin(); while (it != requests_.end()) { const int request_id = it->first; ++it; RejectRequest(request_id, scoped_ptr<RequestValue>(new RequestValue()), base::File::FILE_ERROR_ABORT); } DCHECK_EQ(0u, requests_.size()); STLDeleteValues(&requests_); } int RequestManager::CreateRequest(RequestType type, scoped_ptr<HandlerInterface> handler) { // The request id is unique per request manager, so per service, thereof // per profile. int request_id = next_id_++; // If cycled the int, then signal an error. if (requests_.find(request_id) != requests_.end()) return 0; TRACE_EVENT_ASYNC_BEGIN1("file_system_provider", "RequestManager::Request", request_id, "type", type); Request* request = new Request; request->handler = handler.Pass(); requests_[request_id] = request; ResetTimer(request_id); FOR_EACH_OBSERVER(Observer, observers_, OnRequestCreated(request_id, type)); // Execute the request implementation. In case of an execution failure, // unregister and return 0. This may often happen, eg. if the providing // extension is not listening for the request event being sent. // In such case, we should abort as soon as possible. if (!request->handler->Execute(request_id)) { DestroyRequest(request_id); return 0; } FOR_EACH_OBSERVER(Observer, observers_, OnRequestExecuted(request_id)); return request_id; } base::File::Error RequestManager::FulfillRequest( int request_id, scoped_ptr<RequestValue> response, bool has_more) { CHECK(response.get()); RequestMap::iterator request_it = requests_.find(request_id); if (request_it == requests_.end()) return base::File::FILE_ERROR_NOT_FOUND; FOR_EACH_OBSERVER(Observer, observers_, OnRequestFulfilled(request_id, *response.get(), has_more)); request_it->second->handler->OnSuccess(request_id, response.Pass(), has_more); if (!has_more) { DestroyRequest(request_id); } else { if (notification_manager_) notification_manager_->HideUnresponsiveNotification(request_id); ResetTimer(request_id); } return base::File::FILE_OK; } base::File::Error RequestManager::RejectRequest( int request_id, scoped_ptr<RequestValue> response, base::File::Error error) { CHECK(response.get()); RequestMap::iterator request_it = requests_.find(request_id); if (request_it == requests_.end()) return base::File::FILE_ERROR_NOT_FOUND; FOR_EACH_OBSERVER(Observer, observers_, OnRequestRejected(request_id, *response.get(), error)); request_it->second->handler->OnError(request_id, response.Pass(), error); DestroyRequest(request_id); return base::File::FILE_OK; } void RequestManager::SetTimeoutForTesting(const base::TimeDelta& timeout) { timeout_ = timeout; } std::vector<int> RequestManager::GetActiveRequestIds() const { std::vector<int> result; for (RequestMap::const_iterator request_it = requests_.begin(); request_it != requests_.end(); ++request_it) { result.push_back(request_it->first); } return result; } void RequestManager::AddObserver(Observer* observer) { DCHECK(observer); observers_.AddObserver(observer); } void RequestManager::RemoveObserver(Observer* observer) { DCHECK(observer); observers_.RemoveObserver(observer); } RequestManager::Request::Request() {} RequestManager::Request::~Request() {} void RequestManager::OnRequestTimeout(int request_id) { FOR_EACH_OBSERVER(Observer, observers_, OnRequestTimeouted(request_id)); if (!notification_manager_) { RejectRequest(request_id, scoped_ptr<RequestValue>(new RequestValue()), base::File::FILE_ERROR_ABORT); return; } if (!IsInteractingWithUser()) { notification_manager_->ShowUnresponsiveNotification( request_id, base::Bind(&RequestManager::OnUnresponsiveNotificationResult, weak_ptr_factory_.GetWeakPtr(), request_id)); } else { ResetTimer(request_id); } } void RequestManager::OnUnresponsiveNotificationResult( int request_id, NotificationManagerInterface::NotificationResult result) { RequestMap::iterator request_it = requests_.find(request_id); if (request_it == requests_.end()) return; if (result == NotificationManagerInterface::CONTINUE) { ResetTimer(request_id); return; } RejectRequest(request_id, scoped_ptr<RequestValue>(new RequestValue()), base::File::FILE_ERROR_ABORT); } void RequestManager::ResetTimer(int request_id) { RequestMap::iterator request_it = requests_.find(request_id); if (request_it == requests_.end()) return; request_it->second->timeout_timer.Start( FROM_HERE, timeout_, base::Bind(&RequestManager::OnRequestTimeout, weak_ptr_factory_.GetWeakPtr(), request_id)); } bool RequestManager::IsInteractingWithUser() const { // First try for app windows. If not found, then fall back to browser windows // and tabs. const extensions::AppWindowRegistry* const registry = extensions::AppWindowRegistry::Get(profile_); DCHECK(registry); if (registry->GetCurrentAppWindowForApp(extension_id_)) return true; // This loop is heavy, but it's not called often. Only when a request timeouts // which is at most once every 10 seconds per request (except tests). const extensions::WindowControllerList::ControllerList& windows = extensions::WindowControllerList::GetInstance()->windows(); for (const auto& window : windows) { const TabStripModel* const tabs = window->GetBrowser()->tab_strip_model(); for (int i = 0; i < tabs->count(); ++i) { const content::WebContents* const web_contents = tabs->GetWebContentsAt(i); const GURL& url = web_contents->GetURL(); if (url.scheme() == extensions::kExtensionScheme && url.host() == extension_id_) { return true; } } } return false; } void RequestManager::DestroyRequest(int request_id) { RequestMap::iterator request_it = requests_.find(request_id); if (request_it == requests_.end()) return; delete request_it->second; requests_.erase(request_it); if (notification_manager_) notification_manager_->HideUnresponsiveNotification(request_id); FOR_EACH_OBSERVER(Observer, observers_, OnRequestDestroyed(request_id)); TRACE_EVENT_ASYNC_END0( "file_system_provider", "RequestManager::Request", request_id); } } // namespace file_system_provider } // namespace chromeos <commit_msg>Fix crash when accessing an archive of a deleted file.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/file_system_provider/request_manager.h" #include "base/files/file.h" #include "base/stl_util.h" #include "base/trace_event/trace_event.h" #include "chrome/browser/extensions/window_controller_list.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/common/constants.h" namespace chromeos { namespace file_system_provider { namespace { // Timeout in seconds, before a request is considered as stale and hence // aborted. const int kDefaultTimeout = 10; } // namespace RequestManager::RequestManager( Profile* profile, const std::string& extension_id, NotificationManagerInterface* notification_manager) : profile_(profile), extension_id_(extension_id), notification_manager_(notification_manager), next_id_(1), timeout_(base::TimeDelta::FromSeconds(kDefaultTimeout)), weak_ptr_factory_(this) { } RequestManager::~RequestManager() { // Abort all of the active requests. RequestMap::iterator it = requests_.begin(); while (it != requests_.end()) { const int request_id = it->first; ++it; RejectRequest(request_id, scoped_ptr<RequestValue>(new RequestValue()), base::File::FILE_ERROR_ABORT); } DCHECK_EQ(0u, requests_.size()); STLDeleteValues(&requests_); } int RequestManager::CreateRequest(RequestType type, scoped_ptr<HandlerInterface> handler) { // The request id is unique per request manager, so per service, thereof // per profile. int request_id = next_id_++; // If cycled the int, then signal an error. if (requests_.find(request_id) != requests_.end()) return 0; TRACE_EVENT_ASYNC_BEGIN1("file_system_provider", "RequestManager::Request", request_id, "type", type); Request* request = new Request; request->handler = handler.Pass(); requests_[request_id] = request; ResetTimer(request_id); FOR_EACH_OBSERVER(Observer, observers_, OnRequestCreated(request_id, type)); // Execute the request implementation. In case of an execution failure, // unregister and return 0. This may often happen, eg. if the providing // extension is not listening for the request event being sent. // In such case, we should abort as soon as possible. if (!request->handler->Execute(request_id)) { DestroyRequest(request_id); return 0; } FOR_EACH_OBSERVER(Observer, observers_, OnRequestExecuted(request_id)); return request_id; } base::File::Error RequestManager::FulfillRequest( int request_id, scoped_ptr<RequestValue> response, bool has_more) { CHECK(response.get()); RequestMap::iterator request_it = requests_.find(request_id); if (request_it == requests_.end()) return base::File::FILE_ERROR_NOT_FOUND; FOR_EACH_OBSERVER(Observer, observers_, OnRequestFulfilled(request_id, *response.get(), has_more)); request_it->second->handler->OnSuccess(request_id, response.Pass(), has_more); if (!has_more) { DestroyRequest(request_id); } else { if (notification_manager_) notification_manager_->HideUnresponsiveNotification(request_id); ResetTimer(request_id); } return base::File::FILE_OK; } base::File::Error RequestManager::RejectRequest( int request_id, scoped_ptr<RequestValue> response, base::File::Error error) { CHECK(response.get()); RequestMap::iterator request_it = requests_.find(request_id); if (request_it == requests_.end()) return base::File::FILE_ERROR_NOT_FOUND; FOR_EACH_OBSERVER(Observer, observers_, OnRequestRejected(request_id, *response.get(), error)); request_it->second->handler->OnError(request_id, response.Pass(), error); DestroyRequest(request_id); return base::File::FILE_OK; } void RequestManager::SetTimeoutForTesting(const base::TimeDelta& timeout) { timeout_ = timeout; } std::vector<int> RequestManager::GetActiveRequestIds() const { std::vector<int> result; for (RequestMap::const_iterator request_it = requests_.begin(); request_it != requests_.end(); ++request_it) { result.push_back(request_it->first); } return result; } void RequestManager::AddObserver(Observer* observer) { DCHECK(observer); observers_.AddObserver(observer); } void RequestManager::RemoveObserver(Observer* observer) { DCHECK(observer); observers_.RemoveObserver(observer); } RequestManager::Request::Request() {} RequestManager::Request::~Request() {} void RequestManager::OnRequestTimeout(int request_id) { FOR_EACH_OBSERVER(Observer, observers_, OnRequestTimeouted(request_id)); if (!notification_manager_) { RejectRequest(request_id, scoped_ptr<RequestValue>(new RequestValue()), base::File::FILE_ERROR_ABORT); return; } if (!IsInteractingWithUser()) { notification_manager_->ShowUnresponsiveNotification( request_id, base::Bind(&RequestManager::OnUnresponsiveNotificationResult, weak_ptr_factory_.GetWeakPtr(), request_id)); } else { ResetTimer(request_id); } } void RequestManager::OnUnresponsiveNotificationResult( int request_id, NotificationManagerInterface::NotificationResult result) { RequestMap::iterator request_it = requests_.find(request_id); if (request_it == requests_.end()) return; if (result == NotificationManagerInterface::CONTINUE) { ResetTimer(request_id); return; } RejectRequest(request_id, scoped_ptr<RequestValue>(new RequestValue()), base::File::FILE_ERROR_ABORT); } void RequestManager::ResetTimer(int request_id) { RequestMap::iterator request_it = requests_.find(request_id); if (request_it == requests_.end()) return; request_it->second->timeout_timer.Start( FROM_HERE, timeout_, base::Bind(&RequestManager::OnRequestTimeout, weak_ptr_factory_.GetWeakPtr(), request_id)); } bool RequestManager::IsInteractingWithUser() const { // First try for app windows. If not found, then fall back to browser windows // and tabs. const extensions::AppWindowRegistry* const registry = extensions::AppWindowRegistry::Get(profile_); DCHECK(registry); if (registry->GetCurrentAppWindowForApp(extension_id_)) return true; // This loop is heavy, but it's not called often. Only when a request timeouts // which is at most once every 10 seconds per request (except tests). const extensions::WindowControllerList::ControllerList& windows = extensions::WindowControllerList::GetInstance()->windows(); for (const auto& window : windows) { const Browser* const browser = window->GetBrowser(); if (!browser) continue; const TabStripModel* const tabs = browser->tab_strip_model(); DCHECK(tabs); for (int i = 0; i < tabs->count(); ++i) { const content::WebContents* const web_contents = tabs->GetWebContentsAt(i); const GURL& url = web_contents->GetURL(); if (url.scheme() == extensions::kExtensionScheme && url.host() == extension_id_) { return true; } } } return false; } void RequestManager::DestroyRequest(int request_id) { RequestMap::iterator request_it = requests_.find(request_id); if (request_it == requests_.end()) return; delete request_it->second; requests_.erase(request_it); if (notification_manager_) notification_manager_->HideUnresponsiveNotification(request_id); FOR_EACH_OBSERVER(Observer, observers_, OnRequestDestroyed(request_id)); TRACE_EVENT_ASYNC_END0( "file_system_provider", "RequestManager::Request", request_id); } } // namespace file_system_provider } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/render_view_host_delegate_helper.h" #include <string> #include "base/command_line.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/background_contents_service.h" #include "chrome/browser/character_encoding.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_widget_fullscreen_host.h" #include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/browser/tab_contents/background_contents.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/browser/user_style_sheet_watcher.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" RenderViewHostDelegateViewHelper::RenderViewHostDelegateViewHelper() {} RenderViewHostDelegateViewHelper::~RenderViewHostDelegateViewHelper() {} BackgroundContents* RenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents( int route_id, Profile* profile, SiteInstance* site, const GURL& opener_url, const string16& frame_name) { ExtensionService* extensions_service = profile->GetExtensionService(); if (!opener_url.is_valid() || frame_name.empty() || !extensions_service || !extensions_service->is_ready()) return NULL; // Only hosted apps have web extents, so this ensures that only hosted apps // can create BackgroundContents. We don't have to check for background // permission as that is checked in RenderMessageFilter when the CreateWindow // message is processed. const Extension* extension = extensions_service->GetExtensionByWebExtent(opener_url); if (!extension) return NULL; // Only allow a single background contents per app. if (!profile->GetBackgroundContentsService() || profile->GetBackgroundContentsService()->GetAppBackgroundContents( ASCIIToUTF16(extension->id()))) return NULL; // Ensure that we're trying to open this from the extension's process. ExtensionProcessManager* process_manager = profile->GetExtensionProcessManager(); if (!site->GetProcess() || !process_manager || site->GetProcess() != process_manager->GetExtensionProcess(opener_url)) return NULL; // Passed all the checks, so this should be created as a BackgroundContents. return profile->GetBackgroundContentsService()->CreateBackgroundContents( site, route_id, profile, frame_name, ASCIIToUTF16(extension->id())); } TabContents* RenderViewHostDelegateViewHelper::CreateNewWindow( int route_id, Profile* profile, SiteInstance* site, WebUITypeID webui_type, RenderViewHostDelegate* opener, WindowContainerType window_container_type, const string16& frame_name) { if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) { BackgroundContents* contents = MaybeCreateBackgroundContents( route_id, profile, site, opener->GetURL(), frame_name); if (contents) { pending_contents_[route_id] = contents->render_view_host(); return NULL; } } // Create the new web contents. This will automatically create the new // TabContentsView. In the future, we may want to create the view separately. TabContents* new_contents = new TabContents(profile, site, route_id, opener->GetAsTabContents(), NULL); new_contents->set_opener_web_ui_type(webui_type); TabContentsView* new_view = new_contents->view(); // TODO(brettw) it seems bogus that we have to call this function on the // newly created object and give it one of its own member variables. new_view->CreateViewForWidget(new_contents->render_view_host()); // Save the created window associated with the route so we can show it later. pending_contents_[route_id] = new_contents->render_view_host(); return new_contents; } RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget( int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) { RenderWidgetHost* widget_host = new RenderWidgetHost(process, route_id); RenderWidgetHostView* widget_view = RenderWidgetHostView::CreateViewForWidget(widget_host); // Popups should not get activated. widget_view->set_popup_type(popup_type); // Save the created widget associated with the route so we can show it later. pending_widget_views_[route_id] = widget_view; return widget_view; } RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewFullscreenWidget( int route_id, RenderProcessHost* process) { RenderWidgetFullscreenHost* fullscreen_widget_host = new RenderWidgetFullscreenHost(process, route_id); RenderWidgetHostView* widget_view = RenderWidgetHostView::CreateViewForWidget(fullscreen_widget_host); pending_widget_views_[route_id] = widget_view; return widget_view; } TabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) { PendingContents::iterator iter = pending_contents_.find(route_id); if (iter == pending_contents_.end()) { DCHECK(false); return NULL; } RenderViewHost* new_rvh = iter->second; pending_contents_.erase(route_id); // The renderer crashed or it is a TabContents and has no view. if (!new_rvh->process()->HasConnection() || (new_rvh->delegate()->GetAsTabContents() && !new_rvh->view())) return NULL; // TODO(brettw) this seems bogus to reach into here and initialize the host. new_rvh->Init(); return new_rvh->delegate()->GetAsTabContents(); } RenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget( int route_id) { PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id); if (iter == pending_widget_views_.end()) { DCHECK(false); return NULL; } RenderWidgetHostView* widget_host_view = iter->second; pending_widget_views_.erase(route_id); RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost(); if (!widget_host->process()->HasConnection()) { // The view has gone away or the renderer crashed. Nothing to do. return NULL; } return widget_host_view; } void RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed( RenderWidgetHost* host) { for (PendingWidgetViews::iterator i = pending_widget_views_.begin(); i != pending_widget_views_.end(); ++i) { if (host->view() == i->second) { pending_widget_views_.erase(i); return; } } } bool RenderViewHostDelegateHelper::gpu_enabled_ = true; // static WebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs( Profile* profile, bool is_web_ui) { PrefService* prefs = profile->GetPrefs(); WebPreferences web_prefs; web_prefs.fixed_font_family = UTF8ToUTF16(prefs->GetString(prefs::kWebKitFixedFontFamily)); web_prefs.serif_font_family = UTF8ToUTF16(prefs->GetString(prefs::kWebKitSerifFontFamily)); web_prefs.sans_serif_font_family = UTF8ToUTF16(prefs->GetString(prefs::kWebKitSansSerifFontFamily)); if (prefs->GetBoolean(prefs::kWebKitStandardFontIsSerif)) web_prefs.standard_font_family = web_prefs.serif_font_family; else web_prefs.standard_font_family = web_prefs.sans_serif_font_family; web_prefs.cursive_font_family = UTF8ToUTF16(prefs->GetString(prefs::kWebKitCursiveFontFamily)); web_prefs.fantasy_font_family = UTF8ToUTF16(prefs->GetString(prefs::kWebKitFantasyFontFamily)); web_prefs.default_font_size = prefs->GetInteger(prefs::kWebKitDefaultFontSize); web_prefs.default_fixed_font_size = prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize); web_prefs.minimum_font_size = prefs->GetInteger(prefs::kWebKitMinimumFontSize); web_prefs.minimum_logical_font_size = prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize); web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset); web_prefs.javascript_can_open_windows_automatically = prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically); web_prefs.dom_paste_enabled = prefs->GetBoolean(prefs::kWebKitDomPasteEnabled); web_prefs.shrinks_standalone_images_to_fit = prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit); const DictionaryValue* inspector_settings = prefs->GetDictionary(prefs::kWebKitInspectorSettings); if (inspector_settings) { for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys()); iter != inspector_settings->end_keys(); ++iter) { std::string value; if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value)) web_prefs.inspector_settings.push_back( std::make_pair(*iter, value)); } } web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks); { // Command line switches are used for preferences with no user interface. const CommandLine& command_line = *CommandLine::ForCurrentProcess(); web_prefs.developer_extras_enabled = !command_line.HasSwitch(switches::kDisableDevTools); web_prefs.javascript_enabled = !command_line.HasSwitch(switches::kDisableJavaScript) && prefs->GetBoolean(prefs::kWebKitJavascriptEnabled); web_prefs.web_security_enabled = !command_line.HasSwitch(switches::kDisableWebSecurity) && prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled); web_prefs.plugins_enabled = !command_line.HasSwitch(switches::kDisablePlugins) && prefs->GetBoolean(prefs::kWebKitPluginsEnabled); web_prefs.java_enabled = !command_line.HasSwitch(switches::kDisableJava) && prefs->GetBoolean(prefs::kWebKitJavaEnabled); web_prefs.loads_images_automatically = prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically); web_prefs.uses_page_cache = command_line.HasSwitch(switches::kEnableFastback); web_prefs.remote_fonts_enabled = !command_line.HasSwitch(switches::kDisableRemoteFonts); web_prefs.xss_auditor_enabled = !command_line.HasSwitch(switches::kDisableXSSAuditor); web_prefs.application_cache_enabled = !command_line.HasSwitch(switches::kDisableApplicationCache); web_prefs.local_storage_enabled = !command_line.HasSwitch(switches::kDisableLocalStorage); web_prefs.databases_enabled = !command_line.HasSwitch(switches::kDisableDatabases); web_prefs.webaudio_enabled = command_line.HasSwitch(switches::kEnableWebAudio); web_prefs.experimental_webgl_enabled = gpu_enabled() && !command_line.HasSwitch(switches::kDisable3DAPIs) && !command_line.HasSwitch(switches::kDisableExperimentalWebGL); web_prefs.gl_multisampling_enabled = !command_line.HasSwitch(switches::kDisableGLMultisampling); web_prefs.site_specific_quirks_enabled = !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks); web_prefs.allow_file_access_from_file_urls = command_line.HasSwitch(switches::kAllowFileAccessFromFiles); web_prefs.show_composited_layer_borders = command_line.HasSwitch(switches::kShowCompositedLayerBorders); web_prefs.accelerated_compositing_enabled = gpu_enabled() && !command_line.HasSwitch(switches::kDisableAcceleratedCompositing); web_prefs.accelerated_2d_canvas_enabled = gpu_enabled() && command_line.HasSwitch(switches::kEnableAccelerated2dCanvas); web_prefs.accelerated_layers_enabled = !command_line.HasSwitch(switches::kDisableAcceleratedLayers); web_prefs.composite_to_texture_enabled = command_line.HasSwitch(switches::kEnableCompositeToTexture); web_prefs.accelerated_plugins_enabled = command_line.HasSwitch(switches::kEnableAcceleratedPlugins); web_prefs.accelerated_video_enabled = !command_line.HasSwitch(switches::kDisableAcceleratedVideo); web_prefs.memory_info_enabled = command_line.HasSwitch(switches::kEnableMemoryInfo); web_prefs.hyperlink_auditing_enabled = !command_line.HasSwitch(switches::kNoPings); web_prefs.interactive_form_validation_enabled = !command_line.HasSwitch(switches::kDisableInteractiveFormValidation); // The user stylesheet watcher may not exist in a testing profile. if (profile->GetUserStyleSheetWatcher()) { web_prefs.user_style_sheet_enabled = true; web_prefs.user_style_sheet_location = profile->GetUserStyleSheetWatcher()->user_style_sheet(); } else { web_prefs.user_style_sheet_enabled = false; } } web_prefs.uses_universal_detector = prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector); web_prefs.text_areas_are_resizable = prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable); // Make sure we will set the default_encoding with canonical encoding name. web_prefs.default_encoding = CharacterEncoding::GetCanonicalEncodingNameByAliasName( web_prefs.default_encoding); if (web_prefs.default_encoding.empty()) { prefs->ClearPref(prefs::kDefaultCharset); web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset); } DCHECK(!web_prefs.default_encoding.empty()); if (is_web_ui) { web_prefs.loads_images_automatically = true; web_prefs.javascript_enabled = true; } return web_prefs; } void RenderViewHostDelegateHelper::UpdateInspectorSetting( Profile* profile, const std::string& key, const std::string& value) { DictionaryValue* inspector_settings = profile->GetPrefs()->GetMutableDictionary( prefs::kWebKitInspectorSettings); inspector_settings->SetWithoutPathExpansion(key, Value::CreateStringValue(value)); } void RenderViewHostDelegateHelper::ClearInspectorSettings(Profile* profile) { DictionaryValue* inspector_settings = profile->GetPrefs()->GetMutableDictionary( prefs::kWebKitInspectorSettings); inspector_settings->Clear(); } <commit_msg>Set the standard font from 'serif' family font.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/render_view_host_delegate_helper.h" #include <string> #include "base/command_line.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/background_contents_service.h" #include "chrome/browser/character_encoding.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_widget_fullscreen_host.h" #include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/browser/tab_contents/background_contents.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/browser/user_style_sheet_watcher.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" RenderViewHostDelegateViewHelper::RenderViewHostDelegateViewHelper() {} RenderViewHostDelegateViewHelper::~RenderViewHostDelegateViewHelper() {} BackgroundContents* RenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents( int route_id, Profile* profile, SiteInstance* site, const GURL& opener_url, const string16& frame_name) { ExtensionService* extensions_service = profile->GetExtensionService(); if (!opener_url.is_valid() || frame_name.empty() || !extensions_service || !extensions_service->is_ready()) return NULL; // Only hosted apps have web extents, so this ensures that only hosted apps // can create BackgroundContents. We don't have to check for background // permission as that is checked in RenderMessageFilter when the CreateWindow // message is processed. const Extension* extension = extensions_service->GetExtensionByWebExtent(opener_url); if (!extension) return NULL; // Only allow a single background contents per app. if (!profile->GetBackgroundContentsService() || profile->GetBackgroundContentsService()->GetAppBackgroundContents( ASCIIToUTF16(extension->id()))) return NULL; // Ensure that we're trying to open this from the extension's process. ExtensionProcessManager* process_manager = profile->GetExtensionProcessManager(); if (!site->GetProcess() || !process_manager || site->GetProcess() != process_manager->GetExtensionProcess(opener_url)) return NULL; // Passed all the checks, so this should be created as a BackgroundContents. return profile->GetBackgroundContentsService()->CreateBackgroundContents( site, route_id, profile, frame_name, ASCIIToUTF16(extension->id())); } TabContents* RenderViewHostDelegateViewHelper::CreateNewWindow( int route_id, Profile* profile, SiteInstance* site, WebUITypeID webui_type, RenderViewHostDelegate* opener, WindowContainerType window_container_type, const string16& frame_name) { if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) { BackgroundContents* contents = MaybeCreateBackgroundContents( route_id, profile, site, opener->GetURL(), frame_name); if (contents) { pending_contents_[route_id] = contents->render_view_host(); return NULL; } } // Create the new web contents. This will automatically create the new // TabContentsView. In the future, we may want to create the view separately. TabContents* new_contents = new TabContents(profile, site, route_id, opener->GetAsTabContents(), NULL); new_contents->set_opener_web_ui_type(webui_type); TabContentsView* new_view = new_contents->view(); // TODO(brettw) it seems bogus that we have to call this function on the // newly created object and give it one of its own member variables. new_view->CreateViewForWidget(new_contents->render_view_host()); // Save the created window associated with the route so we can show it later. pending_contents_[route_id] = new_contents->render_view_host(); return new_contents; } RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget( int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) { RenderWidgetHost* widget_host = new RenderWidgetHost(process, route_id); RenderWidgetHostView* widget_view = RenderWidgetHostView::CreateViewForWidget(widget_host); // Popups should not get activated. widget_view->set_popup_type(popup_type); // Save the created widget associated with the route so we can show it later. pending_widget_views_[route_id] = widget_view; return widget_view; } RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewFullscreenWidget( int route_id, RenderProcessHost* process) { RenderWidgetFullscreenHost* fullscreen_widget_host = new RenderWidgetFullscreenHost(process, route_id); RenderWidgetHostView* widget_view = RenderWidgetHostView::CreateViewForWidget(fullscreen_widget_host); pending_widget_views_[route_id] = widget_view; return widget_view; } TabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) { PendingContents::iterator iter = pending_contents_.find(route_id); if (iter == pending_contents_.end()) { DCHECK(false); return NULL; } RenderViewHost* new_rvh = iter->second; pending_contents_.erase(route_id); // The renderer crashed or it is a TabContents and has no view. if (!new_rvh->process()->HasConnection() || (new_rvh->delegate()->GetAsTabContents() && !new_rvh->view())) return NULL; // TODO(brettw) this seems bogus to reach into here and initialize the host. new_rvh->Init(); return new_rvh->delegate()->GetAsTabContents(); } RenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget( int route_id) { PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id); if (iter == pending_widget_views_.end()) { DCHECK(false); return NULL; } RenderWidgetHostView* widget_host_view = iter->second; pending_widget_views_.erase(route_id); RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost(); if (!widget_host->process()->HasConnection()) { // The view has gone away or the renderer crashed. Nothing to do. return NULL; } return widget_host_view; } void RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed( RenderWidgetHost* host) { for (PendingWidgetViews::iterator i = pending_widget_views_.begin(); i != pending_widget_views_.end(); ++i) { if (host->view() == i->second) { pending_widget_views_.erase(i); return; } } } bool RenderViewHostDelegateHelper::gpu_enabled_ = true; // static WebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs( Profile* profile, bool is_web_ui) { PrefService* prefs = profile->GetPrefs(); WebPreferences web_prefs; web_prefs.fixed_font_family = UTF8ToUTF16(prefs->GetString(prefs::kWebKitFixedFontFamily)); web_prefs.serif_font_family = UTF8ToUTF16(prefs->GetString(prefs::kWebKitSerifFontFamily)); web_prefs.sans_serif_font_family = UTF8ToUTF16(prefs->GetString(prefs::kWebKitSansSerifFontFamily)); // TODO(kochi): As we don't have setting UI for kWebKitStandardFontIsSerif, // we always use web_prefs.serif_font_family as a standard font // temporarily for now. Ideally we should have a pref UI for serif/sans // selection as for CJK font sans-serif family font is the default. // See discussion in http://crosbug.com/12311. web_prefs.standard_font_family = web_prefs.serif_font_family; web_prefs.cursive_font_family = UTF8ToUTF16(prefs->GetString(prefs::kWebKitCursiveFontFamily)); web_prefs.fantasy_font_family = UTF8ToUTF16(prefs->GetString(prefs::kWebKitFantasyFontFamily)); web_prefs.default_font_size = prefs->GetInteger(prefs::kWebKitDefaultFontSize); web_prefs.default_fixed_font_size = prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize); web_prefs.minimum_font_size = prefs->GetInteger(prefs::kWebKitMinimumFontSize); web_prefs.minimum_logical_font_size = prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize); web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset); web_prefs.javascript_can_open_windows_automatically = prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically); web_prefs.dom_paste_enabled = prefs->GetBoolean(prefs::kWebKitDomPasteEnabled); web_prefs.shrinks_standalone_images_to_fit = prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit); const DictionaryValue* inspector_settings = prefs->GetDictionary(prefs::kWebKitInspectorSettings); if (inspector_settings) { for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys()); iter != inspector_settings->end_keys(); ++iter) { std::string value; if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value)) web_prefs.inspector_settings.push_back( std::make_pair(*iter, value)); } } web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks); { // Command line switches are used for preferences with no user interface. const CommandLine& command_line = *CommandLine::ForCurrentProcess(); web_prefs.developer_extras_enabled = !command_line.HasSwitch(switches::kDisableDevTools); web_prefs.javascript_enabled = !command_line.HasSwitch(switches::kDisableJavaScript) && prefs->GetBoolean(prefs::kWebKitJavascriptEnabled); web_prefs.web_security_enabled = !command_line.HasSwitch(switches::kDisableWebSecurity) && prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled); web_prefs.plugins_enabled = !command_line.HasSwitch(switches::kDisablePlugins) && prefs->GetBoolean(prefs::kWebKitPluginsEnabled); web_prefs.java_enabled = !command_line.HasSwitch(switches::kDisableJava) && prefs->GetBoolean(prefs::kWebKitJavaEnabled); web_prefs.loads_images_automatically = prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically); web_prefs.uses_page_cache = command_line.HasSwitch(switches::kEnableFastback); web_prefs.remote_fonts_enabled = !command_line.HasSwitch(switches::kDisableRemoteFonts); web_prefs.xss_auditor_enabled = !command_line.HasSwitch(switches::kDisableXSSAuditor); web_prefs.application_cache_enabled = !command_line.HasSwitch(switches::kDisableApplicationCache); web_prefs.local_storage_enabled = !command_line.HasSwitch(switches::kDisableLocalStorage); web_prefs.databases_enabled = !command_line.HasSwitch(switches::kDisableDatabases); web_prefs.webaudio_enabled = command_line.HasSwitch(switches::kEnableWebAudio); web_prefs.experimental_webgl_enabled = gpu_enabled() && !command_line.HasSwitch(switches::kDisable3DAPIs) && !command_line.HasSwitch(switches::kDisableExperimentalWebGL); web_prefs.gl_multisampling_enabled = !command_line.HasSwitch(switches::kDisableGLMultisampling); web_prefs.site_specific_quirks_enabled = !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks); web_prefs.allow_file_access_from_file_urls = command_line.HasSwitch(switches::kAllowFileAccessFromFiles); web_prefs.show_composited_layer_borders = command_line.HasSwitch(switches::kShowCompositedLayerBorders); web_prefs.accelerated_compositing_enabled = gpu_enabled() && !command_line.HasSwitch(switches::kDisableAcceleratedCompositing); web_prefs.accelerated_2d_canvas_enabled = gpu_enabled() && command_line.HasSwitch(switches::kEnableAccelerated2dCanvas); web_prefs.accelerated_layers_enabled = !command_line.HasSwitch(switches::kDisableAcceleratedLayers); web_prefs.composite_to_texture_enabled = command_line.HasSwitch(switches::kEnableCompositeToTexture); web_prefs.accelerated_plugins_enabled = command_line.HasSwitch(switches::kEnableAcceleratedPlugins); web_prefs.accelerated_video_enabled = !command_line.HasSwitch(switches::kDisableAcceleratedVideo); web_prefs.memory_info_enabled = command_line.HasSwitch(switches::kEnableMemoryInfo); web_prefs.hyperlink_auditing_enabled = !command_line.HasSwitch(switches::kNoPings); web_prefs.interactive_form_validation_enabled = !command_line.HasSwitch(switches::kDisableInteractiveFormValidation); // The user stylesheet watcher may not exist in a testing profile. if (profile->GetUserStyleSheetWatcher()) { web_prefs.user_style_sheet_enabled = true; web_prefs.user_style_sheet_location = profile->GetUserStyleSheetWatcher()->user_style_sheet(); } else { web_prefs.user_style_sheet_enabled = false; } } web_prefs.uses_universal_detector = prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector); web_prefs.text_areas_are_resizable = prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable); // Make sure we will set the default_encoding with canonical encoding name. web_prefs.default_encoding = CharacterEncoding::GetCanonicalEncodingNameByAliasName( web_prefs.default_encoding); if (web_prefs.default_encoding.empty()) { prefs->ClearPref(prefs::kDefaultCharset); web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset); } DCHECK(!web_prefs.default_encoding.empty()); if (is_web_ui) { web_prefs.loads_images_automatically = true; web_prefs.javascript_enabled = true; } return web_prefs; } void RenderViewHostDelegateHelper::UpdateInspectorSetting( Profile* profile, const std::string& key, const std::string& value) { DictionaryValue* inspector_settings = profile->GetPrefs()->GetMutableDictionary( prefs::kWebKitInspectorSettings); inspector_settings->SetWithoutPathExpansion(key, Value::CreateStringValue(value)); } void RenderViewHostDelegateHelper::ClearInspectorSettings(Profile* profile) { DictionaryValue* inspector_settings = profile->GetPrefs()->GetMutableDictionary( prefs::kWebKitInspectorSettings); inspector_settings->Clear(); } <|endoftext|>
<commit_before>#ifndef _PITO_INTERCEPTOR_LIB_C_ #define _PITO_INTERCEPTOR_LIB_C_ #include <pito/interceptor/lib/c_traits.hpp> #include <pito/interceptor/SystemCall.hpp> #include <stdlib.h> #include <stdarg.h> #include <fcntl.h> #ifndef PITO_SYSTEM_CALL_BASE #define PITO_SYSTEM_CALL_BASE SystemCallBase #endif #ifndef PITO_JAIL_BASE #define PITO_JAIL_BASE PITO_SYSTEM_CALL_BASE #endif namespace pito { namespace interceptor { using namespace system_call; //////////////////////////////////////////////////////////////////////////////// // security intercepts PITO_SYSTEM_CALL(chmod) PITO_SYSTEM_CALL(fchmod) PITO_SYSTEM_CALL(fchmodat) PITO_SYSTEM_CALL(chown) PITO_SYSTEM_CALL(fchown) PITO_SYSTEM_CALL(fchownat) template <> struct SystemCall<open> : PITO_SYSTEM_CALL_BASE<open> {}; extern "C" { int open(const char *pathname, int flags, ...) { if (flags & O_CREAT) { va_list ap; va_start(ap, flags); mode_t mode = va_arg(ap, int); va_end(ap); return PITO_SUPER(open)(pathname, flags, mode); } else return PITO_SUPER(open)(pathname, flags); } } template <> struct SystemCall<openat> : PITO_SYSTEM_CALL_BASE<openat> {}; extern "C" { int openat(int dirfd, const char *pathname, int flags, ...) { if (flags & O_CREAT) { va_list ap; va_start(ap, flags); mode_t mode = va_arg(ap, int); va_end(ap); return PITO_SUPER(openat)(dirfd, pathname, flags, mode); } else return PITO_SUPER(openat)(dirfd, pathname, flags); } } PITO_SYSTEM_CALL(creat) PITO_SYSTEM_CALL(fopen) PITO_SYSTEM_CALL(lchown) PITO_SYSTEM_CALL(link) PITO_SYSTEM_CALL(linkat) PITO_SYSTEM_CALL(mkdir) PITO_SYSTEM_CALL(mkdirat) PITO_SYSTEM_CALL(opendir) PITO_SYSTEM_CALL(mknod) PITO_SYSTEM_CALL(mknodat) // function todo: __xmknod PITO_SYSTEM_CALL(mkfifo) PITO_SYSTEM_CALL(mkfifoat) PITO_SYSTEM_CALL(access) PITO_SYSTEM_CALL(faccessat) PITO_SYSTEM_CALL(rename) PITO_SYSTEM_CALL(renameat) PITO_SYSTEM_CALL(rmdir) PITO_SYSTEM_CALL(symlink) PITO_SYSTEM_CALL(symlinkat) PITO_SYSTEM_CALL(truncate) PITO_SYSTEM_CALL(unlink) PITO_SYSTEM_CALL(unlinkat) PITO_SYSTEM_CALL(getcwd) template <> struct SystemCall<open64> : PITO_SYSTEM_CALL_BASE<open64> {}; extern "C" { int open64(const char *pathname, int flags, ...) { if (flags & O_CREAT) { va_list ap; va_start(ap, flags); mode_t mode = va_arg(ap, int); va_end(ap); return PITO_SUPER(open64)(pathname, flags, mode); } else return PITO_SUPER(open64)(pathname, flags); } } template <> struct SystemCall<openat64> : PITO_SYSTEM_CALL_BASE<openat64> {}; extern "C" { int openat64(RBUTIL_ARGS_3(SystemCall<openat64>::arg_types), ...) { if (arg2 & O_CREAT) { va_list ap; va_start(ap, arg2); mode_t mode = va_arg(ap, int); va_end(ap); return PITO_SUPER(openat64)(arg0, arg1, arg2, mode); } else return PITO_SUPER(openat64)(arg0, arg1, arg2); } } PITO_SYSTEM_CALL(creat64) PITO_SYSTEM_CALL(fopen64) PITO_SYSTEM_CALL(truncate64) //////////////////////////////////////////////////////////////////////////////// // jail //////////////////////////////////////////////////////////////////////////////// PITO_SYSTEM_CALL_WITH_BASE(execve, PITO_JAIL_BASE) PITO_SYSTEM_CALL_WITH_BASE(execv, PITO_JAIL_BASE) PITO_SYSTEM_CALL_WITH_BASE(execvp, PITO_JAIL_BASE) //////////////////////////////////////////////////////////////////////////////// // end jail //////////////////////////////////////////////////////////////////////////////// PITO_SYSTEM_CALL(utime) PITO_SYSTEM_CALL(utimes) PITO_SYSTEM_CALL(utimensat) PITO_SYSTEM_CALL(futimesat) PITO_SYSTEM_CALL(lutimes) PITO_SYSTEM_CALL(getuid) } } #endif <commit_msg>remove some code innit<commit_after>#ifndef _PITO_INTERCEPTOR_LIB_C_ #define _PITO_INTERCEPTOR_LIB_C_ #include <pito/interceptor/lib/c_traits.hpp> #include <pito/interceptor/SystemCall.hpp> #include <stdlib.h> #include <stdarg.h> #include <fcntl.h> #ifndef PITO_SYSTEM_CALL_BASE #define PITO_SYSTEM_CALL_BASE SystemCallBase #endif #ifndef PITO_JAIL_BASE #define PITO_JAIL_BASE PITO_SYSTEM_CALL_BASE #endif namespace pito { namespace interceptor { using namespace system_call; //////////////////////////////////////////////////////////////////////////////// // security intercepts PITO_SYSTEM_CALL(chmod) PITO_SYSTEM_CALL(fchmod) PITO_SYSTEM_CALL(fchmodat) PITO_SYSTEM_CALL(chown) PITO_SYSTEM_CALL(fchown) PITO_SYSTEM_CALL(fchownat) template <> struct SystemCall<open> : PITO_SYSTEM_CALL_BASE<open> {}; extern "C" { int open(PITO_ARGS(open), ...) { if (arg1 & O_CREAT) { va_list ap; va_start(ap, arg1); mode_t mode = va_arg(ap, int); va_end(ap); return PITO_SUPER(open)(arg0, arg1, mode); } else return PITO_SUPER(open)(arg0, arg1); } } template <> struct SystemCall<openat> : PITO_SYSTEM_CALL_BASE<openat> {}; extern "C" { int openat(PITO_ARGS(openat), ...) { if (arg2 & O_CREAT) { va_list ap; va_start(ap, arg2); mode_t mode = va_arg(ap, int); va_end(ap); return PITO_SUPER(openat)(arg0, arg1, arg2, mode); } else return PITO_SUPER(openat)(arg0, arg1, arg2); } } PITO_SYSTEM_CALL(creat) PITO_SYSTEM_CALL(fopen) PITO_SYSTEM_CALL(lchown) PITO_SYSTEM_CALL(link) PITO_SYSTEM_CALL(linkat) PITO_SYSTEM_CALL(mkdir) PITO_SYSTEM_CALL(mkdirat) PITO_SYSTEM_CALL(opendir) PITO_SYSTEM_CALL(mknod) PITO_SYSTEM_CALL(mknodat) // function todo: __xmknod PITO_SYSTEM_CALL(mkfifo) PITO_SYSTEM_CALL(mkfifoat) PITO_SYSTEM_CALL(access) PITO_SYSTEM_CALL(faccessat) PITO_SYSTEM_CALL(rename) PITO_SYSTEM_CALL(renameat) PITO_SYSTEM_CALL(rmdir) PITO_SYSTEM_CALL(symlink) PITO_SYSTEM_CALL(symlinkat) PITO_SYSTEM_CALL(truncate) PITO_SYSTEM_CALL(unlink) PITO_SYSTEM_CALL(unlinkat) PITO_SYSTEM_CALL(getcwd) template <> struct SystemCall<open64> : PITO_SYSTEM_CALL_BASE<open64> {}; extern "C" { int open64(PITO_ARGS(open64), ...) { if (arg1 & O_CREAT) { va_list ap; va_start(ap, arg1); mode_t mode = va_arg(ap, int); va_end(ap); return PITO_SUPER(open64)(arg0, arg1, mode); } else return PITO_SUPER(open64)(arg0, arg1); } } template <> struct SystemCall<openat64> : PITO_SYSTEM_CALL_BASE<openat64> {}; extern "C" { int openat64(PITO_ARGS(openat64), ...) { if (arg2 & O_CREAT) { va_list ap; va_start(ap, arg2); mode_t mode = va_arg(ap, int); va_end(ap); return PITO_SUPER(openat64)(arg0, arg1, arg2, mode); } else return PITO_SUPER(openat64)(arg0, arg1, arg2); } } PITO_SYSTEM_CALL(creat64) PITO_SYSTEM_CALL(fopen64) PITO_SYSTEM_CALL(truncate64) //////////////////////////////////////////////////////////////////////////////// // jail //////////////////////////////////////////////////////////////////////////////// PITO_SYSTEM_CALL_WITH_BASE(execve, PITO_JAIL_BASE) PITO_SYSTEM_CALL_WITH_BASE(execv, PITO_JAIL_BASE) PITO_SYSTEM_CALL_WITH_BASE(execvp, PITO_JAIL_BASE) //////////////////////////////////////////////////////////////////////////////// // end jail //////////////////////////////////////////////////////////////////////////////// PITO_SYSTEM_CALL(utime) PITO_SYSTEM_CALL(utimes) PITO_SYSTEM_CALL(utimensat) PITO_SYSTEM_CALL(futimesat) PITO_SYSTEM_CALL(lutimes) PITO_SYSTEM_CALL(getuid) } } #endif <|endoftext|>